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