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