add shorthand functions to set/add classes and set IDs on elements
[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 (preg_match('/^\s*function\s+{(.*)}\s*$/is', $this->config_raw['update'], $regs)) {
330 $upfunc = create_function('', $regs[1]);
331 $upvals = $upfunc();
332 }
333 else {
334 $evalcode = $this->config_raw['update'];
335 if (!is_null($evalcode)) {
336 ob_start();
337 eval($evalcode);
338 $ret = ob_get_contents();
339 if (strlen($ret)) { $upvals = explode("\n", $ret); }
340 ob_end_clean();
341 }
342 }
343 }
344 else {
345 foreach ($this->rrd_fields as $ds) {
346 if (is_array($upArray) && isset($upArray[$ds['name']])) { $val = $upArray[$ds['name']]; }
347 elseif (isset($ds['update'])) {
348 $val = null; $evalcode = null;
349 if (substr($ds['update'], 0, 4) == 'val:') {
350 $evalcode = 'function { return trim('.substr($ds['update'], 4).')); }';
351 }
352 elseif (substr($ds['update'], 0, 8) == 'snmp-if:') {
353 if (substr_count($ds['update'], ':') >= 4) {
354 list($nix, $snmphost, $snmpcomm, $ifname, $valtype) = explode(':', $ds['update'], 5);
355 }
356 else {
357 $snmphost = 'localhost'; $snmpcomm = 'public';
358 list($nix, $ifname, $valtype) = explode(':', $ds['update'], 3);
359 }
360 $iflist = explode("\n", `snmpwalk -v2c -c $snmpcomm $snmphost interfaces.ifTable.ifEntry.ifDescr`);
361 $ifnr = null;
362 foreach ($iflist as $ifdesc) {
363 if (preg_match('/ifDescr\.(\d+) = STRING: '.$ifname.'/', $ifdesc, $regs)) { $ifnr = $regs[1]; }
364 }
365 $oid = null;
366 if ($valtype == 'in') { $oid = '1.3.6.1.2.1.2.2.1.10.'.$ifnr; }
367 elseif ($valtype == 'out') { $oid = '1.3.6.1.2.1.2.2.1.16.'.$ifnr; }
368 if (!is_null($ifnr) && !is_null($oid)) {
369 $evalcode = 'function { return trim(substr(strrchr(`snmpget -v2c -c '.$snmpcomm.' '.$snmphost.' '.$oid.'`,":"),1)); }';
370 }
371 }
372 else { $evalcode = $ds['update']; }
373 if (preg_match('/^\s*function\s+{(.*)}\s*$/is', $evalcode, $regs)) {
374 $upfunc = create_function('', $regs[1]);
375 $val = $upfunc();
376 }
377 elseif (!is_null($evalcode)) {
378 ob_start();
379 eval($evalcode);
380 $val = ob_get_contents();
381 ob_end_clean();
382 }
383 }
384 else { $val = null; }
385 $upvals[$ds['name']] = $val;
386 }
387 }
388 $upval_keys = array_keys($upvals);
389 $keys_have_names = !is_numeric(array_shift($upval_keys));
390 if (in_array('L', $upvals, true)) {
391 // for at least one value, we need to set the same as the last recorded value
392 $fvals = $this->fetch();
393 $rowids = array_shift($fvals);
394 $lastvals = array_shift($fvals);
395 foreach (array_keys($upvals, 'L') as $akey) {
396 $upvals[$akey] = $keys_have_names?$lastvals[$akey]:$lastvals[$rowids[$akey]];
397 }
398 }
399 $walkfunc = create_function('&$val,$key', '$val = is_numeric(trim($val))?trim($val):"U";');
400 array_walk($upvals, $walkfunc);
401 $return = null;
402 if (count($upvals)) {
403 $update_cmd = $this->rrdtool_bin.' update '.$this->rrd_file
404 .($keys_have_names?' --template '.implode(':', array_keys($upvals)):'').' N:'.implode(':', $upvals);
405 $return = `$update_cmd 2>&1`;
406 }
407
408 if (strpos($return, 'ERROR') !== false) {
409 trigger_error($this->rrd_file.' - rrd update error: '.$return, E_USER_WARNING);
410 $success = false;
411 }
412 else { $success = true; }
413 return $success;
414 }
415
416 public function fetch($cf = 'AVERAGE', $resolution = null, $start = null, $end = null) {
417 // fetch data from a RRD
418 if (!in_array($this->status, array('ok','readonly'))) {
419 trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false;
420 }
421
422 if (!in_array($cf, array('AVERAGE','MIN','MAX','LAST'))) { $cf = 'AVERAGE'; }
423 if (!is_numeric($resolution)) { $resolution = $this->rrd_step; }
424 if (!is_numeric($end)) { $end = $this->last_update(); }
425 elseif ($end < 0) { $end += $this->last_update(); }
426 $end = intval($end/$resolution)*$resolution;
427 if (!is_numeric($start)) { $start = $end-$resolution; }
428 elseif ($start < 0) { $start += $end; }
429 $start = intval($start/$resolution)*$resolution;
430
431 $fetch_cmd = 'LANG=C '.$this->rrdtool_bin.' fetch '.$this->rrd_file.' '.$cf.' --resolution '.$resolution
432 .' --start '.$start.' --end '.$end;
433 $return = `$fetch_cmd 2>&1`;
434
435 if (strpos($return, 'ERROR') !== false) {
436 trigger_error($this->rrd_file.' - rrd fetch error: '.$return, E_USER_WARNING);
437 $fresult = false;
438 }
439 else {
440 $fresult = array();
441 $rows = explode("\n", $return);
442 $fields = preg_split('/\s+/', array_shift($rows));
443 if (in_array(array_shift($fields), array('timestamp', ''))) {
444 //$fresult[0] = $fields;
445 foreach ($rows as $row) {
446 if (strlen(trim($row))) {
447 $rvals = preg_split('/\s+/', $row);
448 $rtime = str_replace(':', '', array_shift($rvals));
449 $rv_array = array();
450 foreach ($rvals as $key=>$rval) {
451 $rv_array[$fields[$key]] = ($rval=='nan')?null:floatval($rval);
452 }
453 $fresult[$rtime] = $rv_array;
454 }
455 }
456 }
457 }
458 return $fresult;
459 }
460
461 public function last_update() {
462 // fetch time of last update in this RRD file
463 static $last_update, $last_saved;
464 if (isset($last_update) && isset($last_saved) && ($last_saved <= (time() - 10))) { unset($last_update); }
465 if (!isset($last_update) && in_array($this->status, array('ok','readonly'))) {
466 $last_cmd = $this->rrdtool_bin.' last '.$this->rrd_file;
467 $return = trim(`$last_cmd 2>&1`);
468 $last_update = is_numeric($return)?$return:null;
469 $last_saved = time();
470 }
471 return isset($last_update)?$last_update:null;
472 }
473
474 public function graph($timeframe = 'day', $sub = null, $extra = null) {
475 // create a RRD graph
476 static $gColors;
477 if (!isset($gColors)) {
478 $gColors = array('#00CC00','#0000FF','#000000','#FF0000','#00FF00','#FFFF00','#FF00FF','#00FFFF',
479 '#808080','#800000','#008000','#000080','#808000','#800080','#008080','#C0C0C0');
480 }
481
482 if (!in_array($this->status, array('ok','readonly','graphonly'))) {
483 trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false;
484 }
485
486 // assemble configuration
487 $gconf = (array)$extra;
488 if (!is_null($sub) && is_array($this->config_raw['graph.'.$sub])) {
489 $gconf = $gconf + $this->config_raw['graph.'.$sub];
490 }
491 $gconf = $gconf + (array)$this->config_graph;
492
493 if (isset($gconf['format']) && ($gconf['format'] == 'SVG')) {
494 $format = $gconf['format']; $fmt_ext = '.svg';
495 }
496 elseif (isset($gconf['format']) && ($gconf['format'] == 'EPS')) {
497 $format = $gconf['format']; $fmt_ext = '.eps';
498 }
499 elseif (isset($gconf['format']) && ($gconf['format'] == 'PDF')) {
500 $format = $gconf['format']; $fmt_ext = '.pdf';
501 }
502 else {
503 $format = 'PNG'; $fmt_ext = '.png';
504 }
505
506 if (isset($gconf['filename'])) { $fname = $gconf['filename']; }
507 else { $fname = $this->basename.(is_null($sub)?'':'-%s').'-%t%f'; }
508 $fname = str_replace('%s', strval($sub), $fname);
509 $fname = str_replace('%t', $timeframe, $fname);
510 $fname = str_replace('%f', $fmt_ext, $fname);
511 if (substr($fname, -strlen($fmt_ext)) != $fmt_ext) { $fname .= $fmt_ext; }
512 if (isset($gconf['path']) && ($fname{0} != '/')) { $fname = $gconf['path'].'/'.$fname; }
513 if ($fname{0} != '/') { $fname = $this->basedir.$fname; }
514 $fname = str_replace('//', '/', $fname);
515
516 $graphrows = array(); $specialrows = array(); $gC = 0;
517 $gDefs = ''; $gGraphs = ''; $addSpecial = '';
518
519 // the default size for the graph area has a width of 400px, so use 400 slices by default
520 if ($timeframe == 'day') {
521 $slice = isset($gconf['slice'])?$gconf['slice']:300; // 5 minutes
522 $duration = isset($gconf['duration'])?$gconf['duration']:400*$slice; // 33.33 hours
523 // vertical lines at day borders
524 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d')).'#FF0000';
525 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' -1 day').'#FF0000';
526 if (!isset($gconf['grid_x'])) { $gconf['grid_x'] = 'HOUR:1:HOUR:6:HOUR:2:0:%-H'; }
527 }
528 elseif ($timeframe == 'week') {
529 $slice = isset($gconf['slice'])?$gconf['slice']:1800; // 30 minutes
530 $duration = isset($gconf['duration'])?$gconf['duration']:400*$slice; // 8.33 days
531 // vertical lines at week borders
532 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')+1).' day').'#FF0000';
533 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')-6).' day').'#FF0000';
534 }
535 elseif ($timeframe == 'month') {
536 $slice = isset($gconf['slice'])?$gconf['slice']:7200; // 2 hours
537 $duration = isset($gconf['duration'])?$gconf['duration']:400*$slice; // 33.33 days
538 // vertical lines at month borders
539 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01')).'#FF0000';
540 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01').' -1 month').'#FF0000';
541 }
542 elseif ($timeframe == 'year') {
543 $slice = isset($gconf['slice'])?$gconf['slice']:86400; // 1 day
544 $duration = isset($gconf['duration'])?$gconf['duration']:400*$slice; // 400 days
545 // vertical lines at month borders
546 $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00')).'#FF0000';
547 $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00').' -1 year').'#FF0000';
548 }
549 else {
550 $duration = isset($gconf['duration'])?$gconf['duration']:$this->rrd_step*500; // 500 steps
551 $slice = isset($gconf['slice'])?$gconf['slice']:$this->rrd_step; // whatever our step is
552 }
553
554 $use_gcrows = (isset($gconf['rows']) && count($gconf['rows']));
555 if ($use_gcrows) { $grow_def =& $gconf['rows']; }
556 else { $grow_def =& $this->rrd_fields; }
557 foreach ($grow_def as $key=>$erow) {
558 if (isset($erow['name']) && strlen($erow['name'])) {
559 if (!isset($erow['scale']) && isset($gconf['scale'])) { $erow['scale'] = $gconf['scale']; }
560 if (!isset($erow['scale_time_src']) && isset($gconf['scale_time_src'])) {
561 $erow['scale_time_src'] = $gconf['scale_time_src'];
562 }
563 if (!isset($erow['scale_time_tgt']) && isset($gconf['scale_time_tgt'])) {
564 $erow['scale_time_tgt'] = $gconf['scale_time_tgt'];
565 }
566 foreach (array('scale_time_src','scale_time_tgt') as $st) {
567 if (!isset($erow[$st]) || !is_numeric($erow[$st])) {
568 switch (@$erow[$st]) {
569 case 'dyn':
570 case 'auto':
571 $erow[$st] = $slice;
572 break;
573 case 'day':
574 $erow[$st] = 24*3600;
575 break;
576 case '2hr':
577 case '2hours':
578 $erow[$st] = 7200;
579 break;
580 case 'hr':
581 case 'hour':
582 $erow[$st] = 3600;
583 break;
584 case '30min':
585 $erow[$st] = 1800;
586 break;
587 case '5min':
588 $erow[$st] = 300;
589 break;
590 case 'min':
591 $erow[$st] = 60;
592 break;
593 case 's':
594 case 'sec':
595 default:
596 $erow[$st] = 1;
597 break;
598 }
599 }
600 }
601 $scale_time_factor = $erow['scale_time_tgt']/$erow['scale_time_src'];
602 if ($scale_time_factor != 1) { $erow['scale'] = (isset($erow['scale'])?$erow['scale']:1)*$scale_time_factor; }
603 $grow = array();
604 $grow['dType'] = ($use_gcrows && isset($erow['dType']))?$erow['dType']:'DEF';
605 $grow['name'] = $erow['name'].(isset($erow['scale'])?'_tmp':'');
606 if ($grow['dType'] == 'DEF') {
607 $grow['dsname'] = ($use_gcrows && isset($erow['dsname']))?$erow['dsname']:$erow['name'];
608 if ($use_gcrows && isset($erow['dsfile'])) { $grow['dsfile'] = $erow['dsfile']; }
609 $grow['cf'] = ($use_gcrows && isset($erow['cf']))?$erow['cf']:'AVERAGE';
610 }
611 else {
612 $grow['rpn_expr'] = isset($erow['rpn_expr'])?$erow['rpn_expr']:'0';
613 }
614 if (isset($erow['scale'])) {
615 $graphrows[] = $grow;
616 $grow = array();
617 $grow['dType'] = 'CDEF';
618 $grow['name'] = $erow['name'];
619 $grow['rpn_expr'] = $erow['name'].'_tmp,'.sprintf('%F', $erow['scale']).',*';
620 }
621 if ($use_gcrows) { $grow['gType'] = isset($erow['gType'])?$erow['gType']:'LINE1'; }
622 else { $grow['gType'] = ((count($grow_def)==2) && ($key==0))?'AREA':'LINE1'; }
623 $grow['color'] = isset($erow['color'])?$erow['color']:$gColors[$gC++];
624 $grow['color_bg'] = isset($erow['color_bg'])?$erow['color_bg']:'';
625 if ($gC >= count($gColors)) { $gC = 0; }
626 if (isset($erow['legend'])) {
627 $grow['legend'] = $erow['legend'];
628 if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
629 }
630 if (isset($erow['stack'])) { $grow['stack'] = ($erow['stack'] == true); }
631 if (isset($erow['desc'])) { $grow['desc'] = $erow['desc']; }
632 if (isset($erow['legend_long'])) { $grow['legend_long'] = $erow['legend_long']; }
633 $graphrows[] = $grow;
634 }
635 }
636
637 if (isset($gconf['special']) && count($gconf['special'])) {
638 foreach ($gconf['special'] as $crow) {
639 $srow = array();
640 $srow['sType'] = isset($crow['sType'])?$crow['sType']:'COMMENT';
641 if ($grow['sType'] != 'COMMENT') {
642 // XXX: use line below and remove cf var once we have rrdtol 1.2
643 if ($this->rrd_version() >= '1.2') {
644 $srow['name'] = $crow['name'].(isset($crow['cf'])?'_'.$crow['cf']:'');
645 }
646 else {
647 $srow['name'] = $crow['name'];
648 $srow['cf'] = isset($crow['cf'])?$crow['cf']:'AVERAGE';
649 }
650 if (isset($crow['cf'])) {
651 if ($this->rrd_version() >= '1.2') {
652 $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'].'_'.$crow['cf'],
653 'rpn_expr'=>$srow['name'].','.$crow['cf']);
654 }
655 }
656 elseif (isset($crow['rpn_expr'])) {
657 if ($this->rrd_version() >= '1.2') {
658 $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'], 'rpn_expr'=>$crow['rpn_expr']);
659 }
660 }
661 }
662 $srow['text'] = isset($crow['text'])?$crow['text']:'';
663 $specialrows[] = $srow;
664 }
665 }
666 else {
667 $td = $this->mod_textdomain;
668 foreach ($graphrows as $grow) {
669 if (isset($grow['gType']) && strlen($grow['gType'])) {
670 $textprefix = isset($grow['desc'])?$grow['desc']:(isset($grow['legend'])?$grow['legend']:$grow['name']);
671 if ($this->rrd_version() >= '1.2') {
672 $graphrows[] = array('dType'=>'VDEF', 'name'=>'_'.$grow['name'].'__max', 'rpn_expr'=>$grow['name'].',MAXIMUM');
673 $specialrows[] = array('sType'=>'PRINT', 'name'=>'_'.$grow['name'].'__max',
674 'text'=>$textprefix.'|'.dgettext($td, 'Maximum').'|%.2lf%s');
675 $graphrows[] = array('dType'=>'VDEF', 'name'=>'_'.$grow['name'].'__avg', 'rpn_expr'=>$grow['name'].',AVERAGE');
676 $specialrows[] = array('sType'=>'PRINT', 'name'=>'_'.$grow['name'].'__avg',
677 'text'=>$textprefix.'|'.dgettext($td, 'Average').'|%.2lf%s');
678 $graphrows[] = array('dType'=>'VDEF', 'name'=>'_'.$grow['name'].'__last', 'rpn_expr'=>$grow['name'].',LAST');
679 $specialrows[] = array('sType'=>'PRINT', 'name'=>'_'.$grow['name'].'__last',
680 'text'=>$textprefix.'|'.dgettext($td, 'Current').'|%.2lf%s');
681 }
682 else {
683 $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'MAX',
684 'text'=>$textprefix.'|'.dgettext($td, 'Maximum').'|%.2lf%s');
685 $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'AVERAGE',
686 'text'=>$textprefix.'|'.dgettext($td, 'Average').'|%.2lf%s');
687 $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'LAST',
688 'text'=>$textprefix.'|'.dgettext($td, 'Current').'|%.2lf%s');
689 }
690 }
691 }
692 }
693
694 $endtime = isset($gconf['time_end'])?$gconf['time_end']:(is_numeric($this->last_update())?$this->last_update():time());
695 $gOpts = ' --start '.($endtime-$duration).' --end '.$endtime.' --step '.$slice;
696 if (isset($gconf['label_top'])) { $gOpts .= ' --title '.$this->text_quote($gconf['label_top']); }
697 if (isset($gconf['label_y'])) { $gOpts .= ' --vertical-label '.$this->text_quote($gconf['label_y']); }
698 if (isset($gconf['width'])) { $gOpts .= ' --width '.$gconf['width']; }
699 if (isset($gconf['height'])) { $gOpts .= ' --height '.$gconf['height'];
700 if (($gconf['height'] <= 32) && isset($gconf['thumb']) && ($gconf['thumb'])) { $gOpts .= ' --only-graph'; }
701 }
702 if (!isset($gconf['show_legend']) || (!$gconf['show_legend'])) { $gOpts .= ' --no-legend'; }
703 if (isset($gconf['logarithmic']) && $gconf['logarithmic']) { $gOpts .= ' --logarithmic'; }
704 if (isset($gconf['min_y'])) { $gOpts .= ' --lower-limit '.$gconf['min_y']; }
705 if (isset($gconf['max_y'])) { $gOpts .= ' --upper-limit '.$gconf['max_y']; }
706 if (isset($gconf['fix_scale_y']) && $gconf['fix_scale_y']) { $gOpts .= ' --rigid'; }
707 if (isset($gconf['grid_x'])) { $gOpts .= ' --x-grid '.$gconf['grid_x']; }
708 if (isset($gconf['grid_y'])) { $gOpts .= ' --y-grid '.$gconf['grid_y']; }
709 if (isset($gconf['gridfit']) && (!$gconf['gridfit'])) { $gOpts .= ' --no-gridfit'; }
710 if (isset($gconf['calc_scale_y']) && $gconf['calc_scale_y']) { $gOpts .= ' --alt-autoscale'; }
711 if (isset($gconf['calc_max_y']) && $gconf['calc_max_y']) { $gOpts .= ' --alt-autoscale-max'; }
712 if (isset($gconf['units_exponent'])) { $gOpts .= ' --units-exponent '.$gconf['units_exponent']; }
713 if (isset($gconf['units_length'])) { $gOpts .= ' --units-length '.$gconf['units_length']; }
714 if (($this->rrd_version() < '1.2') || !count($specialrows)) {
715 // lazy graphics omit all print reporting in RRDtool 1.2!
716 // --> so don't use them there when we want to print stuff
717 if (!isset($gconf['force_recreate']) || (!$gconf['force_recreate'])) { $gOpts .= ' --lazy'; }
718 }
719 if (isset($gconf['force_color']) && is_array($gconf['force_color'])) {
720 foreach ($gconf['force_color'] as $ctag=>$cval) { $gOpts .= ' --color '.$ctag.$cval; }
721 }
722 if (isset($gconf['force_font']) && is_array($gconf['force_font'])) {
723 foreach ($gconf['force_font'] as $ctag=>$cval) { $gOpts .= ' --font '.$ctag.$cval; }
724 }
725 if (isset($gconf['units_binary']) && $gconf['units_binary']) { $gOpts .= ' --base 1024'; }
726
727 foreach ($graphrows as $grow) {
728 if (isset($grow['dType']) && strlen($grow['dType'])) {
729 $gDefs .= ' '.$grow['dType'].':'.$grow['name'].'=';
730 if ($grow['dType'] == 'DEF') {
731 $gDefs .= isset($grow['dsfile'])?$grow['dsfile']:$this->rrd_file;
732 $gDefs .= ':'.$grow['dsname'].':'.$grow['cf'];
733 }
734 else { $gDefs .= $grow['rpn_expr']; }
735 }
736 if (isset($grow['gType']) && strlen($grow['gType'])) {
737 // XXX: change from STACK type to STACK flag once we have rrdtool 1.2
738 if ($this->rrd_version() < '1.2') {
739 // rrdtool 1.0 only know STACK type
740 if (isset($grow['stack']) && $grow['stack']) { $grow['gType'] = 'STACK'; }
741 }
742 $gGraphs .= ' '.$grow['gType'].':'.$grow['name'].$grow['color'];
743 if (isset($grow['legend'])) { $gGraphs .= ':'.$this->text_quote($grow['legend']); }
744 if ($this->rrd_version() >= '1.2') {
745 // rrdtool 1.2 and above have STACK flag
746 if (isset($grow['stack']) && $grow['stack']) { $gGraphs .= ':STACK'; }
747 }
748 }
749 }
750
751 foreach ($specialrows as $srow) {
752 $addSpecial .= ' '.$srow['sType'];
753 if ($this->rrd_version() >= '1.2') {
754 $addSpecial .= (($srow['sType']!='COMMENT')?':'.$srow['name']:'');
755 }
756 else {
757 $addSpecial .= (($srow['sType']!='COMMENT')?':'.$srow['name'].':'.$srow['cf']:'');
758 }
759 $addSpecial .= ':'.$this->text_quote($srow['text']);
760 }
761
762 $graph_cmd = $this->rrdtool_bin.' graph '.str_replace('*', '\*', $fname.$gOpts.$gDefs.$gGraphs.$addSpecial);
763 $return = `$graph_cmd 2>&1`;
764
765 if (strpos($return, 'ERROR') !== false) {
766 trigger_error($this->rrd_file.' - rrd graph error: '.$return, E_USER_WARNING);
767 $return = 'command:'.$graph_cmd."\n\n".$return;
768 }
769 if (0) {
770 // debug output
771 $return = 'command:'.$graph_cmd."\n\n".$return;
772 }
773 $legendlines = '';
774 foreach ($graphrows as $grow) {
775 $legendline = isset($grow['desc'])?$grow['desc']:(isset($grow['legend'])?$grow['legend']:$grow['name']);
776 $legendline .= '|'.@$grow['color'];
777 $legendline .= '|'.(isset($grow['color_bg'])?$grow['color_bg']:'');
778 $legendline .= '|'.(isset($grow['legend_long'])?$grow['legend_long']:'');
779 $legendlines .= 'legend:'.$legendline."\n";
780 }
781 $return = 'file:'.$fname."\n".$legendlines.$return;
782 return $return;
783 }
784
785 public function graph_plus($timeframe = 'day', $sub = null, $extra = null) {
786 // create a RRD graph and return meta info as a ready-to-use array
787 $gmeta = array('filename'=>null,'legends_long'=>false,'default_colorize'=>false);
788 $ret = $this->graph($timeframe, $sub, $extra);
789 if (0) {
790 // debug output
791 $gmeta['ret'] = $ret;
792 }
793 $grout = explode("\n", $ret);
794 foreach ($grout as $gline) {
795 if (preg_match('/^command:(.+)$/', $gline, $regs)) {
796 $gmeta['graph_cmd'] = $regs[1];
797 }
798 elseif (preg_match('/^file:(.+)$/', $gline, $regs)) {
799 $gmeta['filename'] = $regs[1];
800 }
801 elseif (preg_match('/^legend:([^\|]+)\|([^|]*)\|([^\|]*)\|(.*)$/', $gline, $regs)) {
802 $gmeta['legend'][$regs[1]] = array('color'=>$regs[2], 'color_bg'=>$regs[3], 'desc_long'=>$regs[4]);
803 if (strlen($regs[4])) { $gmeta['legends_long'] = true; }
804 if (strlen($regs[3]) || strlen($regs[4])) { $gmeta['default_colorize'] = true; }
805 }
806 elseif (preg_match('/^(\d+)x(\d+)$/', $gline, $regs)) {
807 $gmeta['width'] = $regs[1]; $gmeta['height'] = $regs[2];
808 }
809 elseif (preg_match('/^([^\|]+)\|([^|]+)\|([^\|]*)$/', $gline, $regs)) {
810 $gmeta['data'][$regs[1]][$regs[2]] = $regs[3];
811 }
812 elseif (preg_match('/^([^\|]+)\|([^\|]*)$/', $gline, $regs)) {
813 $gmeta['var'][$regs[1]] = $regs[2];
814 }
815 elseif (strlen(trim($gline))) {
816 $gmeta['info'][] = $gline;
817 }
818 }
819 if (is_null($gmeta['filename'])) {
820 $gmeta['filename'] = $this->basename.(!is_null($sub)?'-'.$sub:'').'-'.$timeframe.'.png';
821 }
822 return $gmeta;
823 }
824
825 public function page($sub = null, $page_extras = null, $graph_extras = null) {
826 // create a (HTML) page and return it in a string
827
828 // assemble configuration
829 $pconf = (array)$page_extras;
830 if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
831 $pconf = $pconf + $this->config_raw['page.'.$sub];
832 }
833 $pconf = $pconf + (array)$this->config_page;
834
835 $return = null;
836 switch (@$pconf['type']) {
837 case 'index':
838 $return = $this->page_index($pconf);
839 break;
840 case 'overview':
841 $return = $this->page_overview($pconf, $graph_extras);
842 break;
843 case 'simple':
844 default:
845 $return = $this->page_simple($pconf, $graph_extras);
846 break;
847 }
848 return $return;
849 }
850
851 public function simple_html($sub = null, $page_extras = null, $graph_extras = null) {
852 // create a simple (MRTG-like) HTML page and return it in a string
853 // XXX: this is here temporarily for compat only, it's preferred to use page()!
854 trigger_error(__CLASS__.'::'.__METHOD__.' is deprecated, use page() instead.', E_USER_NOTICE);
855
856 // assemble configuration
857 $pconf = (array)$page_extras;
858 if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
859 $pconf = $pconf + $this->config_raw['page.'.$sub];
860 }
861 $pconf = $pconf + (array)$this->config_page;
862
863 return $this->page_simple($pconf, $graph_extras);
864 }
865
866 private function page_index($pconf) {
867 // create a bare, very simple index list HTML page and return it in a string
868 $td = $this->mod_textdomain;
869 $ptitle = isset($pconf['title_page'])?$pconf['title_page']:dgettext($td, 'RRD statistics index');
870
871 $out = '<html><head>'."\n";
872 $out .= '<title>'.$ptitle.'</title>'."\n";
873 $out .= '<style type="text/css">'."\n";
874 if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
875 else {
876 $out .= 'h1 { font-weight: bold; font-size: 1.5em; }'."\n";
877 $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }'."\n";
878 $out .= 'li.scanfile { font-style: italic; }'."\n";
879 }
880 if (isset($pconf['style'])) { $out .= $pconf['style']; }
881 $out .= '</style>'."\n";
882 $out .= '</head>'."\n";
883 $out .= '<body>'."\n";
884
885 $out .= '<h1>'.$ptitle.'</h1>'."\n";
886 if (isset($pconf['text_intro']) && strlen($pconf['text_intro'])) {
887 $out .= '<p class="intro">'.$pconf['text_intro'].'</p>'."\n";
888 }
889 elseif (!isset($pconf['text_intro'])) {
890 $out .= '<p class="intro">'.dgettext($td, 'The following RRD stats are available:').'</p>'."\n";
891 }
892
893 $stats = $this->h_page_statsArray($pconf);
894
895 if (isset($pconf['stats_url'])) { $sURL_base = $pconf['stats_url']; }
896 else { $sURL_base = '?stat=%i%a'; }
897
898 if (isset($pconf['stats_url_add'])) { $sURL_add = $pconf['stats_url_add']; }
899 else { $sURL_add = '&sub=%s'; }
900
901 $out .= '<ul class="indexlist">'."\n";
902 foreach ($stats as $stat) {
903 $out .= '<li'.(isset($stat['class'])?' class="'.$stat['class'].'"':'').'>';
904 $sURL = str_replace('%i', $stat['name'], $sURL_base);
905 $sURL = str_replace('%a', '', $sURL);
906 $sURL = str_replace('%s', '', $sURL);
907 $out .= '<a href="'.$sURL.'">'.$stat['name'].'</a>';
908 if (isset($stat['sub']) && count($stat['sub'])) {
909 $sprt = array();
910 foreach ($stat['sub'] as $ssub) {
911 $sURL = str_replace('%i', $stat['name'], $sURL_base);
912 $sURL = str_replace('%a', $sURL_add, $sURL);
913 $sURL = str_replace('%s', $ssub, $sURL);
914 $sprt[] = '<a href="'.$sURL.'">'.$ssub.'</a>';
915 }
916 $out .= ' <span="subs">('.implode(', ', $sprt).')</span>';
917 }
918 $out .= '</li>'."\n";
919 }
920 $out .= '</ul>'."\n";
921
922 $out .= $this->h_page_footer();
923 $out .= '</body></html>'."\n";
924 return $out;
925 }
926
927 private function page_overview($pconf, $graph_extras = null) {
928 // create an overview HTML page (including graphs) and return it in a string
929 $td = $this->mod_textdomain;
930 $ptitle = isset($pconf['title_page'])?$pconf['title_page']:dgettext($td, 'RRD statistics overview');
931
932 $out = '<html><head>'."\n";
933 $out .= '<title>'.$ptitle.'</title>'."\n";
934 $out .= '<style type="text/css">'."\n";
935 if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
936 else {
937 $out .= 'h1 { font-weight: bold; font-size: 1.5em; }'."\n";
938 $out .= 'h2 { font-weight: bold; font-size: 1em; margin: 0.5em 0; }'."\n";
939 $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }'."\n";
940 $out .= 'img.rrdgraph { border: none; }'."\n";
941 }
942 if (isset($pconf['style'])) { $out .= $pconf['style']; }
943 $out .= '</style>'."\n";
944 $out .= '</head>'."\n";
945 $out .= '<body>'."\n";
946
947 $out .= '<h1>'.$ptitle.'</h1>'."\n";
948 if (isset($pconf['text_intro']) && strlen($pconf['text_intro'])) {
949 $out .= '<p class="intro">'.$pconf['text_intro'].'</p>';
950 }
951
952 $stats = $this->h_page_statsArray($pconf);
953
954 if (isset($pconf['stats_url'])) { $sURL_base = $pconf['stats_url']; }
955 else { $sURL_base = '?stat=%i%a'; }
956
957 if (isset($pconf['stats_url_add'])) { $sURL_add = $pconf['stats_url_add']; }
958 else { $sURL_add = '&sub=%s'; }
959
960 $default_num_cols = $GLOBALS['ua']->isMobile()?1:2;
961 $num_cols = is_numeric(@$pconf['num_rows'])?$pconf['num_rows']:$default_num_cols;
962 $num_rows = ceil(count($stats)/$num_cols);
963
964 $out .= '<table class="overview">'."\n";
965 for ($row = 0; $row < $num_rows; $row++) {
966 $out .= '<tr>'."\n";
967 for ($col = 0; $col < $num_cols; $col++) {
968 $idx = $row * $num_cols + $col;
969 $out .= '<td>'."\n";
970 if ($idx < count($stats)) {
971 @list($sname, $s_psub) = explode('|', $stats[$idx]['name'], 2);
972 $s_psname = 'page'.(isset($s_psub)?'.'.$s_psub:'');
973 $g_sub = @$this->config_all[$sname][$s_psname]['graph_sub'];
974
975 if (isset($this->config_all[$sname][$s_psname]['title_page'])) {
976 $s_ptitle = $this->config_all[$sname][$s_psname]['title_page'];
977 }
978 elseif (isset($this->config_all[$sname]['page']['title_page'])) {
979 $s_ptitle = $this->config_all[$sname]['page']['title_page'];
980 }
981 else {
982 $s_ptitle = isset($s_psub)
983 ?sprintf(dgettext($td, '%s (%s) statistics'), $sname, $s_psub)
984 :sprintf(dgettext($td, '%s statistics'), $sname);
985 }
986 if (!isset($pconf['hide_titles']) || !$pconf['hide_titles']) {
987 $out .= '<h2>'.$s_ptitle.'</h2>'."\n";
988 }
989
990 $s_rrd = new rrdstat($this->config_all, $sname);
991 if (in_array($s_rrd->status, array('ok','readonly','graphonly'))) {
992 $tframe = isset($pconf['graph_timeframe'])?$pconf['graph_timeframe']:'day';
993 $gmeta = $s_rrd->graph_plus($tframe, $g_sub);
994 if (isset($pconf['graph_url'])) {
995 $gURL = $pconf['graph_url'];
996 $gURL = str_replace('%f', basename($gmeta['filename']), $gURL);
997 $gURL = str_replace('%p', $gmeta['filename'], $gURL);
998 if (substr($gURL, -1) == '/') { $gURL .= $gmeta['filename']; }
999 }
1000 else {
1001 $gURL = $gmeta['filename'];
1002 }
1003 $sURL = str_replace('%i', $sname, $sURL_base);
1004 $sURL = str_replace('%a', isset($s_psub)?$sURL_add:'', $sURL);
1005 $sURL = str_replace('%s', isset($s_psub)?$s_psub:'', $sURL);
1006 $out .= '<a href="'.$sURL.'">';
1007 $out .= '<img src="'.$gURL.'"';
1008 $out .= ' alt="'.$s_rrd->basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
1009 if (isset($gmeta['width']) && isset($gmeta['height'])) {
1010 $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;"';
1011 }
1012 $out .= '></a>'."\n";
1013 }
1014 else {
1015 $out .= sprintf(dgettext($td, 'RRD error: status is "%s"'), $s_rrd->status)."\n";
1016 }
1017 }
1018 else {
1019 $out .= '&nbsp;';
1020 }
1021 $out .= '</td>'."\n";
1022 }
1023 $out .= '</tr>'."\n";
1024 }
1025 $out .= '</table>'."\n";
1026
1027 $out .= $this->h_page_footer();
1028 $out .= '</body></html>'."\n";
1029 return $out;
1030 }
1031
1032 private function page_simple($pconf, $graph_extras = null) {
1033 // create a simple (MRTG-like) HTML page and return it in a string
1034 $td = $this->mod_textdomain;
1035
1036 $ptitle = isset($pconf['title_page'])?$pconf['title_page']:sprintf(dgettext($td, '%s - RRD statistics'),$this->basename);
1037 $gtitle = array();
1038 $gtitle['day'] = isset($pconf['title_day'])?$pconf['title_day']:dgettext($td, 'Day overview (scaling 5 minutes)');
1039 $gtitle['week'] = isset($pconf['title_week'])?$pconf['title_week']:dgettext($td, 'Week overview (scaling 30 minutes)');
1040 $gtitle['month'] = isset($pconf['title_month'])?$pconf['title_month']:dgettext($td, 'Month overview (scaling 2 hours)');
1041 $gtitle['year'] = isset($pconf['title_year'])?$pconf['title_year']:dgettext($td, 'Year overview (scaling 1 day)');
1042 $ltitle = isset($pconf['title_legend'])?$pconf['title_legend']:dgettext($td, 'Legend:');
1043
1044 $out = '<html><head>'."\n";
1045 $out .= '<title>'.$ptitle.'</title>'."\n";
1046 $out .= '<style type="text/css">'."\n";
1047 if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
1048 else {
1049 $out .= 'h1 { font-weight: bold; font-size: 1.5em; }'."\n";
1050 $out .= 'h2 { font-weight: bold; font-size: 1em; }'."\n";
1051 $out .= '.gdata, .gvar, .ginfo { font-size: 0.75em; margin: 0.5em 0; }'."\n";
1052 $out .= 'table.gdata, table.legend { border: 1px solid gray; border-collapse: collapse; }'."\n";
1053 $out .= 'table.gdata td, table.gdata th, '."\n";
1054 $out .= 'table.legend td, table.legend th { border: 1px solid gray; padding: 0.1em 0.2em; }'."\n";
1055 $out .= 'div.legend { font-size: 0.75em; margin: 0.5em 0; }'."\n";
1056 $out .= 'div.legend p { margin: 0; }'."\n";
1057 $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }'."\n";
1058 }
1059 if (isset($pconf['style'])) { $out .= $pconf['style']; }
1060 $out .= '</style>'."\n";
1061 $out .= '</head>'."\n";
1062 $out .= '<body>'."\n";
1063
1064 $out .= '<h1>'.$ptitle.'</h1>'."\n";
1065 if (isset($pconf['text_intro']) && strlen($pconf['text_intro'])) {
1066 $out .= '<p class="intro">'.$pconf['text_intro'].'</p>'."\n";
1067 }
1068 if (!isset($pconf['show_update']) || $pconf['show_update']) {
1069 $out .= '<p class="last_up">';
1070 if (is_null($this->last_update())) { $up_time = dgettext($td, 'unknown'); }
1071 elseif (class_exists('baseutils')) { $up_time = baseutils::dateFormat($this->last_update(), 'short'); }
1072 else { $up_time = date('Y-m-d H:i:s', $this->last_update()); }
1073 $out .= sprintf(dgettext($td, 'Last Update: %s'), $up_time);
1074 $out .= '</p>'."\n";
1075 }
1076
1077 $g_sub = isset($pconf['graph_sub'])?$pconf['graph_sub']:null;
1078 if (in_array($this->status, array('ok','readonly','graphonly'))) {
1079 foreach (array('day','week','month','year') as $tframe) {
1080 $gmeta = $this->graph_plus($tframe, $g_sub, $graph_extras);
1081 if (isset($pconf['graph_url'])) {
1082 $gURL = $pconf['graph_url'];
1083 $gURL = str_replace('%f', basename($gmeta['filename']), $gURL);
1084 $gURL = str_replace('%p', $gmeta['filename'], $gURL);
1085 if (substr($gURL, -1) == '/') { $gURL .= $gmeta['filename']; }
1086 }
1087 else {
1088 $gURL = $gmeta['filename'];
1089 }
1090 $out .= '<div class="'.$tframe.'">'."\n";
1091 if (0) {
1092 // debug output
1093 ob_start();
1094 print_r($gmeta);
1095 $buffer = ob_get_contents();
1096 ob_end_clean();
1097 $out .= '<p>'.nl2br($buffer).'</p>';
1098 }
1099 $out .= '<h2>'.$gtitle[$tframe].'</h2>'."\n";
1100 $out .= '<img src="'.$gURL.'"';
1101 $out .= ' alt="'.$this->basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
1102 if (isset($gmeta['width']) && isset($gmeta['height'])) {
1103 $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;"';
1104 }
1105 $out .= '>'."\n";
1106 $colorize_data = (isset($pconf['data_colorize']) && $pconf['data_colorize']) ||
1107 (!isset($pconf['data_colorize']) && $gmeta['default_colorize']);
1108 if (isset($gmeta['data']) && count($gmeta['data'])) {
1109 $out .= '<table class="gdata">'."\n";
1110 foreach ($gmeta['data'] as $field=>$gdata) {
1111 $out .= '<tr><th';
1112 if ($colorize_data && isset($gmeta['legend'][$field])) {
1113 $out .= ' style="color:'.$gmeta['legend'][$field]['color'].';';
1114 if (strlen($gmeta['legend'][$field]['color_bg'])) {
1115 $out .= 'background-color:'.$gmeta['legend'][$field]['color_bg'].';';
1116 }
1117 $out .= '"';
1118 }
1119 $out .= '>'.$field.'</th>';
1120 foreach ($gdata as $gkey=>$gval) {
1121 $out .= '<td><span class="gkey">'.$gkey.': </span>'.$gval.'</td>';
1122 }
1123 $out .= '</tr>'."\n";
1124 }
1125 $out .= '</table>'."\n";
1126 }
1127 if (isset($gmeta['var']) && count($gmeta['var'])) {
1128 foreach ($gmeta['var'] as $gkey=>$gval) {
1129 $out .= '<p class="gvar"><span class="gkey">'.$gkey.': </span>'.$gval.'</p>'."\n";
1130 }
1131 }
1132 if (isset($gmeta['info']) && count($gmeta['info'])) {
1133 foreach ($gmeta['info'] as $gval) {
1134 $out .= '<p class="ginfo">'.$gval.'</p>'."\n";
1135 }
1136 }
1137 $out .= '</div>'."\n";
1138 }
1139 if ($gmeta['legends_long'] && (!isset($pconf['show_legend']) || $pconf['show_legend'])) {
1140 $out .= '<div class="legend">'."\n";
1141 $out .= '<p>'.$ltitle.'</p>'."\n";
1142 $out .= '<table class="legend">'."\n";
1143 foreach ($gmeta['legend'] as $field=>$legend) {
1144 if (strlen($legend['desc_long'])) {
1145 $out .= '<tr><th';
1146 if ($colorize_data && isset($gmeta['legend'][$field])) {
1147 $out .= ' style="color:'.$gmeta['legend'][$field]['color'].';';
1148 if (strlen($gmeta['legend'][$field]['color_bg'])) {
1149 $out .= 'background-color:'.$gmeta['legend'][$field]['color_bg'].';';
1150 }
1151 $out .= '"';
1152 }
1153 $out .= '>'.$field.'</th>';
1154 $out .= '<td>'.$legend['desc_long'].'</td>';
1155 $out .= '</tr>'."\n";
1156 }
1157 }
1158 $out .= '</table>'."\n";
1159 $out .= '</div>'."\n";
1160 }
1161 }
1162 else {
1163 $out .= sprintf(dgettext($td, 'RRD error: status is "%s"'), $this->status)."\n";
1164 }
1165
1166 $out .= $this->h_page_footer();
1167 $out .= '</body></html>'."\n";
1168 return $out;
1169 }
1170
1171 private function h_page_statsArray($pconf) {
1172 // return array of stats to list on a page
1173 $stats = array();
1174 $snames = array(); $s_exclude = array(); $sfiles = array();
1175 if (isset($pconf['index_ids'])) {
1176 foreach (explode(',', $pconf['index_ids']) as $iid) {
1177 if ($iid{0} == '-') { $s_exclude[] = substr($iid, 1); }
1178 else { $snames[] = $iid; }
1179 }
1180 }
1181 if (!isset($pconf['scan_config']) || $pconf['scan_config']) {
1182 foreach ($this->config_all as $iname=>$rinfo) {
1183 if (($iname != '*') && !(isset($rinfo['hidden']) && $rinfo['hidden']) &&
1184 !(in_array($iname, $snames)) && !(in_array($iname, $s_exclude))) {
1185 $snames[] = $iname;
1186 }
1187 }
1188 }
1189 foreach ($snames as $iname) {
1190 $newstat = array('name'=>$iname);
1191 $sfiles[] = isset($this->config_all[$iname]['file'])?$this->config_all[$iname]['file']:$iname.'.rrd';
1192 if (is_array(@$this->config_all[$iname])) {
1193 foreach ($this->config_all[$iname] as $key=>$val) {
1194 if (substr($key, 0, 5) == 'page.') { $newstat['sub'][] = substr($key, 5); }
1195 }
1196 }
1197 $stats[] = $newstat;
1198 }
1199 if (isset($pconf['scan_files']) && $pconf['scan_files']) {
1200 $rrdfiles = glob('*.rrd');
1201 foreach ($rrdfiles as $rrdfile) {
1202 $iname = (substr($rrdfile, -4) == '.rrd')?substr($rrdfile, 0, -4):$rrdfile;
1203 if (!in_array($rrdfile, $sfiles) && !(in_array($iname, $s_exclude))) {
1204 $stats[] = array('name'=>$iname, 'class'=>'scanfile');
1205 }
1206 }
1207 }
1208 return $stats;
1209 }
1210
1211 private function h_page_footer() {
1212 // return generic page footer
1213 $out = '<p class="footer">';
1214 $out .= sprintf(dgettext($this->mod_textdomain, 'Statistics created with %s using a library created by %s.'),
1215 '<a href="http://oss.oetiker.ch/rrdtool/">RRDtool</a>',
1216 '<a href="http://www.kairo.at/">KaiRo.at</a>');
1217 $out .= '</p>'."\n";
1218 return $out;
1219 }
1220
1221 private function text_quote($text) {
1222 $trans = array('"' => '\"', ':' => '\:');
1223 $qtext = '"'.strtr($text, $trans).'"';
1224 return $qtext;
1225 }
1226}
1227?>