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