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