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