thold-v0.4.9.3/thold_functions.php.org thold-v0.4.9.3/thold_functions.php
1<?php 1<?php
2/* 2/*
3 ex: set tabstop=4 shiftwidth=4 autoindent: 3 ex: set tabstop=4 shiftwidth=4 autoindent:
4 +-------------------------------------------------------------------------+ 4 +-------------------------------------------------------------------------+
5 | Copyright (C) 2011 The Cacti Group                                      | 5 | Copyright (C) 2011 The Cacti Group                                      |
6 |                                                                         | 6 |                                                                         |
7 | This program is free software; you can redistribute it and/or           | 7 | This program is free software; you can redistribute it and/or           |
8 | modify it under the terms of the GNU General Public License             | 8 | modify it under the terms of the GNU General Public License             |
9 | as published by the Free Software Foundation; either version 2          | 9 | as published by the Free Software Foundation; either version 2          |
10 | of the License, or (at your option) any later version.                  | 10 | of the License, or (at your option) any later version.                  |
11 |                                                                         | 11 |                                                                         |
12 | This program is distributed in the hope that it will be useful,         | 12 | This program is distributed in the hope that it will be useful,         |
13 | but WITHOUT ANY WARRANTY; without even the implied warranty of          | 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of          |
14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           | 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           |
15 | GNU General Public License for more details.                            | 15 | GNU General Public License for more details.                            |
16 +-------------------------------------------------------------------------+ 16 +-------------------------------------------------------------------------+
17 | Cacti: The Complete RRDTool-based Graphing Solution                     | 17 | Cacti: The Complete RRDTool-based Graphing Solution                     |
18 +-------------------------------------------------------------------------+ 18 +-------------------------------------------------------------------------+
19 | This code is designed, written, and maintained by the Cacti Group. See  | 19 | This code is designed, written, and maintained by the Cacti Group. See  |
20 | about.php and/or the AUTHORS file for specific developer information.   | 20 | about.php and/or the AUTHORS file for specific developer information.   |
21 +-------------------------------------------------------------------------+ 21 +-------------------------------------------------------------------------+
22 | http://www.cacti.net/                                                   | 22 | http://www.cacti.net/                                                   |
23 +-------------------------------------------------------------------------+ 23 +-------------------------------------------------------------------------+
24*/  24*/ 
25  25 
  26 
26function thold_debug($txt) { 27function thold_debug($txt) {
27    global $debug; 28    global $debug;
28  29 
29    if (read_config_option('thold_log_debug') == 'on' || $debug) { 30    if (read_config_option('thold_log_debug') == 'on' || $debug) {
30        thold_cacti_log($txt); 31        thold_cacti_log($txt);
31    } 32    }
32} 33}
33  34 
34function thold_initialize_rusage() { 35function thold_initialize_rusage() {
35    global $thold_start_rusage; 36    global $thold_start_rusage;
36  37 
37    if (function_exists("getrusage")) { 38    if (function_exists("getrusage")) {
38        $thold_start_rusage = getrusage(); 39        $thold_start_rusage = getrusage();
39    } 40    }
40  41 
41    $thold_start_rusage["microtime"] = microtime(); 42    $thold_start_rusage["microtime"] = microtime();
42} 43}
43  44 
44function thold_display_rusage() { 45function thold_display_rusage() {
45    global $colors, $thold_start_rusage; 46    global $colors, $thold_start_rusage;
46  47 
47    if (function_exists("getrusage")) { 48    if (function_exists("getrusage")) {
48        $dat = getrusage(); 49        $dat = getrusage();
49  50 
50        html_start_box("", "100%", $colors["header"], "3", "left", ""); 51        html_start_box("", "100%", $colors["header"], "3", "left", "");
51        print "<tr>"; 52        print "<tr>";
52  53 
53        if (!isset($thold_start_rusage)) { 54        if (!isset($thold_start_rusage)) {
54            print "<td colspan='10'>ERROR: Can not display RUSAGE please call thold_initialize_rusage first</td>"; 55            print "<td colspan='10'>ERROR: Can not display RUSAGE please call thold_initialize_rusage first</td>";
55        } else { 56        } else {
56            $i_u_time = $thold_start_rusage["ru_utime.tv_sec"] + ($thold_start_rusage["ru_utime.tv_usec"] * 1E-6); 57            $i_u_time = $thold_start_rusage["ru_utime.tv_sec"] + ($thold_start_rusage["ru_utime.tv_usec"] * 1E-6);
57            $i_s_time = $thold_start_rusage["ru_stime.tv_sec"] + ($thold_start_rusage["ru_stime.tv_usec"] * 1E-6); 58            $i_s_time = $thold_start_rusage["ru_stime.tv_sec"] + ($thold_start_rusage["ru_stime.tv_usec"] * 1E-6);
58            $s_s      = $thold_start_rusage["ru_nswap"]; 59            $s_s      = $thold_start_rusage["ru_nswap"];
59            $s_pf     = $thold_start_rusage["ru_majflt"]; 60            $s_pf     = $thold_start_rusage["ru_majflt"];
60  61 
61            list($micro,$seconds) = split(" ", $thold_start_rusage["microtime"]); 62            list($micro,$seconds) = split(" ", $thold_start_rusage["microtime"]);
62            $start_time = $seconds + $micro; 63            $start_time = $seconds + $micro;
63            list($micro,$seconds) = split(" ", microtime()); 64            list($micro,$seconds) = split(" ", microtime());
64            $end_time   = $seconds + $micro; 65            $end_time   = $seconds + $micro;
65  66 
66            $utime    = ($dat["ru_utime.tv_sec"] + ($dat["ru_utime.tv_usec"] * 1E-6)) - $i_u_time; 67            $utime    = ($dat["ru_utime.tv_sec"] + ($dat["ru_utime.tv_usec"] * 1E-6)) - $i_u_time;
67            $stime    = ($dat["ru_stime.tv_sec"] + ($dat["ru_stime.tv_usec"] * 1E-6)) - $i_s_time; 68            $stime    = ($dat["ru_stime.tv_sec"] + ($dat["ru_stime.tv_usec"] * 1E-6)) - $i_s_time;
68            $swaps    = $dat["ru_nswap"] - $s_s; 69            $swaps    = $dat["ru_nswap"] - $s_s;
69            $pages    = $dat["ru_majflt"] - $s_pf; 70            $pages    = $dat["ru_majflt"] - $s_pf;
70  71 
71            print "<td colspan='10' width='1%' style='text-align:left;'>"; 72            print "<td colspan='10' width='1%' style='text-align:left;'>";
72            print "<b>Time:</b>&nbsp;" . round($end_time - $start_time,2) . " seconds, "; 73            print "<b>Time:</b>&nbsp;" . round($end_time - $start_time,2) . " seconds, ";
73            print "<b>User:</b>&nbsp;" . round($utime,2) . " seconds, "; 74            print "<b>User:</b>&nbsp;" . round($utime,2) . " seconds, ";
74            print "<b>System:</b>&nbsp;" . round($stime,2) . " seconds, "; 75            print "<b>System:</b>&nbsp;" . round($stime,2) . " seconds, ";
75            print "<b>Swaps:</b>&nbsp;" . ($swaps) . " swaps, "; 76            print "<b>Swaps:</b>&nbsp;" . ($swaps) . " swaps, ";
76            print "<b>Pages:</b>&nbsp;" . ($pages) . " pages"; 77            print "<b>Pages:</b>&nbsp;" . ($pages) . " pages";
77            print "</td>"; 78            print "</td>";
78        } 79        }
79  80 
80        print "</tr>"; 81        print "</tr>";
81        html_end_box(false); 82        html_end_box(false);
82    } 83    }
83  84 
84} 85}
85  86 
86function thold_legend() { 87function thold_legend() {
87    global $colors, $thold_bgcolors; 88    global $colors, $thold_bgcolors;
88  89 
89    html_start_box("", "100%", $colors["header"], "3", "center", ""); 90    html_start_box("", "100%", $colors["header"], "3", "center", "");
90    print "<tr>"; 91    print "<tr>";
91    print "<td width='10%' style='text-align:center;background-color:#" . $thold_bgcolors['red'] . ";'><b>Alarm</b></td>"; 92    print "<td width='10%' style='text-align:center;background-color:#" . $thold_bgcolors['red'] . ";'><b>Alarm</b></td>";
92    print "<td width='10%' style='text-align:center;background-color:#" . $thold_bgcolors['orange'] . ";'><b>Baseline Alarm</b></td>"; 93    print "<td width='10%' style='text-align:center;background-color:#" . $thold_bgcolors['orange'] . ";'><b>Baseline Alarm</b></td>";
93    print "<td width='10%' style='text-align:center;background-color:#" . $thold_bgcolors['warning'] . ";'><b>Warning</b></td>"; 94    print "<td width='10%' style='text-align:center;background-color:#" . $thold_bgcolors['warning'] . ";'><b>Warning</b></td>";
94    print "<td width='10%' style='text-align:center;background-color:#" . $thold_bgcolors['yellow'] . ";'><b>Notice</b></td>"; 95    print "<td width='10%' style='text-align:center;background-color:#" . $thold_bgcolors['yellow'] . ";'><b>Notice</b></td>";
95    print "<td width='10%' style='text-align:center;background-color:#" . $thold_bgcolors['green'] . ";'><b>Ok</b></td>"; 96    print "<td width='10%' style='text-align:center;background-color:#" . $thold_bgcolors['green'] . ";'><b>Ok</b></td>";
96    print "<td width='10%' style='text-align:center;background-color:#" . $thold_bgcolors['grey'] . ";'><b>Disabled</b></td>"; 97    print "<td width='10%' style='text-align:center;background-color:#" . $thold_bgcolors['grey'] . ";'><b>Disabled</b></td>";
97    print "</tr>"; 98    print "</tr>";
98    html_end_box(false); 99    html_end_box(false);
99} 100}
100  101 
101function host_legend() { 102function host_legend() {
102    global $colors, $host_colors, $disabled_color, $notmon_color; 103    global $colors, $host_colors, $disabled_color, $notmon_color;
103  104 
104    html_start_box("", "100%", $colors["header"], "3", "center", ""); 105    html_start_box("", "100%", $colors["header"], "3", "center", "");
105    print "<tr>"; 106    print "<tr>";
106    print "<td width='10%' style='text-align:center;background-color:#" . $host_colors[HOST_DOWN] . ";'><b>Down</b></td>"; 107    print "<td width='10%' style='text-align:center;background-color:#" . $host_colors[HOST_DOWN] . ";'><b>Down</b></td>";
107    print "<td width='10%' style='text-align:center;background-color:#" . $host_colors[HOST_UP] . ";'><b>Up</b></td>"; 108    print "<td width='10%' style='text-align:center;background-color:#" . $host_colors[HOST_UP] . ";'><b>Up</b></td>";
108    print "<td width='10%' style='text-align:center;background-color:#" . $host_colors[HOST_RECOVERING] . ";'><b>Recovering</b></td>"; 109    print "<td width='10%' style='text-align:center;background-color:#" . $host_colors[HOST_RECOVERING] . ";'><b>Recovering</b></td>";
109    print "<td width='10%' style='text-align:center;background-color:#" . $host_colors[HOST_UNKNOWN] . ";'><b>Unknown</b></td>"; 110    print "<td width='10%' style='text-align:center;background-color:#" . $host_colors[HOST_UNKNOWN] . ";'><b>Unknown</b></td>";
110    print "<td width='10%' style='text-align:center;background-color:#" . $notmon_color . ";'><b>Not Monitored</b></td>"; 111    print "<td width='10%' style='text-align:center;background-color:#" . $notmon_color . ";'><b>Not Monitored</b></td>";
111    print "<td width='10%' style='text-align:center;background-color:#" . $disabled_color . ";'><b>Disabled</b></td>"; 112    print "<td width='10%' style='text-align:center;background-color:#" . $disabled_color . ";'><b>Disabled</b></td>";
112    print "</tr>"; 113    print "</tr>";
113    html_end_box(false); 114    html_end_box(false);
114} 115}
115  116 
116function log_legend() { 117function log_legend() {
117    global $colors; 118    global $colors;
118  119 
119    $thold_log = array( 120    $thold_log = array(
120        'alarm'     => 'F21924', 121        'alarm'     => 'F21924',
121        'warning'   => 'FB4A14', 122        'warning'   => 'FB4A14',
122        'retrigger' => 'FF7A30', 123        'retrigger' => 'FF7A30',
123        'trigger'   => 'FAFD9E', 124        'trigger'   => 'FAFD9E',
124        'restoral'  => 'CCFFCC', 125        'restoral'  => 'CCFFCC',
125        'restore'   => 'CDCFC4'); 126        'restore'   => 'CDCFC4');
126  127 
127    $thold_status = array( 128    $thold_status = array(
128        '0' => 'restore', 129        '0' => 'restore',
129        '1' => 'trigger', 130        '1' => 'trigger',
130        '2' => 'retrigger', 131        '2' => 'retrigger',
131        '3' => 'warning', 132        '3' => 'warning',
132        '4' => 'alarm', 133        '4' => 'alarm',
133        '5' => 'restoral'); 134        '5' => 'restoral');
134  135 
135    html_start_box("", "100%", $colors["header"], "3", "center", ""); 136    html_start_box("", "100%", $colors["header"], "3", "center", "");
136    print "<tr>"; 137    print "<tr>";
137    print "<td width='10%' style='text-align:center;background-color:#" . $thold_log['alarm'] . ";'><b>Alarm Notify</b></td>"; 138    print "<td width='10%' style='text-align:center;background-color:#" . $thold_log['alarm'] . ";'><b>Alarm Notify</b></td>";
138    print "<td width='10%' style='text-align:center;background-color:#" . $thold_log['warning'] . ";'><b>Warning Notify</b></td>"; 139    print "<td width='10%' style='text-align:center;background-color:#" . $thold_log['warning'] . ";'><b>Warning Notify</b></td>";
139    print "<td width='10%' style='text-align:center;background-color:#" . $thold_log['retrigger'] . ";'><b>Retrigger Notify</b></td>"; 140    print "<td width='10%' style='text-align:center;background-color:#" . $thold_log['retrigger'] . ";'><b>Retrigger Notify</b></td>";
140    print "<td width='10%' style='text-align:center;background-color:#" . $thold_log['trigger'] . ";'><b>Trigger Event</b></td>"; 141    print "<td width='10%' style='text-align:center;background-color:#" . $thold_log['trigger'] . ";'><b>Trigger Event</b></td>";
141    print "<td width='10%' style='text-align:center;background-color:#" . $thold_log['restoral'] . ";'><b>Restoral Notify</b></td>"; 142    print "<td width='10%' style='text-align:center;background-color:#" . $thold_log['restoral'] . ";'><b>Restoral Notify</b></td>";
142    print "<td width='10%' style='text-align:center;background-color:#" . $thold_log['restore'] . ";'><b>Restoral Event</b></td>"; 143    print "<td width='10%' style='text-align:center;background-color:#" . $thold_log['restore'] . ";'><b>Restoral Event</b></td>";
143    print "</tr>"; 144    print "</tr>";
144    html_end_box(false); 145    html_end_box(false);
145} 146}
146  147 
147// Update automatically 'alert_base_url' if not set and if we are called from the browser 148// Update automatically 'alert_base_url' if not set and if we are called from the browser
148// so that check-thold can pick it up 149// so that check-thold can pick it up
149if (isset($_SERVER['HTTP_HOST']) && isset($_SERVER['PHP_SELF']) && read_config_option('alert_base_url') == '') { 150if (isset($_SERVER['HTTP_HOST']) && isset($_SERVER['PHP_SELF']) && read_config_option('alert_base_url') == '') {
150    $dir = dirname($_SERVER['PHP_SELF']); 151    $dir = dirname($_SERVER['PHP_SELF']);
151    if (strpos($dir, '/plugins/') !== false) 152    if (strpos($dir, '/plugins/') !== false)
152        $dir = substr($dir, 0, strpos($dir, '/plugins/')); 153        $dir = substr($dir, 0, strpos($dir, '/plugins/'));
153    db_execute("replace into settings (name,value) values ('alert_base_url', '" . ("http://" . $_SERVER['HTTP_HOST'] . $dir . "/") . "')"); 154    db_execute("replace into settings (name,value) values ('alert_base_url', '" . ("http://" . $_SERVER['HTTP_HOST'] . $dir . "/") . "')");
154  155 
155    /* reset local settings cache so the user sees the new settings */  156    /* reset local settings cache so the user sees the new settings */ 
156    kill_session_var('sess_config_array'); 157    kill_session_var('sess_config_array');
157} 158}
158  159 
159function thold_expression_rpn_pop(&$stack) { 160function thold_expression_rpn_pop(&$stack) {
160    global $rpn_error; 161    global $rpn_error;
161  162 
162    if (sizeof($stack)) { 163    if (sizeof($stack)) {
163        return array_pop($stack); 164        return array_pop($stack);
164    } else { 165    } else {
165        $rpn_error = true; 166        $rpn_error = true;
166        return false; 167        return false;
167    } 168    }
168} 169}
169  170 
170function thold_expression_math_rpn($operator, &$stack) { 171function thold_expression_math_rpn($operator, &$stack) {
171    global $rpn_error; 172    global $rpn_error;
172  173 
173    switch($operator) { 174    switch($operator) {
174    case '+': 175    case '+':
175    case '-': 176    case '-':
176    case '/': 177    case '/':
177    case '*': 178    case '*':
178    case '%': 179    case '%':
179    case '^': 180    case '^':
180        $v1 = thold_expression_rpn_pop($stack); 181        $v1 = thold_expression_rpn_pop($stack);
181        $v2 = thold_expression_rpn_pop($stack); 182        $v2 = thold_expression_rpn_pop($stack);
182        $v3 = 'U'; 183        $v3 = 'U';
183  184 
184        if (!$rpn_error) { 185        if (!$rpn_error) {
185            @eval("\$v3 = " . $v2 . ' ' . $operator . ' ' . $v1 . ';'); 186            @eval("\$v3 = " . $v2 . ' ' . $operator . ' ' . $v1 . ';');
186            array_push($stack, $v3); 187            array_push($stack, $v3);
187        } 188        }
188        break; 189        break;
189    case 'SIN': 190    case 'SIN':
190    case 'COS': 191    case 'COS':
191    case 'TAN': 192    case 'TAN':
192    case 'ATAN': 193    case 'ATAN':
193    case 'SQRT': 194    case 'SQRT':
194    case 'FLOOR': 195    case 'FLOOR':
195    case 'CEIL': 196    case 'CEIL':
196    case 'DEG2RAD': 197    case 'DEG2RAD':
197    case 'RAD2DEG': 198    case 'RAD2DEG':
198    case 'ABS': 199    case 'ABS':
199    case 'EXP': 200    case 'EXP':
200    case 'LOG': 201    case 'LOG':
201        $v1 = thold_expression_rpn_pop($stack); 202        $v1 = thold_expression_rpn_pop($stack);
202  203 
203        if (!$rpn_error) { 204        if (!$rpn_error) {
204            eval("\$v2 = " . $operator . "(" . $v1 . ");"); 205            eval("\$v2 = " . $operator . "(" . $v1 . ");");
205            array_push($stack, $v2); 206            array_push($stack, $v2);
206        } 207        }
207        break; 208        break;
208    case 'ATAN2': 209    case 'ATAN2':
209        $v1 = thold_expression_rpn_pop($stack); 210        $v1 = thold_expression_rpn_pop($stack);
210        $v2 = thold_expression_rpn_pop($stack); 211        $v2 = thold_expression_rpn_pop($stack);
211  212 
212        if (!$rpn_error) { 213        if (!$rpn_error) {
213            $v3 = atan2($v1, $v2); 214            $v3 = atan2($v1, $v2);
214            array_push($stack, $v3); 215            array_push($stack, $v3);
215        } 216        }
216        break; 217        break;
217    case 'ADDNAN': 218    case 'ADDNAN':
218        $v1 = thold_expression_rpn_pop($stack); 219        $v1 = thold_expression_rpn_pop($stack);
219        $v2 = thold_expression_rpn_pop($stack); 220        $v2 = thold_expression_rpn_pop($stack);
220  221 
221        if (!$rpn_error) { 222        if (!$rpn_error) {
222            if ($v1 == 'NAN' || $v1 == 'U') $v1 = 0; 223            if ($v1 == 'NAN' || $v1 == 'U') $v1 = 0;
223            if ($v2 == 'NAN' || $v2 == 'U') $v2 = 0; 224            if ($v2 == 'NAN' || $v2 == 'U') $v2 = 0;
224            array_push($stack, $v1 + $v2); 225            array_push($stack, $v1 + $v2);
225        } 226        }
226        break; 227        break;
227    } 228    }
228} 229}
229  230 
230function thold_expression_boolean_rpn($operator, &$stack) { 231function thold_expression_boolean_rpn($operator, &$stack) {
231    global $rpn_error; 232    global $rpn_error;
232  233 
233    if ($operator == 'UN') { 234    if ($operator == 'UN') {
234        $v1 = thold_expression_rpn_pop($stack); 235        $v1 = thold_expression_rpn_pop($stack);
235        if ($v1 == 'U' || $v1 == 'NAN') { 236        if ($v1 == 'U' || $v1 == 'NAN') {
236            array_push($stack, '1'); 237            array_push($stack, '1');
237        } else { 238        } else {
238            array_push($stack, '0'); 239            array_push($stack, '0');
239        } 240        }
240    }elseif ($operator == 'ISINF') { 241    }elseif ($operator == 'ISINF') {
241        $v1 = thold_expression_rpn_pop($stack); 242        $v1 = thold_expression_rpn_pop($stack);
242        if ($v1 == 'INF' || $v1 == 'NEGINF') { 243        if ($v1 == 'INF' || $v1 == 'NEGINF') {
243            array_push($stack, '1'); 244            array_push($stack, '1');
244        } else { 245        } else {
245            array_push($stack, '0'); 246            array_push($stack, '0');
246        } 247        }
247    }elseif ($operator == 'AND') { 248    }elseif ($operator == 'AND') {
248        $v1 = thold_expression_rpn_pop($stack); 249        $v1 = thold_expression_rpn_pop($stack);
249        $v2 = thold_expression_rpn_pop($stack); 250        $v2 = thold_expression_rpn_pop($stack);
250        if ($v1 > 0 && $v2 > 0) { 251        if ($v1 > 0 && $v2 > 0) {
251            array_push($stack, '1'); 252            array_push($stack, '1');
252        } else { 253        } else {
253            array_push($stack, '0'); 254            array_push($stack, '0');
254        } 255        }
255    }elseif ($operator == 'OR') { 256    }elseif ($operator == 'OR') {
256        $v1 = thold_expression_rpn_pop($stack); 257        $v1 = thold_expression_rpn_pop($stack);
257        $v2 = thold_expression_rpn_pop($stack); 258        $v2 = thold_expression_rpn_pop($stack);
258        if ($v1 > 0 || $v2 > 0) { 259        if ($v1 > 0 || $v2 > 0) {
259            array_push($stack, '1'); 260            array_push($stack, '1');
260        } else { 261        } else {
261            array_push($stack, '0'); 262            array_push($stack, '0');
262        } 263        }
263    }elseif ($operator == 'IF') { 264    }elseif ($operator == 'IF') {
264        $v1 = thold_expression_rpn_pop($stack); 265        $v1 = thold_expression_rpn_pop($stack);
265        $v2 = thold_expression_rpn_pop($stack); 266        $v2 = thold_expression_rpn_pop($stack);
266        $v3 = thold_expression_rpn_pop($stack); 267        $v3 = thold_expression_rpn_pop($stack);
267  268 
268        if ($v3 == 0) { 269        if ($v3 == 0) {
269            array_push($stack, $v1); 270            array_push($stack, $v1);
270        } else { 271        } else {
271            array_push($stack, $v2); 272            array_push($stack, $v2);
272        } 273        }
273    } else { 274    } else {
274        $v1 = thold_expression_rpn_pop($stack); 275        $v1 = thold_expression_rpn_pop($stack);
275        $v2 = thold_expression_rpn_pop($stack); 276        $v2 = thold_expression_rpn_pop($stack);
276  277 
277        /* deal with unknown or infinite data */  278        /* deal with unknown or infinite data */ 
278        if (($v1 == 'INF' || $v2 == 'INF') || 279        if (($v1 == 'INF' || $v2 == 'INF') ||
279            ($v1 == 'NAN' || $v2 == 'NAN') || 280            ($v1 == 'NAN' || $v2 == 'NAN') ||
280            ($v1 == 'U' || $v2 == 'U') || 281            ($v1 == 'U' || $v2 == 'U') ||
281            ($v1 == 'NEGINF' || $v2 == 'NEGINF')) { 282            ($v1 == 'NEGINF' || $v2 == 'NEGINF')) {
282            array_push($stack, '0'); 283            array_push($stack, '0');
283        } 284        }
284  285 
285        switch($operator) { 286        switch($operator) {
286        case 'LT': 287        case 'LT':
287            if ($v1 < $v2) { 288            if ($v1 < $v2) {
288                array_push($stack, '1'); 289                array_push($stack, '1');
289            } else { 290            } else {
290                array_push($stack, '0'); 291                array_push($stack, '0');
291            } 292            }
292            break; 293            break;
293        case 'GT': 294        case 'GT':
294            if ($v1 > $v2) { 295            if ($v1 > $v2) {
295                array_push($stack, '1'); 296                array_push($stack, '1');
296            } else { 297            } else {
297                array_push($stack, '0'); 298                array_push($stack, '0');
298            } 299            }
299            break; 300            break;
300        case 'LE': 301        case 'LE':
301            if ($v1 <= $v2) { 302            if ($v1 <= $v2) {
302            array_push($stack, '1'); 303            array_push($stack, '1');
303            } else { 304            } else {
304                array_push($stack, '0'); 305                array_push($stack, '0');
305            } 306            }
306            break; 307            break;
307        case 'GE': 308        case 'GE':
308            if ($v1 >= $v2) { 309            if ($v1 >= $v2) {
309                array_push($stack, '1'); 310                array_push($stack, '1');
310            } else { 311            } else {
311                array_push($stack, '0'); 312                array_push($stack, '0');
312            } 313            }
313            break; 314            break;
314        case 'EQ': 315        case 'EQ':
315            if ($v1 == $v2) { 316            if ($v1 == $v2) {
316                array_push($stack, '1'); 317                array_push($stack, '1');
317            } else { 318            } else {
318                array_push($stack, '0'); 319                array_push($stack, '0');
319            } 320            }
320            break; 321            break;
321        case 'NE': 322        case 'NE':
322            if ($v1 != $v2) { 323            if ($v1 != $v2) {
323                array_push($stack, '1'); 324                array_push($stack, '1');
324            } else { 325            } else {
325                array_push($stack, '0'); 326                array_push($stack, '0');
326            } 327            }
327            break; 328            break;
328        } 329        }
329    } 330    }
330} 331}
331  332 
332function thold_expression_compare_rpn($operator, &$stack) { 333function thold_expression_compare_rpn($operator, &$stack) {
333    global $rpn_error; 334    global $rpn_error;
334  335 
335    if ($operator == 'MAX' || $operator == 'MIN') { 336    if ($operator == 'MAX' || $operator == 'MIN') {
336        $v[0] = thold_expression_rpn_pop($stack); 337        $v[0] = thold_expression_rpn_pop($stack);
337        $v[1] = thold_expression_rpn_pop($stack); 338        $v[1] = thold_expression_rpn_pop($stack);
338  339 
339        if (in_array('INF', $v)) { 340        if (in_array('INF', $v)) {
340            array_push($stack, 'INF'); 341            array_push($stack, 'INF');
341        }elseif (in_array('NEGINF', $v)) { 342        }elseif (in_array('NEGINF', $v)) {
342            array_push($stack, 'NEGINF'); 343            array_push($stack, 'NEGINF');
343        }elseif (in_array('U', $v)) { 344        }elseif (in_array('U', $v)) {
344            array_push($stack, 'U'); 345            array_push($stack, 'U');
345        }elseif (in_array('NAN', $v)) { 346        }elseif (in_array('NAN', $v)) {
346            array_push($stack, 'NAN'); 347            array_push($stack, 'NAN');
347        }elseif ($operator == 'MAX') { 348        }elseif ($operator == 'MAX') {
348            array_push($stack, max($v)); 349            array_push($stack, max($v));
349        } else { 350        } else {
350            array_push($stack, min($v)); 351            array_push($stack, min($v));
351        } 352        }
352    } else { 353    } else {
353        $v1 = thold_expression_rpn_pop($stack); 354        $v1 = thold_expression_rpn_pop($stack);
354        $v2 = thold_expression_rpn_pop($stack); 355        $v2 = thold_expression_rpn_pop($stack);
355        $v2 = thold_expression_rpn_pop($stack); 356        $v2 = thold_expression_rpn_pop($stack);
356  357 
357        if (($v1 == 'U' || $v1 == 'NAN') || 358        if (($v1 == 'U' || $v1 == 'NAN') ||
358            ($v2 == 'U' || $v2 == 'NAN') || 359            ($v2 == 'U' || $v2 == 'NAN') ||
359            ($v3 == 'U' || $v3 == 'NAN')) { 360            ($v3 == 'U' || $v3 == 'NAN')) {
360            array_push($stack, 'U'); 361            array_push($stack, 'U');
361        }elseif (($v1 == 'INF' || $v1 == 'NEGINF') || 362        }elseif (($v1 == 'INF' || $v1 == 'NEGINF') ||
362            ($v2 == 'INF' || $v2 == 'NEGINF') || 363            ($v2 == 'INF' || $v2 == 'NEGINF') ||
363            ($v3 == 'INF' || $v3 == 'NEGINF')) { 364            ($v3 == 'INF' || $v3 == 'NEGINF')) {
364            array_push($stack, 'U'); 365            array_push($stack, 'U');
365        }elseif ($v1 < $v2) { 366        }elseif ($v1 < $v2) {
366            if ($v3 >= $v1 && $v3 <= $v2) { 367            if ($v3 >= $v1 && $v3 <= $v2) {
367                array_push($stack, $v3); 368                array_push($stack, $v3);
368            } else { 369            } else {
369                array_push($stack, 'U'); 370                array_push($stack, 'U');
370            } 371            }
371        } else { 372        } else {
372            if ($v3 >= $v2 && $v3 <= $v1) { 373            if ($v3 >= $v2 && $v3 <= $v1) {
373                array_push($stack, $v3); 374                array_push($stack, $v3);
374            } else { 375            } else {
375                array_push($stack, 'U'); 376                array_push($stack, 'U');
376            } 377            }
377        } 378        }
378    } 379    }
379} 380}
380  381 
381function thold_expression_specvals_rpn($operator, &$stack, $count) { 382function thold_expression_specvals_rpn($operator, &$stack, $count) {
382    global $rpn_error; 383    global $rpn_error;
383  384 
384    if ($operator == 'UNKN') { 385    if ($operator == 'UNKN') {
385        array_push($stack, 'U'); 386        array_push($stack, 'U');
386    }elseif ($operator == 'INF') { 387    }elseif ($operator == 'INF') {
387        array_push($stack, 'INF'); 388        array_push($stack, 'INF');
388    }elseif ($operator == 'NEGINF') { 389    }elseif ($operator == 'NEGINF') {
389        array_push($stack, 'NEGINF'); 390        array_push($stack, 'NEGINF');
390    }elseif ($operator == 'COUNT') { 391    }elseif ($operator == 'COUNT') {
391        array_push($stack, $count); 392        array_push($stack, $count);
392    }elseif ($operator == 'PREV') { 393    }elseif ($operator == 'PREV') {
393        /* still have to figure this out */  394        /* still have to figure this out */ 
394    } 395    }
395} 396}
396  397 
397function thold_expression_stackops_rpn($operator, &$stack) { 398function thold_expression_stackops_rpn($operator, &$stack) {
398    global $rpn_error; 399    global $rpn_error;
399  400 
400    if ($operator == 'DUP') { 401    if ($operator == 'DUP') {
401        $v1 = thold_expression_rpn_pop($stack); 402        $v1 = thold_expression_rpn_pop($stack);
402        array_push($stack, $v1); 403        array_push($stack, $v1);
403        array_push($stack, $v1); 404        array_push($stack, $v1);
404    }elseif ($operator == 'POP') { 405    }elseif ($operator == 'POP') {
405        thold_expression_rpn_pop($stack); 406        thold_expression_rpn_pop($stack);
406    } else { 407    } else {
407        $v1 = thold_expression_rpn_pop($stack); 408        $v1 = thold_expression_rpn_pop($stack);
408        $v2 = thold_expression_rpn_pop($stack); 409        $v2 = thold_expression_rpn_pop($stack);
409        array_push($stack, $v2); 410        array_push($stack, $v2);
410        array_push($stack, $v1); 411        array_push($stack, $v1);
411    } 412    }
412} 413}
413  414 
414function thold_expression_time_rpn($operator, &$stack) { 415function thold_expression_time_rpn($operator, &$stack) {
415    global $rpn_error; 416    global $rpn_error;
416  417 
417    if ($operator == 'NOW') { 418    if ($operator == 'NOW') {
418        array_push($stack, time()); 419        array_push($stack, time());
419    }elseif ($operator == 'TIME') { 420    }elseif ($operator == 'TIME') {
420        /* still need to figure this one out */  421        /* still need to figure this one out */ 
421    }elseif ($operator == 'LTIME') { 422    }elseif ($operator == 'LTIME') {
422        /* still need to figure this one out */  423        /* still need to figure this one out */ 
423    } 424    }
424} 425}
425  426 
426function thold_expression_setops_rpn($operator, &$stack) { 427function thold_expression_setops_rpn($operator, &$stack) {
427    global $rpn_error; 428    global $rpn_error;
428  429 
429    if ($operator == 'SORT') { 430    if ($operator == 'SORT') {
430        $count = thold_expression_rpn_pop($stack); 431        $count = thold_expression_rpn_pop($stack);
431        $v     = array(); 432        $v     = array();
432        if ($count > 0) { 433        if ($count > 0) {
433            for($i = 0; $i < $count; $i++) { 434            for($i = 0; $i < $count; $i++) {
434                $v[] = thold_expression_rpn_pop($stack); 435                $v[] = thold_expression_rpn_pop($stack);
435            } 436            }
436  437 
437            sort($v, SORT_NUMERIC); 438            sort($v, SORT_NUMERIC);
438  439 
439            foreach($v as $val) { 440            foreach($v as $val) {
440                array_push($stack, $val); 441                array_push($stack, $val);
441            } 442            }
442        } 443        }
443    }elseif ($operator == 'REV') { 444    }elseif ($operator == 'REV') {
444        $count = thold_expression_rpn_pop($stack); 445        $count = thold_expression_rpn_pop($stack);
445        $v     = array(); 446        $v     = array();
446        if ($count > 0) { 447        if ($count > 0) {
447            for($i = 0; $i < $count; $i++) { 448            for($i = 0; $i < $count; $i++) {
448                $v[] = thold_expression_rpn_pop($stack); 449                $v[] = thold_expression_rpn_pop($stack);
449            } 450            }
450  451 
451            $v = array_reverse($v); 452            $v = array_reverse($v);
452  453 
453            foreach($v as $val) { 454            foreach($v as $val) {
454                array_push($stack, $val); 455                array_push($stack, $val);
455            } 456            }
456        } 457        }
457    }elseif ($operator == 'AVG') { 458    }elseif ($operator == 'AVG') {
458        $count = thold_expression_rpn_pop($stack); 459        $count = thold_expression_rpn_pop($stack);
459        if ($count > 0) { 460        if ($count > 0) {
460            $total  = 0; 461            $total  = 0;
461            $inf    = false; 462            $inf    = false;
462            $neginf = false; 463            $neginf = false;
463            for($i = 0; $i < $count; $i++) { 464            for($i = 0; $i < $count; $i++) {
464                $v = thold_expression_rpn_pop($stack); 465                $v = thold_expression_rpn_pop($stack);
465                if ($v == 'INF') { 466                if ($v == 'INF') {
466                    $inf = true; 467                    $inf = true;
467                }elseif ($v == 'NEGINF') { 468                }elseif ($v == 'NEGINF') {
468                    $neginf = true; 469                    $neginf = true;
469                } else { 470                } else {
470                    $total += $v; 471                    $total += $v;
471                } 472                }
472            } 473            }
473  474 
474            if ($inf) { 475            if ($inf) {
475                array_push($stack, 'INF'); 476                array_push($stack, 'INF');
476            }elseif ($neginf) { 477            }elseif ($neginf) {
477                array_push($stack, 'NEGINF'); 478                array_push($stack, 'NEGINF');
478            } else { 479            } else {
479                array_push($stack, $total/$count); 480                array_push($stack, $total/$count);
480            } 481            }
481        } 482        }
482    } 483    }
483} 484}
484  485 
485function thold_expression_ds_value($operator, &$stack, $data_sources) { 486function thold_expression_ds_value($operator, &$stack, $data_sources) {
486    global $rpn_error; 487    global $rpn_error;
487  488 
488    if (sizeof($data_sources)) { 489    if (sizeof($data_sources)) {
489    foreach($data_sources as $rrd_name => $value) { 490    foreach($data_sources as $rrd_name => $value) {
490        if (strtoupper($rrd_name) == $operator) { 491        if (strtoupper($rrd_name) == $operator) {
491            array_push($stack, $value); 492            array_push($stack, $value);
492            return; 493            return;
493        } 494        }
494    } 495    }
495    } 496    }
496  497 
497    array_push($stack, 0); 498    array_push($stack, 0);
498} 499}
499  500 
500function thold_expression_specialtype_rpn($operator, &$stack, $rra_id, $currentval) { 501function thold_expression_specialtype_rpn($operator, &$stack, $rra_id, $currentval) {
501    switch ($operator) { 502    switch ($operator) {
502    case 'CURRENT_DATA_SOURCE': 503    case 'CURRENT_DATA_SOURCE':
503        array_push($stack, $currentval); 504        array_push($stack, $currentval);
504        break; 505        break;
505    case 'CURRENT_GRAPH_MAXIMUM_VALUE': 506    case 'CURRENT_GRAPH_MAXIMUM_VALUE':
506        array_push(get_current_value($rra_id, 'upper_limit', 0)); 507        array_push(get_current_value($rra_id, 'upper_limit', 0));
507        break; 508        break;
508    case 'CURRENT_GRAPH_MINIMUM_VALUE': 509    case 'CURRENT_GRAPH_MINIMUM_VALUE':
509        array_push(get_current_value($rra_id, 'lower_limit', 0)); 510        array_push(get_current_value($rra_id, 'lower_limit', 0));
510        break; 511        break;
511    case 'CURRENT_DS_MINIMUM_VALUE': 512    case 'CURRENT_DS_MINIMUM_VALUE':
512        array_push(get_current_value($rra_id, 'rrd_minimum', 0)); 513        array_push(get_current_value($rra_id, 'rrd_minimum', 0));
513        break; 514        break;
514    case 'CURRENT_DS_MAXIMUM_VALUE': 515    case 'CURRENT_DS_MAXIMUM_VALUE':
515        array_push($stack, get_current_value($rra_id, 'rrd_maximum', 0)); 516        array_push($stack, get_current_value($rra_id, 'rrd_maximum', 0));
516        break; 517        break;
517    case 'VALUE_OF_HDD_TOTAL': 518    case 'VALUE_OF_HDD_TOTAL':
518        array_push($stack, get_current_value($rra_id, 'hdd_total', 0)); 519        array_push($stack, get_current_value($rra_id, 'hdd_total', 0));
519        break; 520        break;
520    case 'ALL_DATA_SOURCES_NODUPS': 521    case 'ALL_DATA_SOURCES_NODUPS':
521    case 'ALL_DATA_SOURCES_DUPS': 522    case 'ALL_DATA_SOURCES_DUPS':
522        $v1 = 0; 523        $v1 = 0;
523        $all_dsns = array(); 524        $all_dsns = array();
524        $all_dsns = db_fetch_assoc("SELECT data_source_name FROM data_template_rrd WHERE local_data_id = " . $rra_id); 525        $all_dsns = db_fetch_assoc("SELECT data_source_name FROM data_template_rrd WHERE local_data_id = " . $rra_id);
525        if (is_array($all_dsns)) { 526        if (is_array($all_dsns)) {
526            foreach ($all_dsns as $dsn) { 527            foreach ($all_dsns as $dsn) {
527                $v1 += get_current_value($rra_id, $dsn['data_source_name'], 0); 528                $v1 += get_current_value($rra_id, $dsn['data_source_name'], 0);
528            } 529            }
529        } 530        }
530  531 
531        array_push($stack, $v1); 532        array_push($stack, $v1);
532        break; 533        break;
533    default: 534    default:
534        cacti_log('WARNING: CDEF property not implemented yet: ' . $operator, false, 'THOLD'); 535        cacti_log('WARNING: CDEF property not implemented yet: ' . $operator, false, 'THOLD');
535        array_push($stack, $oldvalue); 536        array_push($stack, $oldvalue);
536        break; 537        break;
537    } 538    }
538} 539}
539  540 
540function thold_get_currentval(&$t_item, &$rrd_reindexed, &$rrd_time_reindexed, &$item, &$currenttime) { 541function thold_get_currentval(&$t_item, &$rrd_reindexed, &$rrd_time_reindexed, &$item, &$currenttime) {
541    /* adjust the polling interval by the last read, if applicable */  542    /* adjust the polling interval by the last read, if applicable */ 
542    $currenttime = $rrd_time_reindexed[$t_item['rra_id']]; 543    $currenttime = $rrd_time_reindexed[$t_item['rra_id']];
543    if ($t_item['lasttime'] > 0) { 544    if ($t_item['lasttime'] > 0) {
544        $polling_interval = $currenttime - $t_item['lasttime']; 545        $polling_interval = $currenttime - $t_item['lasttime'];
545    } else { 546    } else {
546        $polling_interval = $t_item['rrd_step']; 547        $polling_interval = $t_item['rrd_step'];
547    } 548    }
548  549 
549    $currentval = 0; 550    $currentval = 0;
550  551 
551    if (isset($rrd_reindexed[$t_item['rra_id']])) { 552    if (isset($rrd_reindexed[$t_item['rra_id']])) {
552        $item = $rrd_reindexed[$t_item['rra_id']]; 553        $item = $rrd_reindexed[$t_item['rra_id']];
553        if (isset($item[$t_item['name']])) { 554        if (isset($item[$t_item['name']])) {
554            switch ($t_item['data_source_type_id']) { 555            switch ($t_item['data_source_type_id']) {
555            case 2:   // COUNTER 556            case 2:   // COUNTER
556                if ($t_item['oldvalue'] != 0) { 557                if ($t_item['oldvalue'] != 0) {
557                    if ($item[$t_item['name']] >= $t_item['oldvalue']) { 558                    if ($item[$t_item['name']] >= $t_item['oldvalue']) {
558                        // Everything is normal 559                        // Everything is normal
559                        $currentval = $item[$t_item['name']] - $t_item['oldvalue']; 560                        $currentval = $item[$t_item['name']] - $t_item['oldvalue'];
560                    } else { 561                    } else {
561                        // Possible overflow, see if its 32bit or 64bit 562                        // Possible overflow, see if its 32bit or 64bit
562                        if ($t_item['oldvalue'] > 4294967295) { 563                        if ($t_item['oldvalue'] > 4294967295) {
563                            $currentval = (18446744073709551615 - $t_item['oldvalue']) + $item[$t_item['name']]; 564                            $currentval = (18446744073709551615 - $t_item['oldvalue']) + $item[$t_item['name']];
564                        } else { 565                        } else {
565                            $currentval = (4294967295 - $t_item['oldvalue']) + $item[$t_item['name']]; 566                            $currentval = (4294967295 - $t_item['oldvalue']) + $item[$t_item['name']];
566                        } 567                        }
567                    } 568                    }
568  569 
569                    $currentval = $currentval / $polling_interval; 570                    $currentval = $currentval / $polling_interval;
570  571 
571                    /* assume counter reset if greater than max value */  572                    /* assume counter reset if greater than max value */ 
572                    if ($t_item['rrd_maximum'] > 0 && $currentval > $t_item['rrd_maximum']) { 573                    if ($t_item['rrd_maximum'] > 0 && $currentval > $t_item['rrd_maximum']) {
573                        $currentval = $item[$t_item['name']] / $polling_interval; 574                        $currentval = $item[$t_item['name']] / $polling_interval;
574                    }elseif ($t_item['rrd_maximum'] == 0 && $currentval > 4.25E+9) { 575                    }elseif ($t_item['rrd_maximum'] == 0 && $currentval > 4.25E+9) {
575                        $currentval = $item[$t_item['name']] / $polling_interval; 576                        $currentval = $item[$t_item['name']] / $polling_interval;
576                    } 577                    }
577                } else { 578                } else {
578                    $currentval = 0; 579                    $currentval = 0;
579                } 580                }
580                break; 581                break;
581            case 3:   // DERIVE 582            case 3:   // DERIVE
582                $currentval = ($item[$t_item['name']] - $t_item['oldvalue']) / $polling_interval; 583                $currentval = ($item[$t_item['name']] - $t_item['oldvalue']) / $polling_interval;
583                break; 584                break;
584            case 4:   // ABSOLUTE 585            case 4:   // ABSOLUTE
585                $currentval = $item[$t_item['name']] / $polling_interval; 586                $currentval = $item[$t_item['name']] / $polling_interval;
586                break; 587                break;
587            case 1:   // GAUGE 588            case 1:   // GAUGE
588            default: 589            default:
589                $currentval = $item[$t_item['name']]; 590                $currentval = $item[$t_item['name']];
590                break; 591                break;
591            } 592            }
592        } 593        }
593    } 594    }
594  595 
595    return $currentval; 596    return $currentval;
596} 597}
597  598 
598function thold_calculate_expression($thold, $currentval, &$rrd_reindexed, &$rrd_time_reindexed) { 599function thold_calculate_expression($thold, $currentval, &$rrd_reindexed, &$rrd_time_reindexed) {
599    global $rpn_error; 600    global $rpn_error;
600  601 
601    /* set an rpn error flag */  602    /* set an rpn error flag */ 
602    $rpn_error = false; 603    $rpn_error = false;
603  604 
604    /* operators to support */  605    /* operators to support */ 
605    $math       = array('+', '-', '*', '/', '%', '^', 'ADDNAN', 'SIN', 'COS', 'LOG', 'EXP', 606    $math       = array('+', '-', '*', '/', '%', '^', 'ADDNAN', 'SIN', 'COS', 'LOG', 'EXP',
606        'SQRT', 'ATAN', 'ATAN2', 'FLOOR', 'CEIL', 'DEG2RAD', 'RAD2DEG', 'ABS'); 607        'SQRT', 'ATAN', 'ATAN2', 'FLOOR', 'CEIL', 'DEG2RAD', 'RAD2DEG', 'ABS');
607    $boolean    = array('LT', 'LE', 'GT', 'GE', 'EQ', 'NE', 'UN', 'ISNF', 'IF', 'AND', 'OR'); 608    $boolean    = array('LT', 'LE', 'GT', 'GE', 'EQ', 'NE', 'UN', 'ISNF', 'IF', 'AND', 'OR');
608    $comparison = array('MIN', 'MAX', 'LIMIT'); 609    $comparison = array('MIN', 'MAX', 'LIMIT');
609    $setops     = array('SORT', 'REV', 'AVG'); 610    $setops     = array('SORT', 'REV', 'AVG');
610    $specvals   = array('UNKN', 'INF', 'NEGINF', 'PREV', 'COUNT'); 611    $specvals   = array('UNKN', 'INF', 'NEGINF', 'PREV', 'COUNT');
611    $stackops   = array('DUP', 'POP', 'EXC'); 612    $stackops   = array('DUP', 'POP', 'EXC');
612    $time       = array('NOW', 'TIME', 'LTIME'); 613    $time       = array('NOW', 'TIME', 'LTIME');
613    $spectypes  = array('CURRENT_DATA_SOURCE','CURRENT_GRAPH_MINIMUM_VALUE', 614    $spectypes  = array('CURRENT_DATA_SOURCE','CURRENT_GRAPH_MINIMUM_VALUE',
614        'CURRENT_GRAPH_MINIMUM_VALUE','CURRENT_DS_MINIMUM_VALUE', 615        'CURRENT_GRAPH_MINIMUM_VALUE','CURRENT_DS_MINIMUM_VALUE',
615        'CURRENT_DS_MAXIMUM_VALUE','VALUE_OF_HDD_TOTAL', 616        'CURRENT_DS_MAXIMUM_VALUE','VALUE_OF_HDD_TOTAL',
616        'ALL_DATA_SOURCES_NODUPS','ALL_DATA_SOURCES_DUPS'); 617        'ALL_DATA_SOURCES_NODUPS','ALL_DATA_SOURCES_DUPS');
617  618 
618    /* our expression array */  619    /* our expression array */ 
619    $expression = explode(',', $thold['expression']); 620    $expression = explode(',', $thold['expression']);
620  621 
621    /* out current data sources */  622    /* out current data sources */ 
622    $data_sources = $rrd_reindexed[$thold['rra_id']]; 623    $data_sources = $rrd_reindexed[$thold['rra_id']];
623    if (sizeof($data_sources)) { 624    if (sizeof($data_sources)) {
624        foreach($data_sources as $key => $value) { 625        foreach($data_sources as $key => $value) {
625            $key = strtolower($key); 626            $key = strtolower($key);
626            $nds[$key] = $value; 627            $nds[$key] = $value;
627        } 628        }
628        $data_sources = $nds; 629        $data_sources = $nds;
629    } 630    }
630  631 
631    /* replace all data tabs in the rpn with values */  632    /* replace all data tabs in the rpn with values */ 
632    if (sizeof($expression)) { 633    if (sizeof($expression)) {
633    foreach($expression as $key => $item) { 634    foreach($expression as $key => $item) {
634        if (substr_count($item, "|ds:")) { 635        if (substr_count($item, "|ds:")) {
635            $dsname = strtolower(trim(str_replace("|ds:", "", $item), " |\n\r")); 636            $dsname = strtolower(trim(str_replace("|ds:", "", $item), " |\n\r"));
636  637 
637            $thold_item = db_fetch_row("SELECT thold_data.id, thold_data.graph_id, 638            $thold_item = db_fetch_row("SELECT thold_data.id, thold_data.graph_id,
638                thold_data.percent_ds, thold_data.expression, 639                thold_data.percent_ds, thold_data.expression,
639                thold_data.data_type, thold_data.cdef, thold_data.rra_id, 640                thold_data.data_type, thold_data.cdef, thold_data.rra_id,
640                thold_data.data_id, thold_data.lastread,  641                thold_data.data_id, thold_data.lastread,  
641                UNIX_TIMESTAMP(thold_data.lasttime) AS lasttime, thold_data.oldvalue, 642                UNIX_TIMESTAMP(thold_data.lasttime) AS lasttime, thold_data.oldvalue,
642                data_template_rrd.data_source_name as name, 643                data_template_rrd.data_source_name as name,
643                data_template_rrd.data_source_type_id, data_template_data.rrd_step, 644                data_template_rrd.data_source_type_id, data_template_data.rrd_step,
644                data_template_rrd.rrd_maximum 645                data_template_rrd.rrd_maximum
645                FROM thold_data 646                FROM thold_data
646                LEFT JOIN data_template_rrd 647                LEFT JOIN data_template_rrd
647                ON (data_template_rrd.id = thold_data.data_id) 648                ON (data_template_rrd.id = thold_data.data_id)
648                LEFT JOIN data_template_data 649                LEFT JOIN data_template_data
649                ON (data_template_data.local_data_id=thold_data.rra_id) 650                ON (data_template_data.local_data_id=thold_data.rra_id)
650                WHERE data_template_rrd.data_source_name='$dsname' 651                WHERE data_template_rrd.data_source_name='$dsname'
651                AND thold_data.rra_id=" . $thold['rra_id'], false); 652                AND thold_data.rra_id=" . $thold['rra_id'], false);
652  653 
653            if (sizeof($thold_item)) { 654            if (sizeof($thold_item)) {
654                $item = array(); 655                $item = array();
655                $currenttime = 0; 656                $currenttime = 0;
656                $expression[$key] = thold_get_currentval($thold_item, $rrd_reindexed, $rrd_time_reindexed, $item, $currenttime); 657                $expression[$key] = thold_get_currentval($thold_item, $rrd_reindexed, $rrd_time_reindexed, $item, $currenttime);
657            } else { 658            } else {
658                $value = ''; 659                $value = '';
659                if (api_plugin_is_enabled('dsstats') && read_config_option("dsstats_enable") == "on") { 660                if (api_plugin_is_enabled('dsstats') && read_config_option("dsstats_enable") == "on") {
660                    $value = db_fetch_cell("SELECT calculated 661                    $value = db_fetch_cell("SELECT calculated
661                        FROM data_source_stats_hourly_last 662                        FROM data_source_stats_hourly_last
662                        WHERE local_data_id=" . $thold['rrd_id'] . " 663                        WHERE local_data_id=" . $thold['rrd_id'] . "
663                        AND rrd_name='$dsname'"); 664                        AND rrd_name='$dsname'");
664                } 665                }
665  666 
666                if (empty($value) || $value == '-90909090909') { 667                if (empty($value) || $value == '-90909090909') {
667                    $expression[$key] = get_current_value($thold['rra_id'], $dsname); 668                    $expression[$key] = get_current_value($thold['rra_id'], $dsname);
668                } else { 669                } else {
669                    $expression[$key] = $value; 670                    $expression[$key] = $value;
670                } 671                }
671                cacti_log($expression[$key]); 672                cacti_log($expression[$key]);
672            } 673            }
673  674 
674            if ($expression[$key] == '') $expression[$key] = '0'; 675            if ($expression[$key] == '') $expression[$key] = '0';
675        }elseif (substr_count($item, "|")) { 676        }elseif (substr_count($item, "|")) {
676            $gl = db_fetch_row("SELECT * FROM graph_local WHERE id=" . $thold["graph_id"]); 677            $gl = db_fetch_row("SELECT * FROM graph_local WHERE id=" . $thold["graph_id"]);
677  678 
678            if (sizeof($gl)) { 679            if (sizeof($gl)) {
679                $expression[$key] = thold_expand_title($thold, $gl["host_id"], $gl["snmp_query_id"], $gl["snmp_index"], $item); 680                $expression[$key] = thold_expand_title($thold, $gl["host_id"], $gl["snmp_query_id"], $gl["snmp_index"], $item);
680            } else { 681            } else {
681                $expression[$key] = '0'; 682                $expression[$key] = '0';
682                cacti_log("WARNING: Query Replacement for '$item' Does Not Exist"); 683                cacti_log("WARNING: Query Replacement for '$item' Does Not Exist");
683            } 684            }
684  685 
685            if ($expression[$key] == '') $expression[$key] = '0'; 686            if ($expression[$key] == '') $expression[$key] = '0';
686        } else { 687        } else {
687            /* normal operator */  688            /* normal operator */ 
688        } 689        }
689    } 690    }
690    } 691    }
691  692 
692    //cacti_log(implode(",", array_keys($data_sources))); 693    //cacti_log(implode(",", array_keys($data_sources)));
693    //cacti_log(implode(",", $data_sources)); 694    //cacti_log(implode(",", $data_sources));
694    //cacti_log(implode(",", $expression)); 695    //cacti_log(implode(",", $expression));
695  696 
696    /* now let's process the RPN stack */  697    /* now let's process the RPN stack */ 
697    $x = count($expression); 698    $x = count($expression);
698  699 
699    if ($x == 0) return $currentval; 700    if ($x == 0) return $currentval;
700  701 
701    /* operation stack for RPN */  702    /* operation stack for RPN */ 
702    $stack = array(); 703    $stack = array();
703  704 
704    /* current pointer in the RPN operations list */  705    /* current pointer in the RPN operations list */ 
705    $cursor = 0; 706    $cursor = 0;
706  707 
707    while($cursor < $x) { 708    while($cursor < $x) {
708        $operator = strtoupper(trim($expression[$cursor])); 709        $operator = strtoupper(trim($expression[$cursor]));
709  710 
710        /* is the operator a data source */  711        /* is the operator a data source */ 
711        if (is_numeric($operator)) { 712        if (is_numeric($operator)) {
712            //cacti_log("NOTE: Numeric '$operator'", false, "THOLD"); 713            //cacti_log("NOTE: Numeric '$operator'", false, "THOLD");
713            array_push($stack, $operator); 714            array_push($stack, $operator);
714        }elseif (array_key_exists($operator, $data_sources)) { 715        }elseif (array_key_exists($operator, $data_sources)) {
715            //cacti_log("NOTE: DS Value '$operator'", false, "THOLD"); 716            //cacti_log("NOTE: DS Value '$operator'", false, "THOLD");
716            thold_expression_ds_value($operator, $stack, $data_sources); 717            thold_expression_ds_value($operator, $stack, $data_sources);
717        }elseif (in_array($operator, $comparison)) { 718        }elseif (in_array($operator, $comparison)) {
718            //cacti_log("NOTE: Compare '$operator'", false, "THOLD"); 719            //cacti_log("NOTE: Compare '$operator'", false, "THOLD");
719            thold_expression_compare_rpn($operator, $stack); 720            thold_expression_compare_rpn($operator, $stack);
720        }elseif (in_array($operator, $boolean)) { 721        }elseif (in_array($operator, $boolean)) {
721            //cacti_log("NOTE: Boolean '$operator'", false, "THOLD"); 722            //cacti_log("NOTE: Boolean '$operator'", false, "THOLD");
722            thold_expression_boolean_rpn($operator, $stack); 723            thold_expression_boolean_rpn($operator, $stack);
723        }elseif (in_array($operator, $math)) { 724        }elseif (in_array($operator, $math)) {
724            //cacti_log("NOTE: Math '$operator'", false, "THOLD"); 725            //cacti_log("NOTE: Math '$operator'", false, "THOLD");
725            thold_expression_math_rpn($operator, $stack); 726            thold_expression_math_rpn($operator, $stack);
726        }elseif (in_array($operator, $setops)) { 727        }elseif (in_array($operator, $setops)) {
727            //cacti_log("NOTE: SetOps '$operator'", false, "THOLD"); 728            //cacti_log("NOTE: SetOps '$operator'", false, "THOLD");
728            thold_expression_setops_rpn($operator, $stack); 729            thold_expression_setops_rpn($operator, $stack);
729        }elseif (in_array($operator, $specvals)) { 730        }elseif (in_array($operator, $specvals)) {
730            //cacti_log("NOTE: SpecVals '$operator'", false, "THOLD"); 731            //cacti_log("NOTE: SpecVals '$operator'", false, "THOLD");
731            thold_expression_specvals_rpn($operator, $stack, $cursor + 2); 732            thold_expression_specvals_rpn($operator, $stack, $cursor + 2);
732        }elseif (in_array($operator, $stackops)) { 733        }elseif (in_array($operator, $stackops)) {
733            //cacti_log("NOTE: StackOps '$operator'", false, "THOLD"); 734            //cacti_log("NOTE: StackOps '$operator'", false, "THOLD");
734            thold_expression_stackops_rpn($operator, $stack); 735            thold_expression_stackops_rpn($operator, $stack);
735        }elseif (in_array($operator, $time)) { 736        }elseif (in_array($operator, $time)) {
736            //cacti_log("NOTE: Time '$operator'", false, "THOLD"); 737            //cacti_log("NOTE: Time '$operator'", false, "THOLD");
737            thold_expression_time_rpn($operator, $stack); 738            thold_expression_time_rpn($operator, $stack);
738        }elseif (in_array($operator, $spectypes)) { 739        }elseif (in_array($operator, $spectypes)) {
739            //cacti_log("NOTE: SpecialTypes '$operator'", false, "THOLD"); 740            //cacti_log("NOTE: SpecialTypes '$operator'", false, "THOLD");
740            thold_expression_specialtype_rpn($operator, $stack, $thold['rra_id'], $currentval); 741            thold_expression_specialtype_rpn($operator, $stack, $thold['rra_id'], $currentval);
741        } else { 742        } else {
742            cacti_log("WARNING: Unsupported Field '$operator'", false, "THOLD"); 743            cacti_log("WARNING: Unsupported Field '$operator'", false, "THOLD");
743            $rpn_error = true; 744            $rpn_error = true;
744        } 745        }
745  746 
746        $cursor++; 747        $cursor++;
747  748 
748        if ($rpn_error) { 749        if ($rpn_error) {
749            cacti_log("ERROR: RPN Expression is invalid! THold:'" . $thold['thold_name'] . "', Value:'" . $currentval . "', Expression:'" . $thold['expression'] . "'", false, 'THOLD'); 750            cacti_log("ERROR: RPN Expression is invalid! THold:'" . $thold['thold_name'] . "', Value:'" . $currentval . "', Expression:'" . $thold['expression'] . "'", false, 'THOLD');
750            return 0; 751            return 0;
751        } 752        }
752    } 753    }
753  754 
754    return $stack[0]; 755    return $stack[0];
755} 756}
756  757 
757function thold_expand_title($thold, $host_id, $snmp_query_id, $snmp_index, $string) { 758function thold_expand_title($thold, $host_id, $snmp_query_id, $snmp_index, $string) {
758    if (strstr($string, "|query_") && !empty($host_id)) { 759    if (strstr($string, "|query_") && !empty($host_id)) {
759        $value = thold_substitute_snmp_query_data($string, $host_id, $snmp_query_id, $snmp_index, read_config_option("max_data_query_field_length")); 760        $value = thold_substitute_snmp_query_data($string, $host_id, $snmp_query_id, $snmp_index, read_config_option("max_data_query_field_length"));
760  761 
761        if ($value == '|query_ifHighSpeed|') { 762        if ($value == '|query_ifHighSpeed|') {
762            $value = thold_substitute_snmp_query_data('|query_ifSpeed|', $host_id, $snmp_query_id, $snmp_index, read_config_option("max_data_query_field_length")) / 1000000; 763            $value = thold_substitute_snmp_query_data('|query_ifSpeed|', $host_id, $snmp_query_id, $snmp_index, read_config_option("max_data_query_field_length")) / 1000000;
763        } 764        }
764  765 
765        if (strstr($value, "|")) { 766        if (strstr($value, "|")) {
766            cacti_log("WARNING: Expression Replacment for '$string' in THold '" . $thold["thold_name"] . "' Failed, A Reindex may be required!"); 767            cacti_log("WARNING: Expression Replacment for '$string' in THold '" . $thold["thold_name"] . "' Failed, A Reindex may be required!");
767            return '0'; 768            return '0';
768        } 769        }
769  770 
770        return $value; 771        return $value;
771    }elseif ((strstr($string, "|host_")) && (!empty($host_id))) { 772    }elseif ((strstr($string, "|host_")) && (!empty($host_id))) {
772        return thold_substitute_host_data($string, "|", "|", $host_id); 773        return thold_substitute_host_data($string, "|", "|", $host_id);
773    }else{ 774    }else{
774        return $string; 775        return $string;
775    } 776    }
776} 777}
777  778 
778function thold_substitute_snmp_query_data($string, $host_id, $snmp_query_id, $snmp_index, $max_chars = 0) { 779function thold_substitute_snmp_query_data($string, $host_id, $snmp_query_id, $snmp_index, $max_chars = 0) {
779    $field_name = trim(str_replace("|query_", "", $string),"| \n\r"); 780    $field_name = trim(str_replace("|query_", "", $string),"| \n\r");
780    $snmp_cache_data = db_fetch_cell("SELECT field_value 781    $snmp_cache_data = db_fetch_cell("SELECT field_value
781        FROM host_snmp_cache 782        FROM host_snmp_cache
782        WHERE host_id=$host_id 783        WHERE host_id=$host_id
783        AND snmp_query_id=$snmp_query_id 784        AND snmp_query_id=$snmp_query_id
784        AND snmp_index='$snmp_index' 785        AND snmp_index='$snmp_index'
785        AND field_name='$field_name'"); 786        AND field_name='$field_name'");
786  787 
787    if ($snmp_cache_data != '') { 788    if ($snmp_cache_data != '') {
788        return $snmp_cache_data; 789        return $snmp_cache_data;
789    }else{ 790    }else{
790        return $string; 791        return $string;
791    } 792    }
792} 793}
793  794 
794function thold_substitute_host_data($string, $l_escape_string, $r_escape_string, $host_id) { 795function thold_substitute_host_data($string, $l_escape_string, $r_escape_string, $host_id) {
795    $field_name = trim(str_replace("|host_", "", $string),"| \n\r"); 796    $field_name = trim(str_replace("|host_", "", $string),"| \n\r");
796    if (!isset($_SESSION["sess_host_cache_array"][$host_id])) { 797    if (!isset($_SESSION["sess_host_cache_array"][$host_id])) {
797        $host = db_fetch_row("select * from host where id=$host_id"); 798        $host = db_fetch_row("select * from host where id=$host_id");
798        $_SESSION["sess_host_cache_array"][$host_id] = $host; 799        $_SESSION["sess_host_cache_array"][$host_id] = $host;
799    } 800    }
800  801 
801    if (isset($_SESSION["sess_host_cache_array"][$host_id][$field_name])) { 802    if (isset($_SESSION["sess_host_cache_array"][$host_id][$field_name])) {
802        return $_SESSION["sess_host_cache_array"][$host_id][$field_name]; 803        return $_SESSION["sess_host_cache_array"][$host_id][$field_name];
803    } 804    }
804  805 
805    $string = str_replace($l_escape_string . "host_management_ip" . $r_escape_string, $_SESSION["sess_host_cache_array"][$host_id]["hostname"], $string); 806    $string = str_replace($l_escape_string . "host_management_ip" . $r_escape_string, $_SESSION["sess_host_cache_array"][$host_id]["hostname"], $string);
806    $temp = api_plugin_hook_function('substitute_host_data', array('string' => $string, 'l_escape_string' => $l_escape_string, 'r_escape_string' => $r_escape_string, 'host_id' => $host_id)); 807    $temp = api_plugin_hook_function('substitute_host_data', array('string' => $string, 'l_escape_string' => $l_escape_string, 'r_escape_string' => $r_escape_string, 'host_id' => $host_id));
807    $string = $temp['string']; 808    $string = $temp['string'];
808  809 
809    return $string; 810    return $string;
810} 811}
811  812 
812function thold_calculate_percent($thold, $currentval, $rrd_reindexed) { 813function thold_calculate_percent($thold, $currentval, $rrd_reindexed) {
813    $ds = $thold['percent_ds']; 814    $ds = $thold['percent_ds'];
814    if (isset($rrd_reindexed[$thold['rra_id']][$ds])) { 815    if (isset($rrd_reindexed[$thold['rra_id']][$ds])) {
815        $t = $rrd_reindexed[$thold['rra_id']][$thold['percent_ds']]; 816        $t = $rrd_reindexed[$thold['rra_id']][$thold['percent_ds']];
816        if ($t != 0) { 817        if ($t != 0) {
817            $currentval = ($currentval / $t) * 100; 818            $currentval = ($currentval / $t) * 100;
818        } else { 819        } else {
819            $currentval = 0; 820            $currentval = 0;
820        } 821        }
821    } else { 822    } else {
822        $currentval = ''; 823        $currentval = '';
823    } 824    }
824    return $currentval; 825    return $currentval;
825} 826}
826  827 
827function thold_user_auth_threshold ($rra) { 828function thold_user_auth_threshold ($rra) {
828    $current_user = db_fetch_row("select policy_graphs,policy_hosts,policy_graph_templates from user_auth where id=" . $_SESSION["sess_user_id"]); 829    $current_user = db_fetch_row("select policy_graphs,policy_hosts,policy_graph_templates from user_auth where id=" . $_SESSION["sess_user_id"]);
829    $sql_where = 'WHERE ' . get_graph_permissions_sql($current_user['policy_graphs'], $current_user['policy_hosts'], $current_user['policy_graph_templates']); 830    $sql_where = 'WHERE ' . get_graph_permissions_sql($current_user['policy_graphs'], $current_user['policy_hosts'], $current_user['policy_graph_templates']);
830    $graphs = db_fetch_assoc('SELECT DISTINCT graph_templates_graph.local_graph_id 831    $graphs = db_fetch_assoc('SELECT DISTINCT graph_templates_graph.local_graph_id
831        FROM data_template_rrd 832        FROM data_template_rrd
832        LEFT JOIN graph_templates_item ON graph_templates_item.task_item_id = data_template_rrd.id 833        LEFT JOIN graph_templates_item ON graph_templates_item.task_item_id = data_template_rrd.id
833        LEFT JOIN graph_local ON (graph_local.id=graph_templates_item.local_graph_id) 834        LEFT JOIN graph_local ON (graph_local.id=graph_templates_item.local_graph_id)
834        LEFT JOIN host ON graph_local.host_id = host.id 835        LEFT JOIN host ON graph_local.host_id = host.id
835        LEFT JOIN graph_templates_graph ON graph_templates_graph.local_graph_id = graph_local.id 836        LEFT JOIN graph_templates_graph ON graph_templates_graph.local_graph_id = graph_local.id
836        LEFT JOIN graph_templates ON (graph_templates.id=graph_templates_graph.graph_template_id) 837        LEFT JOIN graph_templates ON (graph_templates.id=graph_templates_graph.graph_template_id)
837        LEFT JOIN user_auth_perms on ((graph_templates_graph.local_graph_id=user_auth_perms.item_id and user_auth_perms.type=1 and user_auth_perms.user_id=' . $_SESSION['sess_user_id'] . ') OR (host.id=user_auth_perms.item_id and user_auth_perms.type=3 and user_auth_perms.user_id=' . $_SESSION['sess_user_id'] . ') OR (graph_templates.id=user_auth_perms.item_id and user_auth_perms.type=4 and user_auth_perms.user_id=' . $_SESSION['sess_user_id'] . ")) 838        LEFT JOIN user_auth_perms on ((graph_templates_graph.local_graph_id=user_auth_perms.item_id and user_auth_perms.type=1 and user_auth_perms.user_id=' . $_SESSION['sess_user_id'] . ') OR (host.id=user_auth_perms.item_id and user_auth_perms.type=3 and user_auth_perms.user_id=' . $_SESSION['sess_user_id'] . ') OR (graph_templates.id=user_auth_perms.item_id and user_auth_perms.type=4 and user_auth_perms.user_id=' . $_SESSION['sess_user_id'] . "))
838        $sql_where 839        $sql_where
839        AND data_template_rrd.local_data_id = $rra"); 840        AND data_template_rrd.local_data_id = $rra");
840    if (!empty($graphs)) { 841    if (!empty($graphs)) {
841        return true; 842        return true;
842    } 843    }
843    return false; 844    return false;
844} 845}
845  846 
846function thold_log($save){ 847function thold_log($save){
847    $save['id'] = 0; 848    $save['id'] = 0;
848    if (read_config_option('thold_log_cacti') == 'on') { 849    if (read_config_option('thold_log_cacti') == 'on') {
849        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $save['threshold_id'], FALSE); 850        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $save['threshold_id'], FALSE);
850        $dt = db_fetch_cell('SELECT data_template_id FROM data_template_data WHERE local_data_id=' . $thold['rra_id'], FALSE); 851        $dt = db_fetch_cell('SELECT data_template_id FROM data_template_data WHERE local_data_id=' . $thold['rra_id'], FALSE);
851        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $dt, FALSE); 852        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $dt, FALSE);
852        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id'], FALSE); 853        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id'], FALSE);
853  854 
854        if ($save['status'] == 0) { 855        if ($save['status'] == 0) {
855            $desc = "Threshold Restored  ID: " . $save['threshold_id']; 856            $desc = "Threshold Restored  ID: " . $save['threshold_id'];
856        } else { 857        } else {
857            $desc = "Threshold Breached  ID: " . $save['threshold_id']; 858            $desc = "Threshold Breached  ID: " . $save['threshold_id'];
858        } 859        }
859        $desc .= '  DataTemplate: ' . $tname; 860        $desc .= '  DataTemplate: ' . $tname;
860        $desc .= '  DataSource: ' . $ds; 861        $desc .= '  DataSource: ' . $ds;
861  862 
862        $types = array('High/Low', 'Baseline Deviation', 'Time Based'); 863        $types = array('High/Low', 'Baseline Deviation', 'Time Based');
863        $desc .= '  Type: ' . $types[$thold['thold_type']]; 864        $desc .= '  Type: ' . $types[$thold['thold_type']];
864        $desc .= '  Enabled: ' . $thold['thold_enabled']; 865        $desc .= '  Enabled: ' . $thold['thold_enabled'];
865        switch ($thold['thold_type']) { 866        switch ($thold['thold_type']) {
866        case 0: 867        case 0:
867            $desc .= '  Current: ' . $save['current']; 868            $desc .= '  Current: ' . $save['current'];
868            $desc .= '  High: ' . $thold['thold_hi']; 869            $desc .= '  High: ' . $thold['thold_hi'];
869            $desc .= '  Low: ' . $thold['thold_low']; 870            $desc .= '  Low: ' . $thold['thold_low'];
870            $desc .= '  Trigger: ' . plugin_thold_duration_convert($thold['rra_id'], $thold['thold_fail_trigger'], 'alert'); 871            $desc .= '  Trigger: ' . plugin_thold_duration_convert($thold['rra_id'], $thold['thold_fail_trigger'], 'alert');
871            $desc .= '  Warning High: ' . $thold['thold_warning_hi']; 872            $desc .= '  Warning High: ' . $thold['thold_warning_hi'];
872            $desc .= '  Warning Low: ' . $thold['thold_warning_low']; 873            $desc .= '  Warning Low: ' . $thold['thold_warning_low'];
873            $desc .= '  Warning Trigger: ' . plugin_thold_duration_convert($thold['rra_id'], $thold['thold_warning_fail_trigger'], 'alert'); 874            $desc .= '  Warning Trigger: ' . plugin_thold_duration_convert($thold['rra_id'], $thold['thold_warning_fail_trigger'], 'alert');
874            break; 875            break;
875        case 1: 876        case 1:
876            $desc .= '  Current: ' . $save['current']; 877            $desc .= '  Current: ' . $save['current'];
877            break; 878            break;
878        case 2: 879        case 2:
879            $desc .= '  Current: ' . $save['current']; 880            $desc .= '  Current: ' . $save['current'];
880            $desc .= '  High: ' . $thold['time_hi']; 881            $desc .= '  High: ' . $thold['time_hi'];
881            $desc .= '  Low: ' . $thold['time_low']; 882            $desc .= '  Low: ' . $thold['time_low'];
882            $desc .= '  Trigger: ' . $thold['time_fail_trigger']; 883            $desc .= '  Trigger: ' . $thold['time_fail_trigger'];
883            $desc .= '  Time: ' . plugin_thold_duration_convert($thold['rra_id'], $thold['time_fail_length'], 'time'); 884            $desc .= '  Time: ' . plugin_thold_duration_convert($thold['rra_id'], $thold['time_fail_length'], 'time');
884            $desc .= '  Warning High: ' . $thold['time_warning_hi']; 885            $desc .= '  Warning High: ' . $thold['time_warning_hi'];
885            $desc .= '  Warning Low: ' . $thold['time_warning_low']; 886            $desc .= '  Warning Low: ' . $thold['time_warning_low'];
886            $desc .= '  Warning Trigger: ' . $thold['time_warning_fail_trigger']; 887            $desc .= '  Warning Trigger: ' . $thold['time_warning_fail_trigger'];
887            $desc .= '  Warning Time: ' . plugin_thold_duration_convert($thold['rra_id'], $thold['time_warning_fail_length'], 'time'); 888            $desc .= '  Warning Time: ' . plugin_thold_duration_convert($thold['rra_id'], $thold['time_warning_fail_length'], 'time');
888            break; 889            break;
889        } 890        }
890  891 
891        $desc .= '  SentTo: ' . $save['emails']; 892        $desc .= '  SentTo: ' . $save['emails'];
892  893 
893        if ($save['status'] != 1) { 894        if ($save['status'] != 1) {
894            thold_cacti_log($desc); 895            thold_cacti_log($desc);
895        } 896        }
896    } 897    }
897    unset($save['emails']); 898    unset($save['emails']);
898    $id = sql_save($save, 'plugin_thold_log'); 899    $id = sql_save($save, 'plugin_thold_log');
899} 900}
900  901 
901function plugin_thold_duration_convert($rra, $data, $type, $field = 'local_data_id') { 902function plugin_thold_duration_convert($rra, $data, $type, $field = 'local_data_id') {
902    /* handle a null data value */  903    /* handle a null data value */ 
903    if ($data == '') { 904    if ($data == '') {
904        return ''; 905        return '';
905    } 906    }
906  907 
907    $step = db_fetch_cell("SELECT rrd_step FROM data_template_data WHERE $field=$rra"); 908    $step = db_fetch_cell("SELECT rrd_step FROM data_template_data WHERE $field=$rra");
908  909 
909    if ($step == 60) { 910    if ($step == 60) {
910        $repeatarray = array(0 => 'Never', 1 => 'Every Minute', 2 => 'Every 2 Minutes', 3 => 'Every 3 Minutes', 4 => 'Every 4 Minutes', 5 => 'Every 5 Minutes', 10 => 'Every 10 Minutes', 15 => 'Every 15 Minutes', 20 => 'Every 20 Minutes', 30 => 'Every 30 Minutes', 45 => 'Every 45 Minutes', 60 => 'Every Hour', 120 => 'Every 2 Hours', 180 => 'Every 3 Hours', 240 => 'Every 4 Hours', 360 => 'Every 6 Hours', 480 => 'Every 8 Hours', 720 => 'Every 12 Hours', 1440 => 'Every Day', 2880 => 'Every 2 Days', 10080 => 'Every Week', 20160 => 'Every 2 Weeks', 43200 => 'Every Month'); 911        $repeatarray = array(0 => 'Never', 1 => 'Every Minute', 2 => 'Every 2 Minutes', 3 => 'Every 3 Minutes', 4 => 'Every 4 Minutes', 5 => 'Every 5 Minutes', 10 => 'Every 10 Minutes', 15 => 'Every 15 Minutes', 20 => 'Every 20 Minutes', 30 => 'Every 30 Minutes', 45 => 'Every 45 Minutes', 60 => 'Every Hour', 120 => 'Every 2 Hours', 180 => 'Every 3 Hours', 240 => 'Every 4 Hours', 360 => 'Every 6 Hours', 480 => 'Every 8 Hours', 720 => 'Every 12 Hours', 1440 => 'Every Day', 2880 => 'Every 2 Days', 10080 => 'Every Week', 20160 => 'Every 2 Weeks', 43200 => 'Every Month');
911        $alertarray  = array(0 => 'Never', 1 => '1 Minute', 2 => '2 Minutes', 3 => '3 Minutes', 4 => '4 Minutes', 5 => '5 Minutes', 10 => '10 Minutes', 15 => '15 Minutes', 20 => '20 Minutes', 30 => '30 Minutes', 45 => '45 Minutes', 60 => '1 Hour', 120 => '2 Hours', 180 => '3 Hours', 240 => '4 Hours', 360 => '6 Hours', 480 => '8 Hours', 720 => '12 Hours', 1440 => '1 Day', 2880 => '2 Days', 10080 => '1 Week', 20160 => '2 Weeks', 43200 => '1 Month'); 912        $alertarray  = array(0 => 'Never', 1 => '1 Minute', 2 => '2 Minutes', 3 => '3 Minutes', 4 => '4 Minutes', 5 => '5 Minutes', 10 => '10 Minutes', 15 => '15 Minutes', 20 => '20 Minutes', 30 => '30 Minutes', 45 => '45 Minutes', 60 => '1 Hour', 120 => '2 Hours', 180 => '3 Hours', 240 => '4 Hours', 360 => '6 Hours', 480 => '8 Hours', 720 => '12 Hours', 1440 => '1 Day', 2880 => '2 Days', 10080 => '1 Week', 20160 => '2 Weeks', 43200 => '1 Month');
912        $timearray   = array(1 => '1 Minute', 2 => '2 Minutes', 3 => '3 Minutes', 4 => '4 Minutes', 5 => '5 Minutes', 10 => '10 Minutes', 15 => '15 Minutes', 20 => '20 Minutes', 30 => '30 Minutes', 45 => '45 Minutes', 60 => '1 Hour', 120 => '2 Hours', 180 => '3 Hours', 240 => '4 Hours', 360 => '6 Hours', 480 => '8 Hours', 720 => '12 Hours', 1440 => '1 Day', 2880 => '2 Days', 10080 => '1 Week', 20160 => '2 Weeks', 43200 => '1 Month'); 913        $timearray   = array(1 => '1 Minute', 2 => '2 Minutes', 3 => '3 Minutes', 4 => '4 Minutes', 5 => '5 Minutes', 10 => '10 Minutes', 15 => '15 Minutes', 20 => '20 Minutes', 30 => '30 Minutes', 45 => '45 Minutes', 60 => '1 Hour', 120 => '2 Hours', 180 => '3 Hours', 240 => '4 Hours', 360 => '6 Hours', 480 => '8 Hours', 720 => '12 Hours', 1440 => '1 Day', 2880 => '2 Days', 10080 => '1 Week', 20160 => '2 Weeks', 43200 => '1 Month');
913    } else if ($step == 300) { 914    } else if ($step == 300) {
914        $repeatarray = array(0 => 'Never', 1 => 'Every 5 Minutes', 2 => 'Every 10 Minutes', 3 => 'Every 15 Minutes', 4 => 'Every 20 Minutes', 6 => 'Every 30 Minutes', 8 => 'Every 45 Minutes', 12 => 'Every Hour', 24 => 'Every 2 Hours', 36 => 'Every 3 Hours', 48 => 'Every 4 Hours', 72 => 'Every 6 Hours', 96 => 'Every 8 Hours', 144 => 'Every 12 Hours', 288 => 'Every Day', 576 => 'Every 2 Days', 2016 => 'Every Week', 4032 => 'Every 2 Weeks', 8640 => 'Every Month'); 915        $repeatarray = array(0 => 'Never', 1 => 'Every 5 Minutes', 2 => 'Every 10 Minutes', 3 => 'Every 15 Minutes', 4 => 'Every 20 Minutes', 6 => 'Every 30 Minutes', 8 => 'Every 45 Minutes', 12 => 'Every Hour', 24 => 'Every 2 Hours', 36 => 'Every 3 Hours', 48 => 'Every 4 Hours', 72 => 'Every 6 Hours', 96 => 'Every 8 Hours', 144 => 'Every 12 Hours', 288 => 'Every Day', 576 => 'Every 2 Days', 2016 => 'Every Week', 4032 => 'Every 2 Weeks', 8640 => 'Every Month');
915        $alertarray  = array(0 => 'Never', 1 => '5 Minutes', 2 => '10 Minutes', 3 => '15 Minutes', 4 => '20 Minutes', 5 => '25 Minutes', 6 => '30 Minutes', 7 => '35 Minutes', 8 => '40 Minutes', 12 => '1 Hour', 24 => '2 Hours', 36 => '3 Hours', 48 => '4 Hours', 72 => '6 Hours', 96 => '8 Hours', 144 => '12 Hours', 288 => '1 Day', 576 => '2 Days', 2016 => '1 Week', 4032 => '2 Weeks', 8640 => '1 Month'); 916        $alertarray  = array(0 => 'Never', 1 => '5 Minutes', 2 => '10 Minutes', 3 => '15 Minutes', 4 => '20 Minutes', 5 => '25 Minutes', 6 => '30 Minutes', 7 => '35 Minutes', 8 => '40 Minutes', 12 => '1 Hour', 24 => '2 Hours', 36 => '3 Hours', 48 => '4 Hours', 72 => '6 Hours', 96 => '8 Hours', 144 => '12 Hours', 288 => '1 Day', 576 => '2 Days', 2016 => '1 Week', 4032 => '2 Weeks', 8640 => '1 Month');
916        $timearray   = array(1 => '5 Minutes', 2 => '10 Minutes', 3 => '15 Minutes', 4 => '20 Minutes', 6 => '30 Minutes', 8 => '45 Minutes', 12 => '1 Hour', 24 => '2 Hours', 36 => '3 Hours', 48 => '4 Hours', 72 => '6 Hours', 96 => '8 Hours', 144 => '12 Hours', 288 => '1 Day', 576 => '2 Days', 2016 => '1 Week', 4032 => '2 Weeks', 8640 => '1 Month'); 917        $timearray   = array(1 => '5 Minutes', 2 => '10 Minutes', 3 => '15 Minutes', 4 => '20 Minutes', 6 => '30 Minutes', 8 => '45 Minutes', 12 => '1 Hour', 24 => '2 Hours', 36 => '3 Hours', 48 => '4 Hours', 72 => '6 Hours', 96 => '8 Hours', 144 => '12 Hours', 288 => '1 Day', 576 => '2 Days', 2016 => '1 Week', 4032 => '2 Weeks', 8640 => '1 Month');
917    } else { 918    } else {
918        $repeatarray = array(0 => 'Never', 1 => 'Every Polling', 2 => 'Every 2 Pollings', 3 => 'Every 3 Pollings', 4 => 'Every 4 Pollings', 6 => 'Every 6 Pollings', 8 => 'Every 8 Pollings', 12 => 'Every 12 Pollings', 24 => 'Every 24 Pollings', 36 => 'Every 36 Pollings', 48 => 'Every 48 Pollings', 72 => 'Every 72 Pollings', 96 => 'Every 96 Pollings', 144 => 'Every 144 Pollings', 288 => 'Every 288 Pollings', 576 => 'Every 576 Pollings', 2016 => 'Every 2016 Pollings'); 919        $repeatarray = array(0 => 'Never', 1 => 'Every Polling', 2 => 'Every 2 Pollings', 3 => 'Every 3 Pollings', 4 => 'Every 4 Pollings', 6 => 'Every 6 Pollings', 8 => 'Every 8 Pollings', 12 => 'Every 12 Pollings', 24 => 'Every 24 Pollings', 36 => 'Every 36 Pollings', 48 => 'Every 48 Pollings', 72 => 'Every 72 Pollings', 96 => 'Every 96 Pollings', 144 => 'Every 144 Pollings', 288 => 'Every 288 Pollings', 576 => 'Every 576 Pollings', 2016 => 'Every 2016 Pollings');
919        $alertarray  = array(0 => 'Never', 1 => '1 Polling', 2 => '2 Pollings', 3 => '3 Pollings', 4 => '4 Pollings', 6 => '6 Pollings', 8 => '8 Pollings', 12 => '12 Pollings', 24 => '24 Pollings', 36 => '36 Pollings', 48 => '48 Pollings', 72 => '72 Pollings', 96 => '96 Pollings', 144 => '144 Pollings', 288 => '288 Pollings', 576 => '576 Pollings', 2016 => '2016 Pollings'); 920        $alertarray  = array(0 => 'Never', 1 => '1 Polling', 2 => '2 Pollings', 3 => '3 Pollings', 4 => '4 Pollings', 6 => '6 Pollings', 8 => '8 Pollings', 12 => '12 Pollings', 24 => '24 Pollings', 36 => '36 Pollings', 48 => '48 Pollings', 72 => '72 Pollings', 96 => '96 Pollings', 144 => '144 Pollings', 288 => '288 Pollings', 576 => '576 Pollings', 2016 => '2016 Pollings');
920        $timearray   = array(1 => '1 Polling', 2 => '2 Pollings', 3 => '3 Pollings', 4 => '4 Pollings', 6 => '6 Pollings', 8 => '8 Pollings', 12 => '12 Pollings', 24 => '24 Pollings', 36 => '36 Pollings', 48 => '48 Pollings', 72 => '72 Pollings', 96 => '96 Pollings', 144 => '144 Pollings', 288 => '288 Pollings', 576 => '576 Pollings', 2016 => '2016 Pollings'); 921        $timearray   = array(1 => '1 Polling', 2 => '2 Pollings', 3 => '3 Pollings', 4 => '4 Pollings', 6 => '6 Pollings', 8 => '8 Pollings', 12 => '12 Pollings', 24 => '24 Pollings', 36 => '36 Pollings', 48 => '48 Pollings', 72 => '72 Pollings', 96 => '96 Pollings', 144 => '144 Pollings', 288 => '288 Pollings', 576 => '576 Pollings', 2016 => '2016 Pollings');
921    } 922    }
922  923 
923    switch ($type) { 924    switch ($type) {
924    case 'repeat': 925    case 'repeat':
925        return (isset($repeatarray[$data]) ? $repeatarray[$data] : $data); 926        return (isset($repeatarray[$data]) ? $repeatarray[$data] : $data);
926        break; 927        break;
927    case 'alert': 928    case 'alert':
928        return (isset($alertarray[$data]) ? $alertarray[$data] : $data); 929        return (isset($alertarray[$data]) ? $alertarray[$data] : $data);
929        break; 930        break;
930    case 'time': 931    case 'time':
931        return (isset($timearray[$data]) ? $timearray[$data] : $data); 932        return (isset($timearray[$data]) ? $timearray[$data] : $data);
932        break; 933        break;
933    } 934    }
934    return $data; 935    return $data;
935} 936}
936  937 
937function plugin_thold_log_changes($id, $changed, $message = array()) { 938function plugin_thold_log_changes($id, $changed, $message = array()) {
938    global $config; 939    global $config;
939    $desc = ''; 940    $desc = '';
940  941 
941    if (read_config_option('thold_log_changes') != 'on') { 942    if (read_config_option('thold_log_changes') != 'on') {
942        return; 943        return;
943    } 944    }
944  945 
945    if (isset($_SESSION['sess_user_id'])) { 946    if (isset($_SESSION['sess_user_id'])) {
946        $user = db_fetch_row('SELECT username FROM user_auth WHERE id = ' . $_SESSION['sess_user_id']); 947        $user = db_fetch_row('SELECT username FROM user_auth WHERE id = ' . $_SESSION['sess_user_id']);
947        $user = $user['username']; 948        $user = $user['username'];
948    } else { 949    } else {
949        $user = 'Unknown'; 950        $user = 'Unknown';
950    } 951    }
951  952 
952    switch ($changed) { 953    switch ($changed) {
953    case 'enabled_threshold': 954    case 'enabled_threshold':
954        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $id, FALSE); 955        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $id, FALSE);
955        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']); 956        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']);
956        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']); 957        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']);
957        $desc = "Enabled Threshold  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>"; 958        $desc = "Enabled Threshold  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>";
958        $desc .= '  DataTemplate: ' . $tname; 959        $desc .= '  DataTemplate: ' . $tname;
959        $desc .= '  DataSource: ' . $ds; 960        $desc .= '  DataSource: ' . $ds;
960        break; 961        break;
961    case 'disabled_threshold': 962    case 'disabled_threshold':
962        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $id, FALSE); 963        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $id, FALSE);
963        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']); 964        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']);
964        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']); 965        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']);
965        $desc = "Disabled Threshold  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>"; 966        $desc = "Disabled Threshold  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>";
966        $desc .= '  DataTemplate: ' . $tname; 967        $desc .= '  DataTemplate: ' . $tname;
967        $desc .= '  DataSource: ' . $ds; 968        $desc .= '  DataSource: ' . $ds;
968        break; 969        break;
969    case 'reapply_name': 970    case 'reapply_name':
970        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id=' . $id, FALSE); 971        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id=' . $id, FALSE);
971        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']); 972        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']);
972        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']); 973        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']);
973        $desc = "Reapply Threshold Name User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>"; 974        $desc = "Reapply Threshold Name User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>";
974        $desc .= '  DataTemplate: ' . $tname; 975        $desc .= '  DataTemplate: ' . $tname;
975        $desc .= '  DataSource: ' . $ds; 976        $desc .= '  DataSource: ' . $ds;
976        break; 977        break;
977    case 'enabled_host': 978    case 'enabled_host':
978        $host = db_fetch_row('SELECT * FROM host WHERE id = ' . $id); 979        $host = db_fetch_row('SELECT * FROM host WHERE id = ' . $id);
979        $desc = "User: $user  Enabled Host[$id] - " . $host['description'] . ' (' . $host['hostname'] . ')'; 980        $desc = "User: $user  Enabled Host[$id] - " . $host['description'] . ' (' . $host['hostname'] . ')';
980        break; 981        break;
981    case 'disabled_host': 982    case 'disabled_host':
982        $host = db_fetch_row('SELECT * FROM host WHERE id = ' . $id); 983        $host = db_fetch_row('SELECT * FROM host WHERE id = ' . $id);
983        $desc = "User: $user  Disabled Host[$id] - " . $host['description'] . ' (' . $host['hostname'] . ')'; 984        $desc = "User: $user  Disabled Host[$id] - " . $host['description'] . ' (' . $host['hostname'] . ')';
984        break; 985        break;
985    case 'auto_created': 986    case 'auto_created':
986        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $id, FALSE); 987        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $id, FALSE);
987        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']); 988        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']);
988        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']); 989        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']);
989        $desc = "Auto-created Threshold  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>"; 990        $desc = "Auto-created Threshold  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>";
990        $desc .= '  DataTemplate: ' . $tname; 991        $desc .= '  DataTemplate: ' . $tname;
991        $desc .= '  DataSource: ' . $ds; 992        $desc .= '  DataSource: ' . $ds;
992        break; 993        break;
993    case 'created': 994    case 'created':
994        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $id, FALSE); 995        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $id, FALSE);
995        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']); 996        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']);
996        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']); 997        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']);
997        $desc = "Created Threshold  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>"; 998        $desc = "Created Threshold  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>";
998        $desc .= '  DataTemplate: ' . $tname; 999        $desc .= '  DataTemplate: ' . $tname;
999        $desc .= '  DataSource: ' . $ds; 1000        $desc .= '  DataSource: ' . $ds;
1000        break; 1001        break;
1001    case 'deleted': 1002    case 'deleted':
1002        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $id, FALSE); 1003        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $id, FALSE);
1003        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']); 1004        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']);
1004        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']); 1005        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']);
1005        $desc = "Deleted Threshold  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>"; 1006        $desc = "Deleted Threshold  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>";
1006        $desc .= '  DataTemplate: ' . $tname; 1007        $desc .= '  DataTemplate: ' . $tname;
1007        $desc .= '  DataSource: ' . $ds; 1008        $desc .= '  DataSource: ' . $ds;
1008        break; 1009        break;
1009    case 'deleted_template': 1010    case 'deleted_template':
1010        $thold = db_fetch_row('SELECT * FROM thold_template WHERE id = ' . $id, FALSE); 1011        $thold = db_fetch_row('SELECT * FROM thold_template WHERE id = ' . $id, FALSE);
1011        $desc = "Deleted Template  User: $user  ID: $id"; 1012        $desc = "Deleted Template  User: $user  ID: $id";
1012        $desc .= '  DataTemplate: ' . $thold['data_template_name']; 1013        $desc .= '  DataTemplate: ' . $thold['data_template_name'];
1013        $desc .= '  DataSource: ' . $thold['data_source_name']; 1014        $desc .= '  DataSource: ' . $thold['data_source_name'];
1014        break; 1015        break;
1015    case 'modified': 1016    case 'modified':
1016        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $id, FALSE); 1017        $thold = db_fetch_row('SELECT * FROM thold_data WHERE id = ' . $id, FALSE);
1017  1018 
1018        $rows = db_fetch_assoc('SELECT plugin_thold_contacts.data 1019        $rows = db_fetch_assoc('SELECT plugin_thold_contacts.data
1019            FROM plugin_thold_contacts, plugin_thold_threshold_contact 1020            FROM plugin_thold_contacts, plugin_thold_threshold_contact
1020            WHERE plugin_thold_contacts.id=plugin_thold_threshold_contact.contact_id 1021            WHERE plugin_thold_contacts.id=plugin_thold_threshold_contact.contact_id
1021            AND plugin_thold_threshold_contact.thold_id=' . $id); 1022            AND plugin_thold_threshold_contact.thold_id=' . $id);
1022  1023 
1023        $alert_emails = ''; 1024        $alert_emails = '';
1024        if (read_config_option('thold_disable_legacy') != 'on') { 1025        if (read_config_option('thold_disable_legacy') != 'on') {
1025            $alert_emails = array(); 1026            $alert_emails = array();
1026            if (count($rows)) { 1027            if (count($rows)) {
1027                foreach ($rows as $row) { 1028                foreach ($rows as $row) {
1028                $alert_emails[] = $row['data']; 1029                $alert_emails[] = $row['data'];
1029                } 1030                }
1030            } 1031            }
1031            $alert_emails = implode(',', $alert_emails); 1032            $alert_emails = implode(',', $alert_emails);
1032            if ($alert_emails != '') { 1033            if ($alert_emails != '') {
1033                $alert_emails .= ',' . $thold['notify_extra']; 1034                $alert_emails .= ',' . $thold['notify_extra'];
1034            } else { 1035            } else {
1035                $alert_emails = $thold['notify_extra']; 1036                $alert_emails = $thold['notify_extra'];
1036            } 1037            }
1037        } 1038        }
1038  1039 
1039        $alert_emails .= (strlen($alert_emails) ? ",":"") . get_thold_notification_emails($thold['notify_alert']); 1040        $alert_emails .= (strlen($alert_emails) ? ",":"") . get_thold_notification_emails($thold['notify_alert']);
1040  1041 
1041        $warning_emails = ''; 1042        $warning_emails = '';
1042        if (read_config_option('thold_disable_legacy') != 'on') { 1043        if (read_config_option('thold_disable_legacy') != 'on') {
1043            $warning_emails = $thold['notify_warning_extra']; 1044            $warning_emails = $thold['notify_warning_extra'];
1044        } 1045        }
1045  1046 
1046        if ($message['id'] > 0) { 1047        if ($message['id'] > 0) {
1047            $desc = "Modified Threshold  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>"; 1048            $desc = "Modified Threshold  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>";
1048        } else { 1049        } else {
1049            $desc = "Created Threshold  User: $user  ID:  <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>"; 1050            $desc = "Created Threshold  User: $user  ID:  <a href='" . $config['url_path'] . "plugins/thold/thold.php?rra=" . $thold['rra_id'] . "&view_rrd=" . $thold['data_id'] . "'>$id</a>";
1050        } 1051        }
1051  1052 
1052        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']); 1053        $tname = db_fetch_cell('SELECT name FROM data_template WHERE id=' . $thold['data_template']);
1053        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']); 1054        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']);
1054  1055 
1055        $desc .= '  DataTemplate: ' . $tname; 1056        $desc .= '  DataTemplate: ' . $tname;
1056        $desc .= '  DataSource: ' . $ds; 1057        $desc .= '  DataSource: ' . $ds;
1057  1058 
1058        if ($message['template_enabled'] == 'on') { 1059        if ($message['template_enabled'] == 'on') {
1059            $desc .= '  Use Template: On'; 1060            $desc .= '  Use Template: On';
1060        } else { 1061        } else {
1061            $types = array('High/Low', 'Baseline Deviation', 'Time Based'); 1062            $types = array('High/Low', 'Baseline Deviation', 'Time Based');
1062            $desc .= '  Type: ' . $types[$message['thold_type']]; 1063            $desc .= '  Type: ' . $types[$message['thold_type']];
1063            $desc .= '  Enabled: ' . $message['thold_enabled']; 1064            $desc .= '  Enabled: ' . $message['thold_enabled'];
1064            switch ($message['thold_type']) { 1065            switch ($message['thold_type']) {
1065            case 0: 1066            case 0:
1066                $desc .= '  High: ' . $message['thold_hi']; 1067                $desc .= '  High: ' . $message['thold_hi'];
1067                $desc .= '  Low: ' . $message['thold_low']; 1068                $desc .= '  Low: ' . $message['thold_low'];
1068                $desc .= '  Trigger: ' . plugin_thold_duration_convert($thold['rra_id'], $message['thold_fail_trigger'], 'alert'); 1069                $desc .= '  Trigger: ' . plugin_thold_duration_convert($thold['rra_id'], $message['thold_fail_trigger'], 'alert');
1069                $desc .= '  Warning High: ' . $message['thold_warning_hi']; 1070                $desc .= '  Warning High: ' . $message['thold_warning_hi'];
1070                $desc .= '  Warning Low: ' . $message['thold_warning_low']; 1071                $desc .= '  Warning Low: ' . $message['thold_warning_low'];
1071                $desc .= '  Warning Trigger: ' . plugin_thold_duration_convert($thold['rra_id'], $message['thold_warning_fail_trigger'], 'alert'); 1072                $desc .= '  Warning Trigger: ' . plugin_thold_duration_convert($thold['rra_id'], $message['thold_warning_fail_trigger'], 'alert');
1072  1073 
1073                break; 1074                break;
1074            case 1: 1075            case 1:
1075                $desc .= '  Range: ' . $message['bl_ref_time_range']; 1076                $desc .= '  Range: ' . $message['bl_ref_time_range'];
1076                $desc .= '  Dev Up: ' . $message['bl_pct_up']; 1077                $desc .= '  Dev Up: ' . $message['bl_pct_up'];
1077                $desc .= '  Dev Down: ' . $message['bl_pct_down']; 1078                $desc .= '  Dev Down: ' . $message['bl_pct_down'];
1078                $desc .= '  Trigger: ' . $message['bl_fail_trigger']; 1079                $desc .= '  Trigger: ' . $message['bl_fail_trigger'];
1079  1080 
1080                break; 1081                break;
1081            case 2: 1082            case 2:
1082                $desc .= '  High: ' . $message['time_hi']; 1083                $desc .= '  High: ' . $message['time_hi'];
1083                $desc .= '  Low: ' . $message['time_low']; 1084                $desc .= '  Low: ' . $message['time_low'];
1084                $desc .= '  Trigger: ' . $message['time_fail_trigger']; 1085                $desc .= '  Trigger: ' . $message['time_fail_trigger'];
1085                $desc .= '  Time: ' . plugin_thold_duration_convert($thold['rra_id'], $message['time_fail_length'], 'time'); 1086                $desc .= '  Time: ' . plugin_thold_duration_convert($thold['rra_id'], $message['time_fail_length'], 'time');
1086                $desc .= '  Warning High: ' . $message['time_warning_hi']; 1087                $desc .= '  Warning High: ' . $message['time_warning_hi'];
1087                $desc .= '  Warning Low: ' . $message['time_warning_low']; 1088                $desc .= '  Warning Low: ' . $message['time_warning_low'];
1088                $desc .= '  Warning Trigger: ' . $message['time_warning_fail_trigger']; 1089                $desc .= '  Warning Trigger: ' . $message['time_warning_fail_trigger'];
1089                $desc .= '  Warning Time: ' . plugin_thold_duration_convert($thold['rra_id'], $message['time_warning_fail_length'], 'time'); 1090                $desc .= '  Warning Time: ' . plugin_thold_duration_convert($thold['rra_id'], $message['time_warning_fail_length'], 'time');
1090  1091 
1091                break; 1092                break;
1092            } 1093            }
1093            $desc .= '  CDEF: ' . $message['cdef']; 1094            $desc .= '  CDEF: ' . $message['cdef'];
1094            $desc .= '  ReAlert: ' . plugin_thold_duration_convert($thold['rra_id'], $message['repeat_alert'], 'alert'); 1095            $desc .= '  ReAlert: ' . plugin_thold_duration_convert($thold['rra_id'], $message['repeat_alert'], 'alert');
1095            $desc .= '  Alert Emails: ' . $alert_emails; 1096            $desc .= '  Alert Emails: ' . $alert_emails;
1096            $desc .= '  Warning Emails: ' . $warning_emails; 1097            $desc .= '  Warning Emails: ' . $warning_emails;
1097        } 1098        }
1098  1099 
1099        break; 1100        break;
1100    case 'modified_template': 1101    case 'modified_template':
1101        $thold = db_fetch_row('SELECT * FROM thold_template WHERE id = ' . $id, FALSE); 1102        $thold = db_fetch_row('SELECT * FROM thold_template WHERE id = ' . $id, FALSE);
1102  1103 
1103        $rows = db_fetch_assoc('SELECT plugin_thold_contacts.data 1104        $rows = db_fetch_assoc('SELECT plugin_thold_contacts.data
1104            FROM plugin_thold_contacts, plugin_thold_template_contact 1105            FROM plugin_thold_contacts, plugin_thold_template_contact
1105            WHERE plugin_thold_contacts.id=plugin_thold_template_contact.contact_id 1106            WHERE plugin_thold_contacts.id=plugin_thold_template_contact.contact_id
1106            AND plugin_thold_template_contact.template_id=' . $id); 1107            AND plugin_thold_template_contact.template_id=' . $id);
1107  1108 
1108        $alert_emails = ''; 1109        $alert_emails = '';
1109        if (read_config_option('thold_disable_legacy') != 'on') { 1110        if (read_config_option('thold_disable_legacy') != 'on') {
1110            $alert_emails = array(); 1111            $alert_emails = array();
1111            if (count($rows)) { 1112            if (count($rows)) {
1112                foreach ($rows as $row) { 1113                foreach ($rows as $row) {
1113                $alert_emails[] = $row['data']; 1114                $alert_emails[] = $row['data'];
1114                } 1115                }
1115            } 1116            }
1116            $alert_emails = implode(',', $alert_emails); 1117            $alert_emails = implode(',', $alert_emails);
1117            if ($alert_emails != '') { 1118            if ($alert_emails != '') {
1118                $alert_emails .= ',' . $thold['notify_extra']; 1119                $alert_emails .= ',' . $thold['notify_extra'];
1119            } else { 1120            } else {
1120                $alert_emails = $thold['notify_extra']; 1121                $alert_emails = $thold['notify_extra'];
1121            } 1122            }
1122        } 1123        }
1123  1124 
1124        $alert_emails .= (strlen($alert_emails) ? ",":"") . get_thold_notification_emails($thold['notify_alert']); 1125        $alert_emails .= (strlen($alert_emails) ? ",":"") . get_thold_notification_emails($thold['notify_alert']);
1125  1126 
1126        $warning_emails = ''; 1127        $warning_emails = '';
1127        if (read_config_option('thold_disable_legacy') != 'on') { 1128        if (read_config_option('thold_disable_legacy') != 'on') {
1128            $warning_emails = $item['notify_warning_extra']; 1129            $warning_emails = $thold['notify_warning_extra'];
1129        } 1130        }
1130  1131 
1131        if ($message['id'] > 0) { 1132        if ($message['id'] > 0) {
1132            $desc = "Modified Template  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold_templates.php?action=edit&id=$id'>$id</a>"; 1133            $desc = "Modified Template  User: $user  ID: <a href='" . $config['url_path'] . "plugins/thold/thold_templates.php?action=edit&id=$id'>$id</a>";
1133        } else { 1134        } else {
1134            $desc = "Created Template  User: $user  ID:  <a href='" . $config['url_path'] . "plugins/thold/thold_templates.php?action=edit&id=$id'>$id</a>"; 1135            $desc = "Created Template  User: $user  ID:  <a href='" . $config['url_path'] . "plugins/thold/thold_templates.php?action=edit&id=$id'>$id</a>";
1135        } 1136        }
1136  1137 
1137        $desc .= '  DataTemplate: ' . $thold['data_template_name']; 1138        $desc .= '  DataTemplate: ' . $thold['data_template_name'];
1138        $desc .= '  DataSource: ' . $thold['data_source_name']; 1139        $desc .= '  DataSource: ' . $thold['data_source_name'];
1139  1140 
1140        $types = array('High/Low', 'Baseline Deviation', 'Time Based'); 1141        $types = array('High/Low', 'Baseline Deviation', 'Time Based');
1141        $desc .= '  Type: ' . $types[$message['thold_type']]; 1142        $desc .= '  Type: ' . $types[$message['thold_type']];
1142        $desc .= '  Enabled: ' . $message['thold_enabled']; 1143        $desc .= '  Enabled: ' . $message['thold_enabled'];
1143  1144 
1144        switch ($message['thold_type']) { 1145        switch ($message['thold_type']) {
1145        case 0: 1146        case 0:
1146            $desc .= '  High: ' . (isset($message['thold_hi']) ? $message['thold_hi'] : ''); 1147            $desc .= '  High: ' . (isset($message['thold_hi']) ? $message['thold_hi'] : '');
1147            $desc .= '  Low: ' . (isset($message['thold_low']) ? $message['thold_low'] : ''); 1148            $desc .= '  Low: ' . (isset($message['thold_low']) ? $message['thold_low'] : '');
1148            $desc .= '  Trigger: ' . plugin_thold_duration_convert($thold['data_template_id'], (isset($message['thold_fail_trigger']) ? $message['thold_fail_trigger'] : ''), 'alert', 'data_template_id'); 1149            $desc .= '  Trigger: ' . plugin_thold_duration_convert($thold['data_template_id'], (isset($message['thold_fail_trigger']) ? $message['thold_fail_trigger'] : ''), 'alert', 'data_template_id');
1149            $desc .= '  Warning High: ' . (isset($message['thold_warning_hi']) ? $message['thold_warning_hi'] : ''); 1150            $desc .= '  Warning High: ' . (isset($message['thold_warning_hi']) ? $message['thold_warning_hi'] : '');
1150            $desc .= '  Warning Low: ' . (isset($message['thold_warning_low']) ? $message['thold_warning_low'] : ''); 1151            $desc .= '  Warning Low: ' . (isset($message['thold_warning_low']) ? $message['thold_warning_low'] : '');
1151            $desc .= '  Warning Trigger: ' . plugin_thold_duration_convert($thold['data_template_id'], (isset($message['thold_warning_fail_trigger']) ? $message['thold_fail_trigger'] : ''), 'alert', 'data_template_id'); 1152            $desc .= '  Warning Trigger: ' . plugin_thold_duration_convert($thold['data_template_id'], (isset($message['thold_warning_fail_trigger']) ? $message['thold_fail_trigger'] : ''), 'alert', 'data_template_id');
1152  1153 
1153            break; 1154            break;
1154        case 1: 1155        case 1:
1155            $desc .= '  Range: ' . $message['bl_ref_time_range']; 1156            $desc .= '  Range: ' . $message['bl_ref_time_range'];
1156            $desc .= '  Dev Up: ' . (isset($message['bl_pct_up'])? $message['bl_pct_up'] : "" ); 1157            $desc .= '  Dev Up: ' . (isset($message['bl_pct_up'])? $message['bl_pct_up'] : "" );
1157            $desc .= '  Dev Down: ' . (isset($message['bl_pct_down'])? $message['bl_pct_down'] : "" ); 1158            $desc .= '  Dev Down: ' . (isset($message['bl_pct_down'])? $message['bl_pct_down'] : "" );
1158            $desc .= '  Trigger: ' . $message['bl_fail_trigger']; 1159            $desc .= '  Trigger: ' . $message['bl_fail_trigger'];
1159  1160 
1160            break; 1161            break;
1161        case 2: 1162        case 2:
1162            $desc .= '  High: ' . $message['time_hi']; 1163            $desc .= '  High: ' . $message['time_hi'];
1163            $desc .= '  Low: ' . $message['time_low']; 1164            $desc .= '  Low: ' . $message['time_low'];
1164            $desc .= '  Trigger: ' . $message['time_fail_trigger']; 1165            $desc .= '  Trigger: ' . $message['time_fail_trigger'];
1165            $desc .= '  Time: ' . plugin_thold_duration_convert($thold['data_template_id'], $message['time_fail_length'], 'alert', 'data_template_id'); 1166            $desc .= '  Time: ' . plugin_thold_duration_convert($thold['data_template_id'], $message['time_fail_length'], 'alert', 'data_template_id');
1166            $desc .= '  Warning High: ' . $message['time_warning_hi']; 1167            $desc .= '  Warning High: ' . $message['time_warning_hi'];
1167            $desc .= '  Warning Low: ' . $message['time_warning_low']; 1168            $desc .= '  Warning Low: ' . $message['time_warning_low'];
1168            $desc .= '  Warning Trigger: ' . $message['time_warning_fail_trigger']; 1169            $desc .= '  Warning Trigger: ' . $message['time_warning_fail_trigger'];
1169            $desc .= '  Warning Time: ' . plugin_thold_duration_convert($thold['data_template_id'], $message['time_warning_fail_length'], 'alert', 'data_template_id'); 1170            $desc .= '  Warning Time: ' . plugin_thold_duration_convert($thold['data_template_id'], $message['time_warning_fail_length'], 'alert', 'data_template_id');
1170  1171 
1171            break; 1172            break;
1172        } 1173        }
1173  1174 
1174        $desc .= '  CDEF: ' . (isset($message['cdef']) ? $message['cdef']: ''); 1175        $desc .= '  CDEF: ' . (isset($message['cdef']) ? $message['cdef']: '');
1175        $desc .= '  ReAlert: ' . plugin_thold_duration_convert($thold['data_template_id'], $message['repeat_alert'], 'alert', 'data_template_id'); 1176        $desc .= '  ReAlert: ' . plugin_thold_duration_convert($thold['data_template_id'], $message['repeat_alert'], 'alert', 'data_template_id');
1176        $desc .= '  Alert Emails: ' . $alert_emails; 1177        $desc .= '  Alert Emails: ' . $alert_emails;
1177        $desc .= '  Warning Emails: ' . $warning_emails; 1178        $desc .= '  Warning Emails: ' . $warning_emails;
1178  1179 
1179        break; 1180        break;
1180    } 1181    }
1181  1182 
1182    if ($desc != '') { 1183    if ($desc != '') {
1183        thold_cacti_log($desc); 1184        thold_cacti_log($desc);
1184    } 1185    }
1185} 1186}
1186  1187 
1187function thold_check_threshold ($rra_id, $data_id, $name, $currentval, $cdef) { 1188function thold_check_threshold ($rra_id, $data_id, $name, $currentval, $cdef) {
1188    global $config, $plugins, $debug; 1189    global $config, $plugins, $debug;
1189  1190 
1190    thold_debug("Checking Threshold:  DS:$name RRA_ID:$rra_id DATA_ID:$data_id VALUE:$currentval"); 1191    thold_debug("Checking Threshold:  DS:$name RRA_ID:$rra_id DATA_ID:$data_id VALUE:$currentval");
1191    $debug = false; 1192    $debug = false;
1192  1193 
1193    // Do not proceed if we have chosen to globally disable all alerts 1194    // Do not proceed if we have chosen to globally disable all alerts
1194    if (read_config_option('thold_disable_all') == 'on') { 1195    if (read_config_option('thold_disable_all') == 'on') {
1195        thold_debug('Threshold checking is disabled globally'); 1196        thold_debug('Threshold checking is disabled globally');
1196        return; 1197        return;
1197    } 1198    }
1198  1199 
1199    $alert_exempt = read_config_option('alert_exempt'); 1200    $alert_exempt = read_config_option('alert_exempt');
1200    /* check for exemptions */  1201    /* check for exemptions */ 
1201    $weekday = date('l'); 1202    $weekday = date('l');
1202    if (($weekday == 'Saturday' || $weekday == 'Sunday') && $alert_exempt == 'on') { 1203    if (($weekday == 'Saturday' || $weekday == 'Sunday') && $alert_exempt == 'on') {
1203        thold_debug('Threshold checking is disabled by global weekend exemption'); 1204        thold_debug('Threshold checking is disabled by global weekend exemption');
1204        return; 1205        return;
1205    } 1206    }
1206  1207 
1207    /* Get all the info about the item from the database */  1208    /* Get all the info about the item from the database */ 
1208    $item = db_fetch_assoc("SELECT * FROM thold_data WHERE thold_enabled='on' AND data_id=" . $data_id); 1209    $item = db_fetch_assoc("SELECT * FROM thold_data WHERE thold_enabled='on' AND data_id=" . $data_id);
1209  1210 
1210    /* return if the item doesn't exist, which means its disabled */  1211    /* return if the item doesn't exist, which means its disabled */ 
1211    if (!isset($item[0])) { 1212    if (!isset($item[0])) {
1212        thold_debug('Threshold is disabled'); 1213        thold_debug('Threshold is disabled');
1213        return; 1214        return;
1214    } 1215    }
1215    $item = $item[0]; 1216    $item = $item[0];
1216  1217 
1217    /* check for the weekend exemption on the threshold level */  1218    /* check for the weekend exemption on the threshold level */ 
1218    if (($weekday == 'Saturday' || $weekday == 'Sunday') && $item['exempt'] == 'on') { 1219    if (($weekday == 'Saturday' || $weekday == 'Sunday') && $item['exempt'] == 'on') {
1219        thold_debug('Threshold checking is disabled by global weekend exemption'); 1220        thold_debug('Threshold checking is disabled by global weekend exemption');
1220        return; 1221        return;
1221    } 1222    }
1222  1223 
1223    /* don't alert for this host if it's selected for maintenance */  1224    /* don't alert for this host if it's selected for maintenance */ 
1224    if (api_plugin_is_enabled('maint') || in_array('maint', $plugins)) { 1225    if (api_plugin_is_enabled('maint') || in_array('maint', $plugins)) {
1225        include_once($config["base_path"] . '/plugins/maint/functions.php'); 1226        include_once($config["base_path"] . '/plugins/maint/functions.php');
1226        if (plugin_maint_check_cacti_host ($item['host_id'])) { 1227        if (plugin_maint_check_cacti_host ($item['host_id'])) {
1227            thold_debug('Threshold checking is disabled by maintenance schedule'); 1228            thold_debug('Threshold checking is disabled by maintenance schedule');
1228            return; 1229            return;
1229        } 1230        }
1230    } 1231    }
1231  1232 
1232    $graph_id = $item['graph_id']; 1233    $graph_id = $item['graph_id'];
1233  1234 
1234    /* only alert if Host is in UP mode (not down, unknown, or recovering) */  1235    /* only alert if Host is in UP mode (not down, unknown, or recovering) */ 
1235    $h = db_fetch_row('SELECT * FROM host WHERE id=' . $item['host_id']); 1236    $h = db_fetch_row('SELECT * FROM host WHERE id=' . $item['host_id']);
1236    if ($h['status'] != 3) { 1237    if ($h['status'] != 3) {
1237        thold_debug('Threshold checking halted by Host Status (' . $h['status'] . ')' ); 1238        thold_debug('Threshold checking halted by Host Status (' . $h['status'] . ')' );
1238        return; 1239        return;
1239    } 1240    }
1240  1241 
1241    /* pull the cached name, if not present, it means that the graph hasn't polled yet */  1242    /* pull the cached name, if not present, it means that the graph hasn't polled yet */ 
1242    $t = db_fetch_assoc('SELECT id, name, name_cache 1243    $t = db_fetch_assoc('SELECT id, name, name_cache
1243        FROM data_template_data 1244        FROM data_template_data
1244        WHERE local_data_id = ' . $rra_id . '  1245        WHERE local_data_id = ' . $rra_id . ' 
1245        ORDER BY id 1246        ORDER BY id
1246        LIMIT 1'); 1247        LIMIT 1');
1247  1248 
1248    /* pull a few default settings */  1249    /* pull a few default settings */ 
1249    $global_alert_address = read_config_option('alert_email'); 1250    $global_alert_address = read_config_option('alert_email');
1250    $global_notify_enabled = (read_config_option('alert_notify_default') == 'on'); 1251    $global_notify_enabled = (read_config_option('alert_notify_default') == 'on');
1251    $logset = (read_config_option('alert_syslog') == 'on'); 1252    $logset = (read_config_option('alert_syslog') == 'on');
1252    $deadnotify = (read_config_option('alert_deadnotify') == 'on'); 1253    $deadnotify = (read_config_option('alert_deadnotify') == 'on');
1253    $realert = read_config_option('alert_repeat'); 1254    $realert = read_config_option('alert_repeat');
1254    $alert_trigger = read_config_option('alert_trigger'); 1255    $alert_trigger = read_config_option('alert_trigger');
1255    $alert_bl_trigger = read_config_option('alert_bl_trigger'); 1256    $alert_bl_trigger = read_config_option('alert_bl_trigger');
1256    $httpurl = read_config_option('alert_base_url'); 1257    $httpurl = read_config_option('alert_base_url');
1257    $thold_show_datasource = read_config_option('thold_show_datasource'); 1258    $thold_show_datasource = read_config_option('thold_show_datasource');
1258    $thold_send_text_only = read_config_option('thold_send_text_only'); 1259    $thold_send_text_only = read_config_option('thold_send_text_only');
1259    $thold_alert_text = read_config_option('thold_alert_text'); 1260    $thold_alert_text = read_config_option('thold_alert_text');
1260    $thold_warning_text = read_config_option('thold_warning_text'); 1261    $thold_warning_text = read_config_option('thold_warning_text');
1261  1262 
1262    /* remove this after adding an option for it */  1263    /* remove this after adding an option for it */ 
1263    $thold_show_datasource = true; 1264    $thold_show_datasource = true;
1264  1265 
1265    $trigger = ($item['thold_fail_trigger'] == '' ? $alert_trigger : $item['thold_fail_trigger']); 1266    $trigger = ($item['thold_fail_trigger'] == '' ? $alert_trigger : $item['thold_fail_trigger']);
1266    $warning_trigger = ($item['thold_warning_fail_trigger'] == '' ? $alert_trigger : $item['thold_warning_fail_trigger']); 1267    $warning_trigger = ($item['thold_warning_fail_trigger'] == '' ? $alert_trigger : $item['thold_warning_fail_trigger']);
1267    $alertstat = $item['thold_alert']; 1268    $alertstat = $item['thold_alert'];
1268  1269 
1269    /* make sure the alert text has been set */  1270    /* make sure the alert text has been set */ 
1270    if (!isset($thold_alert_text) || $thold_alert_text == '') { 1271    if (!isset($thold_alert_text) || $thold_alert_text == '') {
1271        $thold_alert_text = "<html><body>An alert has been issued that requires your attention.<br><br><strong>Host</strong>: <DESCRIPTION> (<HOSTNAME>)<br><strong>URL</strong>: <URL><br><strong>Message</strong>: <SUBJECT><br><br><GRAPH></body></html>"; 1272        $thold_alert_text = "<html><body>一个警告信息已??生,需要?的?注!<br><br><strong>服?器</strong>: <DESCRIPTION> (<HOSTNAME>)<br><strong>URL</strong>: <URL><br><strong>消息</strong>: <SUBJECT><br><br><GRAPH></body></html>";
  1273        /* $thold_alert_text = "<html><body>An alert has been issued that requires your attention.<br><br><strong>Host</strong>: <DESCRIPTION> (<HOSTNAME>)<br><strong>URL</strong>: <URL><br><strong>Message</strong>: <SUBJECT><br><br><GRAPH></body></html>"; */ 
1272    } 1274    }
1273    /* make sure the warning text has been set */  1275    /* make sure the warning text has been set */ 
1274    if (!isset($thold_warning_text) || $thold_warning_text == '') { 1276    if (!isset($thold_warning_text) || $thold_warning_text == '') {
1275        $thold_warning_text = "<html><body>A warning has been issued that requires your attention.<br><br><strong>Host</strong>: <DESCRIPTION> (<HOSTNAME>)<br><strong>URL</strong>: <URL><br><strong>Message</strong>: <SUBJECT><br><br><GRAPH></body></html>"; 1277        $thold_warning_text = "<html><body>一个警告信息已??生,需要?的?注!<br><br><strong>服?器</strong>: <DESCRIPTION> (<HOSTNAME>)<br><strong>URL</strong>: <URL><br><strong>消息</strong>: <SUBJECT><br><br><GRAPH></body></html>";
  1278        /* $thold_warning_text = "<html><body>A warning has been issued that requires your attention.<br><br><strong>Host</strong>: <DESCRIPTION> (<HOSTNAME>)<br><strong>URL</strong>: <URL><br><strong>Message</strong>: <SUBJECT><br><br><GRAPH></body></html>"; */ 
1276    } 1279    }
1277  1280 
1278    $hostname = db_fetch_row('SELECT description, hostname from host WHERE id = ' . $item['host_id']); 1281    $hostname = db_fetch_row('SELECT description, hostname from host WHERE id = ' . $item['host_id']);
1279  1282 
1280    $rows = db_fetch_assoc('SELECT plugin_thold_contacts.data 1283    $rows = db_fetch_assoc('SELECT plugin_thold_contacts.data
1281        FROM plugin_thold_contacts, plugin_thold_threshold_contact 1284        FROM plugin_thold_contacts, plugin_thold_threshold_contact
1282        WHERE plugin_thold_contacts.id=plugin_thold_threshold_contact.contact_id 1285        WHERE plugin_thold_contacts.id=plugin_thold_threshold_contact.contact_id
1283        AND plugin_thold_threshold_contact.thold_id = ' . $item['id']); 1286        AND plugin_thold_threshold_contact.thold_id = ' . $item['id']);
1284  1287 
1285    $alert_emails = ''; 1288    $alert_emails = '';
1286    if (read_config_option('thold_disable_legacy') != 'on') { 1289    if (read_config_option('thold_disable_legacy') != 'on') {
1287        $alert_emails = array(); 1290        $alert_emails = array();
1288        if (count($rows)) { 1291        if (count($rows)) {
1289            foreach ($rows as $row) { 1292            foreach ($rows as $row) {
1290                $alert_emails[] = $row['data']; 1293                $alert_emails[] = $row['data'];
1291            } 1294            }
1292        } 1295        }
1293  1296 
1294        $alert_emails = implode(',', $alert_emails); 1297        $alert_emails = implode(',', $alert_emails);
1295        if ($alert_emails != '') { 1298        if ($alert_emails != '') {
1296            $alert_emails .= ',' . $item['notify_extra']; 1299            $alert_emails .= ',' . $item['notify_extra'];
1297        } else { 1300        } else {
1298            $alert_emails = $item['notify_extra']; 1301            $alert_emails = $item['notify_extra'];
1299        } 1302        }
1300    } 1303    }
1301  1304 
1302    $alert_emails .= (strlen($alert_emails) ? ",":"") . get_thold_notification_emails($item['notify_alert']); 1305    $alert_emails .= (strlen($alert_emails) ? ",":"") . get_thold_notification_emails($item['notify_alert']);
1303  1306 
1304    $warning_emails = ''; 1307    $warning_emails = '';
1305    if (read_config_option('thold_disable_legacy') != 'on') { 1308    if (read_config_option('thold_disable_legacy') != 'on') {
1306        $warning_emails = $item['notify_warning_extra']; 1309        $warning_emails = $item['notify_warning_extra'];
1307    } 1310    }
1308  1311 
1309    $warning_emails .= (strlen($warning_emails) ? ",":"") . get_thold_notification_emails($item['notify_warning']); 1312    $warning_emails .= (strlen($warning_emails) ? ",":"") . get_thold_notification_emails($item['notify_warning']);
1310  1313 
1311    $types = array('High/Low', 'Baseline Deviation', 'Time Based'); 1314    $types = array('High/Low', 'Baseline Deviation', 'Time Based');
1312  1315 
1313    // Do some replacement of variables 1316    // Do some replacement of variables
1314    $thold_alert_text = str_replace('<DESCRIPTION>', $hostname['description'], $thold_alert_text); 1317    $thold_alert_text = str_replace('<DESCRIPTION>', $hostname['description'], $thold_alert_text);
1315    $thold_alert_text = str_replace('<HOSTNAME>', $hostname['hostname'], $thold_alert_text); 1318    $thold_alert_text = str_replace('<HOSTNAME>', $hostname['hostname'], $thold_alert_text);
1316    $thold_alert_text = str_replace('<TIME>', time(), $thold_alert_text); 1319    $thold_alert_text = str_replace('<TIME>', time(), $thold_alert_text);
1317    $thold_alert_text = str_replace('<GRAPHID>', $graph_id, $thold_alert_text); 1320    $thold_alert_text = str_replace('<GRAPHID>', $graph_id, $thold_alert_text);
1318    $thold_alert_text = str_replace('<URL>', "<a href='$httpurl/graph.php?local_graph_id=$graph_id&rra_id=1'>$httpurl/graph.php?local_graph_id=$graph_id&rra_id=1</a>", $thold_alert_text); 1321    $thold_alert_text = str_replace('<URL>', "<a href='$httpurl/graph.php?local_graph_id=$graph_id&rra_id=1'>$httpurl/graph.php?local_graph_id=$graph_id&rra_id=1</a>", $thold_alert_text);
1319    $thold_alert_text = str_replace('<CURRENTVALUE>', $currentval, $thold_alert_text); 1322    $thold_alert_text = str_replace('<CURRENTVALUE>', $currentval, $thold_alert_text);
1320    $thold_alert_text = str_replace('<THRESHOLDNAME>', $item['name'], $thold_alert_text); 1323    $thold_alert_text = str_replace('<THRESHOLDNAME>', $item['name'], $thold_alert_text);
1321    $thold_alert_text = str_replace('<DSNAME>', $name, $thold_alert_text); 1324    $thold_alert_text = str_replace('<DSNAME>', $name, $thold_alert_text);
1322    $thold_alert_text = str_replace('<THOLDTYPE>', $types[$item['thold_type']], $thold_alert_text); 1325    $thold_alert_text = str_replace('<THOLDTYPE>', $types[$item['thold_type']], $thold_alert_text);
1323    $thold_alert_text = str_replace('<HI>', ($item['thold_type'] == 0 ? $item['thold_hi'] : ($item['thold_type'] == 2 ? $item['time_hi'] : '')), $thold_alert_text); 1326    $thold_alert_text = str_replace('<HI>', ($item['thold_type'] == 0 ? $item['thold_hi'] : ($item['thold_type'] == 2 ? $item['time_hi'] : '')), $thold_alert_text);
1324    $thold_alert_text = str_replace('<LOW>', ($item['thold_type'] == 0 ? $item['thold_low'] : ($item['thold_type'] == 2 ? $item['time_low'] : '')), $thold_alert_text); 1327    $thold_alert_text = str_replace('<LOW>', ($item['thold_type'] == 0 ? $item['thold_low'] : ($item['thold_type'] == 2 ? $item['time_low'] : '')), $thold_alert_text);
1325    $thold_alert_text = str_replace('<TRIGGER>', ($item['thold_type'] == 0 ? $item['thold_fail_trigger'] : ($item['thold_type'] == 2 ? $item['time_fail_trigger'] : '')), $thold_alert_text); 1328    $thold_alert_text = str_replace('<TRIGGER>', ($item['thold_type'] == 0 ? $item['thold_fail_trigger'] : ($item['thold_type'] == 2 ? $item['time_fail_trigger'] : '')), $thold_alert_text);
1326    $thold_alert_text = str_replace('<DURATION>', ($item['thold_type'] == 2 ? plugin_thold_duration_convert($item['rra_id'], $item['time_fail_length'], 'time') : ''), $thold_alert_text); 1329    $thold_alert_text = str_replace('<DURATION>', ($item['thold_type'] == 2 ? plugin_thold_duration_convert($item['rra_id'], $item['time_fail_length'], 'time') : ''), $thold_alert_text);
1327    $thold_alert_text = str_replace('<DATE_RFC822>', date(DATE_RFC822), $thold_alert_text); 1330    $thold_alert_text = str_replace('<DATE_RFC822>', date(DATE_RFC822), $thold_alert_text);
1328    $thold_alert_text = str_replace('<DEVICENOTE>', $h['notes'], $thold_alert_text); 1331    $thold_alert_text = str_replace('<DEVICENOTE>', $h['notes'], $thold_alert_text);
1329  1332 
1330    // Do some replacement of variables 1333    // Do some replacement of variables
1331    $thold_warning_text = str_replace('<DESCRIPTION>', $hostname['description'], $thold_warning_text); 1334    $thold_warning_text = str_replace('<DESCRIPTION>', $hostname['description'], $thold_warning_text);
1332    $thold_warning_text = str_replace('<HOSTNAME>', $hostname['hostname'], $thold_warning_text); 1335    $thold_warning_text = str_replace('<HOSTNAME>', $hostname['hostname'], $thold_warning_text);
1333    $thold_warning_text = str_replace('<TIME>', time(), $thold_warning_text); 1336    $thold_warning_text = str_replace('<TIME>', time(), $thold_warning_text);
1334    $thold_warning_text = str_replace('<GRAPHID>', $graph_id, $thold_warning_text); 1337    $thold_warning_text = str_replace('<GRAPHID>', $graph_id, $thold_warning_text);
1335    $thold_warning_text = str_replace('<URL>', "<a href='$httpurl/graph.php?local_graph_id=$graph_id&rra_id=1'>$httpurl/graph.php?local_graph_id=$graph_id&rra_id=1</a>", $thold_warning_text); 1338    $thold_warning_text = str_replace('<URL>', "<a href='$httpurl/graph.php?local_graph_id=$graph_id&rra_id=1'>$httpurl/graph.php?local_graph_id=$graph_id&rra_id=1</a>", $thold_warning_text);
1336    $thold_warning_text = str_replace('<CURRENTVALUE>', $currentval, $thold_warning_text); 1339    $thold_warning_text = str_replace('<CURRENTVALUE>', $currentval, $thold_warning_text);
1337    $thold_warning_text = str_replace('<THRESHOLDNAME>', $item['name'], $thold_warning_text); 1340    $thold_warning_text = str_replace('<THRESHOLDNAME>', $item['name'], $thold_warning_text);
1338    $thold_warning_text = str_replace('<DSNAME>', $name, $thold_warning_text); 1341    $thold_warning_text = str_replace('<DSNAME>', $name, $thold_warning_text);
1339    $thold_warning_text = str_replace('<THOLDTYPE>', $types[$item['thold_type']], $thold_warning_text); 1342    $thold_warning_text = str_replace('<THOLDTYPE>', $types[$item['thold_type']], $thold_warning_text);
1340    $thold_warning_text = str_replace('<HI>', ($item['thold_type'] == 0 ? $item['thold_hi'] : ($item['thold_type'] == 2 ? $item['time_warning_hi'] : '')), $thold_warning_text); 1343    $thold_warning_text = str_replace('<HI>', ($item['thold_type'] == 0 ? $item['thold_hi'] : ($item['thold_type'] == 2 ? $item['time_warning_hi'] : '')), $thold_warning_text);
1341    $thold_warning_text = str_replace('<LOW>', ($item['thold_type'] == 0 ? $item['thold_low'] : ($item['thold_type'] == 2 ? $item['time_warning_low'] : '')), $thold_warning_text); 1344    $thold_warning_text = str_replace('<LOW>', ($item['thold_type'] == 0 ? $item['thold_low'] : ($item['thold_type'] == 2 ? $item['time_warning_low'] : '')), $thold_warning_text);
1342    $thold_warning_text = str_replace('<TRIGGER>', ($item['thold_type'] == 0 ? $item['thold_warning_fail_trigger'] : ($item['thold_type'] == 2 ? $item['time_warning_fail_trigger'] : '')), $thold_warning_text); 1345    $thold_warning_text = str_replace('<TRIGGER>', ($item['thold_type'] == 0 ? $item['thold_warning_fail_trigger'] : ($item['thold_type'] == 2 ? $item['time_warning_fail_trigger'] : '')), $thold_warning_text);
1343    $thold_warning_text = str_replace('<DURATION>', ($item['thold_type'] == 2 ? plugin_thold_duration_convert($item['rra_id'], $item['time_warning_fail_length'], 'time') : ''), $thold_warning_text); 1346    $thold_warning_text = str_replace('<DURATION>', ($item['thold_type'] == 2 ? plugin_thold_duration_convert($item['rra_id'], $item['time_warning_fail_length'], 'time') : ''), $thold_warning_text);
1344    $thold_warning_text = str_replace('<DATE_RFC822>', date(DATE_RFC822), $thold_warning_text); 1347    $thold_warning_text = str_replace('<DATE_RFC822>', date(DATE_RFC822), $thold_warning_text);
1345    $thold_warning_text = str_replace('<DEVICENOTE>', $h['notes'], $thold_warning_text); 1348    $thold_warning_text = str_replace('<DEVICENOTE>', $h['notes'], $thold_warning_text);
1346  1349 
1347    $msg = $thold_alert_text; 1350    $msg = $thold_alert_text;
1348    $warn_msg = $thold_warning_text; 1351    $warn_msg = $thold_warning_text;
  1352    $process = "pr_count";
1349  1353 
1350    if ($thold_send_text_only == 'on') { 1354    if ($thold_send_text_only == 'on') {
1351        $file_array = ''; 1355        $file_array = '';
1352    } else { 1356    } else {
1353        $file_array = array(0 => array('local_graph_id' => $graph_id, 'rra_id' => 0, 'file' => "$httpurl/graph_image.php?local_graph_id=$graph_id&rra_id=0&view_type=tree",'mimetype'=>'image/png','filename'=>$graph_id)); 1357        $file_array = array(0 => array('local_graph_id' => $graph_id, 'rra_id' => 0, 'file' => "$httpurl/graph_image.php?local_graph_id=$graph_id&rra_id=0&view_type=tree",'mimetype'=>'image/png','filename'=>$graph_id));
1354    } 1358    }
1355  1359 
1356    $url = $httpurl . "/graph.php?local_graph_id=" . $graph_id ."&rra_id=all"; 1360    $url = $httpurl . "/graph.php?local_graph_id=" . $graph_id ."&rra_id=all";
1357  1361 
1358    switch ($item['thold_type']) { 1362    switch ($item['thold_type']) {
1359    case 0:   /* hi/low */  1363    case 0:   /* hi/low */ 
1360        if ($currentval != '') { 1364        if ($currentval != '') {
1361            $breach_up = ($item['thold_hi'] != '' && $currentval > $item['thold_hi']); 1365            $breach_up = ($item['thold_hi'] != '' && $currentval > $item['thold_hi']);
1362            $breach_down = ($item['thold_low'] != '' && $currentval < $item['thold_low']); 1366            $breach_down = ($item['thold_low'] != '' && $currentval < $item['thold_low']);
1363            $warning_breach_up = ($item['thold_warning_hi'] != '' && $currentval > $item['thold_warning_hi']); 1367            $warning_breach_up = ($item['thold_warning_hi'] != '' && $currentval > $item['thold_warning_hi']);
1364            $warning_breach_down = ($item['thold_warning_low'] != '' && $currentval < $item['thold_warning_low']); 1368            $warning_breach_down = ($item['thold_warning_low'] != '' && $currentval < $item['thold_warning_low']);
1365        } else { 1369        } else {
1366            $breach_up = $breach_down = $warning_breach_up = $warning_breach_down = false; 1370            $breach_up = $breach_down = $warning_breach_up = $warning_breach_down = false;
1367        } 1371        }
1368  1372 
1369        /* is in alert status */  1373        /* is in alert status */ 
1370        if ($breach_up || $breach_down) { 1374        if ($breach_up || $breach_down) {
1371            $notify = false; 1375            $notify = false;
1372  1376 
1373            thold_debug('Threshold HI / Low check breached HI:' . $item['thold_hi'] . '  LOW:' . $item['thold_low'] . ' VALUE:' . $currentval); 1377            thold_debug('Threshold HI / Low check breached HI:' . $item['thold_hi'] . '  LOW:' . $item['thold_low'] . ' VALUE:' . $currentval);
1374  1378 
1375            $item['thold_fail_count']++; 1379            $item['thold_fail_count']++;
1376            $item['thold_alert'] = ($breach_up ? STAT_HI : STAT_LO); 1380            $item['thold_alert'] = ($breach_up ? STAT_HI : STAT_LO);
1377  1381 
1378            /* Re-Alert? */  1382            /* Re-Alert? */ 
1379            $ra = ($item['thold_fail_count'] > $trigger && $item['repeat_alert'] != 0 && $item['thold_fail_count'] % $item['repeat_alert'] == 0); 1383            $ra = ($item['thold_fail_count'] > $trigger && $item['repeat_alert'] != 0 && $item['thold_fail_count'] % $item['repeat_alert'] == 0);
1380  1384 
1381            if ($item['thold_fail_count'] == $trigger || $ra) { 1385            if ($item['thold_fail_count'] == $trigger || $ra) {
1382                $notify = true; 1386                $notify = true;
1383            } 1387            }
1384  1388 
1385            $subject = "ALERT: " . $item['name'] . ($thold_show_datasource ? " [$name]" : '') . ' ' . ($ra ? 'is still' : 'went') . ' ' . ($breach_up ? 'above' : 'below') . ' threshold of ' . ($breach_up ? $item['thold_hi'] : $item['thold_low']) . " with $currentval";  1389            if (strstr($name,$process)) { 
1386            if ($notify) {  1390                $subject = "?重警示: " . (iconv("UTF-8", "GB2312//IGNORE", $item['name'])). '?程'. ($ra ? '仍然' : '目前') . ($breach_up ? '高于' : '?常消失或不存在') . ",当前??:$currentval" . ',而非正常的' . ($breach_up ? $item['thold_hi'] : $item['thold_low']) . ',?尽快?理!'; 
  1391                } else {
  1392                     $subject = "?重警示: " . (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . ($thold_show_datasource ? " [$name]" : '') . ' ' . ($ra ? '仍然' : '?在') . ' ' . ($breach_up ? '高于' : '低于') . ' ????的 ' . ($breach_up ? $item['thold_hi'] : $item['thold_low']) . " 当前??: $currentval";
  1393        }
  1394        if ($notify) {
1387                thold_debug('Alerting is necessary'); 1395                thold_debug('Alerting is necessary');
1388  1396 
1389                if ($logset == 1) { 1397                if ($logset == 1) {
1390                    logger($item['name'], $breach_up, ($breach_up ? $item['thold_hi'] : $item['thold_low']), $currentval, $trigger, $item['thold_fail_count'], $url); 1398                    logger($item['name'], $breach_up, ($breach_up ? $item['thold_hi'] : $item['thold_low']), $currentval, $trigger, $item['thold_fail_count'], $url);
1391                } 1399                }
1392  1400 
1393                if (trim($alert_emails) != '') { 1401                if (trim($alert_emails) != '') {
1394                    thold_mail($alert_emails, '', $subject, $msg, $file_array); 1402                    thold_mail($alert_emails, '', $subject, $msg, $file_array);
1395                } 1403                }
1396  1404 
1397                thold_log(array( 1405                thold_log(array(
1398                    'type' => 0, 1406                    'type' => 0,
1399                    'time' => time(), 1407                    'time' => time(),
1400                    'host_id' => $item['host_id'], 1408                    'host_id' => $item['host_id'],
1401                    'graph_id' => $graph_id, 1409                    'graph_id' => $graph_id,
1402                    'threshold_id' => $item['id'], 1410                    'threshold_id' => $item['id'],
1403                    'threshold_value' => ($breach_up ? $item['thold_hi'] : $item['thold_low']), 1411                    'threshold_value' => ($breach_up ? $item['thold_hi'] : $item['thold_low']),
1404                    'current' => $currentval, 1412                    'current' => $currentval,
1405                    'status' => ($ra ? ST_NOTIFYRA:ST_NOTIFYAL), 1413                    'status' => ($ra ? ST_NOTIFYRA:ST_NOTIFYAL),
1406                    'description' => $subject, 1414                    'description' => $subject,
1407                    'emails' => $alert_emails)); 1415                    'emails' => $alert_emails));
1408            } 1416            }
1409  1417 
1410            db_execute("UPDATE thold_data 1418            db_execute("UPDATE thold_data
1411                SET thold_alert=" . $item['thold_alert'] . ", 1419                SET thold_alert=" . $item['thold_alert'] . ",
1412                thold_fail_count=" . $item['thold_fail_count'] . ", 1420                thold_fail_count=" . $item['thold_fail_count'] . ",
1413                thold_warning_fail_count=0 1421                thold_warning_fail_count=0
1414                WHERE rra_id=$rra_id AND data_id=" . $item['data_id']); 1422                WHERE rra_id=$rra_id AND data_id=" . $item['data_id']);
1415        } elseif ($warning_breach_up || $warning_breach_down) { 1423        } elseif ($warning_breach_up || $warning_breach_down) {
1416            $notify = false; 1424            $notify = false;
1417  1425 
1418            thold_debug('Threshold HI / Low Warning check breached HI:' . $item['thold_warning_hi'] . '  LOW:' . $item['thold_warning_low'] . ' VALUE:' . $currentval); 1426            thold_debug('Threshold HI / Low Warning check breached HI:' . $item['thold_warning_hi'] . '  LOW:' . $item['thold_warning_low'] . ' VALUE:' . $currentval);
1419  1427 
1420            $item['thold_warning_fail_count']++; 1428            $item['thold_warning_fail_count']++;
1421            $item['thold_alert'] = ($warning_breach_up ? STAT_HI:STAT_LO); 1429            $item['thold_alert'] = ($warning_breach_up ? STAT_HI:STAT_LO);
1422  1430 
1423            /* re-alert? */  1431            /* re-alert? */ 
1424            $ra = ($item['thold_warning_fail_count'] > $warning_trigger && $item['repeat_alert'] != 0 && $item['thold_warning_fail_count'] % $item['repeat_alert'] == 0); 1432            $ra = ($item['thold_warning_fail_count'] > $warning_trigger && $item['repeat_alert'] != 0 && $item['thold_warning_fail_count'] % $item['repeat_alert'] == 0);
1425  1433 
1426            if ($item['thold_warning_fail_count'] == $warning_trigger || $ra) { 1434            if ($item['thold_warning_fail_count'] == $warning_trigger || $ra) {
1427                $notify = true; 1435                $notify = true;
1428            } 1436            }
1429  1437      if (strstr($name,$process)) { 
1430            $subject = ($notify ? "WARNING: ":"TRIGGER: ") . $item['name'] . ($thold_show_datasource ? " [$name]" : '') . ' ' . ($ra ? 'is still' : 'went') . ' ' . ($warning_breach_up ? 'above' : 'below') . ' threshold of ' . ($warning_breach_up ? $item['thold_warning_hi'] : $item['thold_warning_low']) . " with $currentval"; 1438                    $subject = ($notify ? "警告: ":"触?: ") . (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . '?程' . ($ra ? '仍然' : '?在') . ($breach_up ? '高于' : '?常消失或不存在') . ",当前??:$currentval" . ',而非正常的' . ($breach_up ? $item['thold_hi'] : $item['thold_low']) . ',?尽快?理!';
1431  1439                    } else { 
  1440                         $subject = ($notify ? "警告: ":"触?: ") . (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . ($thold_show_datasource ? " [$name]" : '') . ' ' . ($ra ? '仍然' : '?在') . ' ' . ($warning_breach_up ? '高于' : '低于') . ' ????的 ' . ($warning_breach_up ? $item['thold_warning_hi'] : $item['thold_warning_low']) . " 当前??: $currentval";
  1441         }
1432            if ($notify) { 1442            if ($notify) {
1433                thold_debug('Alerting is necessary'); 1443                thold_debug('Alerting is necessary');
1434  1444 
1435                if ($logset == 1) { 1445                if ($logset == 1) {
1436                    logger($item['name'], 'warning', ($warning_breach_up ? $item['thold_warning_hi'] : $item['thold_warning_low']), $currentval, $warning_trigger, $item['thold_warning_fail_count'], $url); 1446                    logger($item['name'], 'warning', ($warning_breach_up ? $item['thold_warning_hi'] : $item['thold_warning_low']), $currentval, $warning_trigger, $item['thold_warning_fail_count'], $url);
1437                } 1447                }
1438  1448 
1439                if (trim($warning_emails) != '') { 1449                if (trim($warning_emails) != '') {
1440                    thold_mail($warning_emails, '', $subject, $warn_msg, $file_array); 1450                    thold_mail($warning_emails, '', $subject, $warn_msg, $file_array);
1441                } 1451                }
1442  1452 
1443                thold_log(array( 1453                thold_log(array(
1444                    'type' => 0, 1454                    'type' => 0,
1445                    'time' => time(), 1455                    'time' => time(),
1446                    'host_id' => $item['host_id'], 1456                    'host_id' => $item['host_id'],
1447                    'graph_id' => $graph_id, 1457                    'graph_id' => $graph_id,
1448                    'threshold_id' => $item['id'], 1458                    'threshold_id' => $item['id'],
1449                    'threshold_value' => ($warning_breach_up ? $item['thold_warning_hi'] : $item['thold_warning_low']), 1459                    'threshold_value' => ($warning_breach_up ? $item['thold_warning_hi'] : $item['thold_warning_low']),
1450                    'current' => $currentval, 1460                    'current' => $currentval,
1451                    'status' => ($ra ? ST_NOTIFYRA:ST_NOTIFYWA), 1461                    'status' => ($ra ? ST_NOTIFYRA:ST_NOTIFYWA),
1452                    'description' => $subject, 1462                    'description' => $subject,
1453                    'emails' => $alert_emails)); 1463                    'emails' => $alert_emails));
1454            }elseif (($item['thold_warning_fail_count'] >= $warning_trigger) && ($item['thold_fail_count'] >= $trigger)) { 1464            }elseif (($item['thold_warning_fail_count'] >= $warning_trigger) && ($item['thold_fail_count'] >= $trigger)) {
1455                $subject = "ALERT -> WARNING: ". $item['name'] . ($thold_show_datasource ? " [$name]" : '') . " Changed to Warning Threshold with Value $currentval";  1465                if (strstr($name,$process)) { 
1456  1466                    $subject = "?警事件状?改?,从:?重警示 -> 警告: ". (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . '?程' . " 恢?至警告状?,??: $currentval"; 
  1467                    } else {
  1468                           $subject = "?警事件状?改?,从:?重警示 -> 警告: ". (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . ($thold_show_datasource ? " [$name]" : '') . " 恢?至警告状?,??: $currentval";
  1469                }
1457                if (trim($alert_emails) != '') { 1470                if (trim($alert_emails) != '') {
1458                    thold_mail($alert_emails, '', $subject, $warn_msg, $file_array); 1471                    thold_mail($alert_emails, '', $subject, $warn_msg, $file_array);
1459                } 1472                }
1460  1473 
1461                thold_log(array( 1474                thold_log(array(
1462                    'type' => 0, 1475                    'type' => 0,
1463                    'time' => time(), 1476                    'time' => time(),
1464                    'host_id' => $item['host_id'], 1477                    'host_id' => $item['host_id'],
1465                    'graph_id' => $graph_id, 1478                    'graph_id' => $graph_id,
1466                    'threshold_id' => $item['id'], 1479                    'threshold_id' => $item['id'],
1467                    'threshold_value' => ($warning_breach_up ? $item['thold_warning_hi'] : $item['thold_warning_low']), 1480                    'threshold_value' => ($warning_breach_up ? $item['thold_warning_hi'] : $item['thold_warning_low']),
1468                    'current' => $currentval, 1481                    'current' => $currentval,
1469                    'status' => ST_NOTIFYAW, 1482                    'status' => ST_NOTIFYAW,
1470                    'description' => $subject, 1483                    'description' => $subject,
1471                    'emails' => $alert_emails)); 1484                    'emails' => $alert_emails));
1472            } 1485            }
1473  1486 
1474            db_execute("UPDATE thold_data 1487            db_execute("UPDATE thold_data
1475                SET thold_alert=" . $item['thold_alert'] . ", 1488                SET thold_alert=" . $item['thold_alert'] . ",
1476                thold_warning_fail_count=" . $item['thold_warning_fail_count'] . ", 1489                thold_warning_fail_count=" . $item['thold_warning_fail_count'] . ",
1477                thold_fail_count=0 1490                thold_fail_count=0
1478                WHERE rra_id=$rra_id AND data_id=" . $item['data_id']); 1491                WHERE rra_id=$rra_id AND data_id=" . $item['data_id']);
1479        } else { 1492        } else {
1480            thold_debug('Threshold HI / Low check is normal HI:' . $item['thold_hi'] . '  LOW:' . $item['thold_low'] . ' VALUE:' . $currentval); 1493            thold_debug('Threshold HI / Low check is normal HI:' . $item['thold_hi'] . '  LOW:' . $item['thold_low'] . ' VALUE:' . $currentval);
1481  1494 
1482            /* if we were at an alert status before */  1495            /* if we were at an alert status before */ 
1483            if ($alertstat != 0) { 1496            if ($alertstat != 0) {
1484                $subject = "NORMAL: ". $item['name'] . ($thold_show_datasource ? " [$name]" : '') . " Restored to Normal Threshold with Value $currentval";  1497                if (strstr($name,$process)) { 
1485  1498                    $subject = "恢?正常: ". (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . '?程' . " 恢?至正常状?,??: $currentval"; 
  1499                    } else {
  1500                             $subject = "恢?正常: ". (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . ($thold_show_datasource ? " [$name]" : '') . " 恢?至正常状?,??: $currentval";
  1501          }
1486                db_execute("UPDATE thold_data 1502                db_execute("UPDATE thold_data
1487                    SET thold_alert=0, thold_fail_count=0, thold_warning_fail_count=0 1503                    SET thold_alert=0, thold_fail_count=0, thold_warning_fail_count=0
1488                    WHERE rra_id=$rra_id AND data_id=" . $item['data_id']); 1504                    WHERE rra_id=$rra_id AND data_id=" . $item['data_id']);
1489  1505 
1490                if ($item['thold_warning_fail_count'] >= $warning_trigger && $item['restored_alert'] != 'on') { 1506                if ($item['thold_warning_fail_count'] >= $warning_trigger && $item['restored_alert'] != 'on') {
1491                    if ($logset == 1) { 1507                    if ($logset == 1) {
1492                        logger($item['name'], 'ok', 0, $currentval, $warning_trigger, $item['thold_warning_fail_count'], $url); 1508                        logger($item['name'], 'ok', 0, $currentval, $warning_trigger, $item['thold_warning_fail_count'], $url);
1493                    } 1509                    }
1494  1510 
1495                    if (trim($warning_emails) != '' && $item['restored_alert'] != 'on') { 1511                    if (trim($warning_emails) != '' && $item['restored_alert'] != 'on') {
1496                        thold_mail($warning_emails, '', $subject, $warn_msg, $file_array); 1512                        thold_mail($warning_emails, '', $subject, $warn_msg, $file_array);
1497                    } 1513                    }
1498  1514 
1499                    thold_log(array( 1515                    thold_log(array(
1500                        'type' => 0, 1516                        'type' => 0,
1501                        'time' => time(), 1517                        'time' => time(),
1502                        'host_id' => $item['host_id'], 1518                        'host_id' => $item['host_id'],
1503                        'graph_id' => $graph_id, 1519                        'graph_id' => $graph_id,
1504                        'threshold_id' => $item['id'], 1520                        'threshold_id' => $item['id'],
1505                        'threshold_value' => '', 1521                        'threshold_value' => '',
1506                        'current' => $currentval, 1522                        'current' => $currentval,
1507                        'status' => ST_NOTIFYRS, 1523                        'status' => ST_NOTIFYRS,
1508                        'description' => $subject, 1524                        'description' => $subject,
1509                        'emails' => $warning_emails)); 1525                        'emails' => $warning_emails));
1510                } elseif ($item['thold_fail_count'] >= $trigger && $item['restored_alert'] != 'on') { 1526                } elseif ($item['thold_fail_count'] >= $trigger && $item['restored_alert'] != 'on') {
1511                    if ($logset == 1) { 1527                    if ($logset == 1) {
1512                        logger($item['name'], 'warning', 0, $currentval, $trigger, $item['thold_fail_count'], $url); 1528                        logger($item['name'], 'warning', 0, $currentval, $trigger, $item['thold_fail_count'], $url);
1513                    } 1529                    }
1514  1530 
1515                    if (trim($alert_emails) != '' && $item['restored_alert'] != 'on') { 1531                    if (trim($alert_emails) != '' && $item['restored_alert'] != 'on') {
1516                        thold_mail($alert_emails, '', $subject, $msg, $file_array); 1532                        thold_mail($alert_emails, '', $subject, $msg, $file_array);
1517                    } 1533                    }
1518  1534 
1519                    thold_log(array( 1535                    thold_log(array(
1520                        'type' => 0, 1536                        'type' => 0,
1521                        'time' => time(), 1537                        'time' => time(),
1522                        'host_id' => $item['host_id'], 1538                        'host_id' => $item['host_id'],
1523                        'graph_id' => $graph_id, 1539                        'graph_id' => $graph_id,
1524                        'threshold_id' => $item['id'], 1540                        'threshold_id' => $item['id'],
1525                        'threshold_value' => '', 1541                        'threshold_value' => '',
1526                        'current' => $currentval, 1542                        'current' => $currentval,
1527                        'status' => ST_NOTIFYRS, 1543                        'status' => ST_NOTIFYRS,
1528                        'description' => $subject, 1544                        'description' => $subject,
1529                        'emails' => $alert_emails)); 1545                        'emails' => $alert_emails));
1530                } 1546                }
1531            } 1547            }
1532        } 1548        }
1533  1549 
1534        break; 1550        break;
1535    case 1:   /* baseline */  1551    case 1:   /* baseline */ 
1536        $bl_alert_prev = $item['bl_alert']; 1552        $bl_alert_prev = $item['bl_alert'];
1537        $bl_count_prev = $item['bl_fail_count']; 1553        $bl_count_prev = $item['bl_fail_count'];
1538        $bl_fail_trigger = ($item['bl_fail_trigger'] == '' ? $alert_bl_trigger : $item['bl_fail_trigger']); 1554        $bl_fail_trigger = ($item['bl_fail_trigger'] == '' ? $alert_bl_trigger : $item['bl_fail_trigger']);
1539        $item['bl_alert'] = thold_check_baseline($rra_id, $name, $currentval, $item); 1555        $item['bl_alert'] = thold_check_baseline($rra_id, $name, $currentval, $item);
1540  1556 
1541        switch($item['bl_alert']) { 1557        switch($item['bl_alert']) {
1542        case -2:   /* exception is active, Future Release 'todo' */  1558        case -2:   /* exception is active, Future Release 'todo' */ 
1543            break; 1559            break;
1544        case -1:   /* reference value not available, Future Release 'todo' */  1560        case -1:   /* reference value not available, Future Release 'todo' */ 
1545            break; 1561            break;
1546        case 0:       /* all clear */  1562        case 0:       /* all clear */ 
1547            /* if we were at an alert status before */  1563            /* if we were at an alert status before */ 
1548            if ($alertstat != 0) { 1564            if ($alertstat != 0) {
1549                thold_debug('Threshold Baseline check is normal'); 1565                thold_debug('Threshold Baseline check is normal');
1550  1566 
1551                if ($item['bl_fail_count'] >= $bl_fail_trigger && $item['restored_alert'] != 'on') { 1567                if ($item['bl_fail_count'] >= $bl_fail_trigger && $item['restored_alert'] != 'on') {
1552                    thold_debug('Threshold Baseline check returned to normal'); 1568                    thold_debug('Threshold Baseline check returned to normal');
1553  1569 
1554                    if ($logset == 1) { 1570                    if ($logset == 1) {
1555                        logger($item['name'], 'ok', 0, $currentval, $item['bl_fail_trigger'], $item['bl_fail_count'], $url); 1571                        logger($item['name'], 'ok', 0, $currentval, $item['bl_fail_trigger'], $item['bl_fail_count'], $url);
1556                    } 1572                    }
1557  1573          if (strstr($name,$process)) { 
1558                    $subject = "NORMAL: " . $item['name'] . ($thold_show_datasource ? " [$name]" : '') . " restored to normal threshold with value $currentval"; 1574                    $subject = "恢?正常: " . (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . '?程' . "重新恢?恢?正常,其??: $currentval";
1559  1575                    } else { 
  1576                             $subject = "恢?正常: " . (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . ($thold_show_datasource ? " [$name]" : '') . " 恢?至正常状?,??: $currentval";
  1577          }
1560                    if (trim($alert_emails) != '') { 1578                    if (trim($alert_emails) != '') {
1561                        thold_mail($alert_emails, '', $subject, $msg, $file_array); 1579                        thold_mail($alert_emails, '', $subject, $msg, $file_array);
1562                    } 1580                    }
1563  1581 
1564                    thold_log(array( 1582                    thold_log(array(
1565                        'type' => 1, 1583                        'type' => 1,
1566                        'time' => time(), 1584                        'time' => time(),
1567                        'host_id' => $item['host_id'], 1585                        'host_id' => $item['host_id'],
1568                        'graph_id' => $graph_id, 1586                        'graph_id' => $graph_id,
1569                        'threshold_id' => $item['id'], 1587                        'threshold_id' => $item['id'],
1570                        'threshold_value' => '', 1588                        'threshold_value' => '',
1571                        'current' => $currentval, 1589                        'current' => $currentval,
1572                        'status' => ST_NOTIFYRA, 1590                        'status' => ST_NOTIFYRA,
1573                        'description' => $subject, 1591                        'description' => $subject,
1574                        'emails' => $alert_emails)); 1592                        'emails' => $alert_emails));
1575                } 1593                }
1576            } 1594            }
1577  1595 
1578            $item['bl_fail_count'] = 0; 1596            $item['bl_fail_count'] = 0;
1579  1597 
1580            break; 1598            break;
1581        case 1: /* value is below calculated threshold */  1599        case 1: /* value is below calculated threshold */ 
1582        case 2: /* value is above calculated threshold */  1600        case 2: /* value is above calculated threshold */ 
1583            $item['bl_fail_count']++; 1601            $item['bl_fail_count']++;
1584            $breach_up   = ($item['bl_alert'] == STAT_HI); 1602            $breach_up   = ($item['bl_alert'] == STAT_HI);
1585            $breach_down = ($item['bl_alert'] == STAT_LO); 1603            $breach_down = ($item['bl_alert'] == STAT_LO);
1586  1604 
1587            thold_debug('Threshold Baseline check breached'); 1605            thold_debug('Threshold Baseline check breached');
1588  1606 
1589            /* re-alert? */  1607            /* re-alert? */ 
1590            $ra = ($item['bl_fail_count'] > $bl_fail_trigger && ($item['bl_fail_count'] % ($item['repeat_alert'] == '' ? $realert : $item['repeat_alert'])) == 0); 1608            $ra = ($item['bl_fail_count'] > $bl_fail_trigger && ($item['bl_fail_count'] % ($item['repeat_alert'] == '' ? $realert : $item['repeat_alert'])) == 0);
1591  1609 
1592            if ($item['bl_fail_count'] == $bl_fail_trigger || $ra) { 1610            if ($item['bl_fail_count'] == $bl_fail_trigger || $ra) {
1593                thold_debug('Alerting is necessary'); 1611                thold_debug('Alerting is necessary');
1594  1612        if (strstr($name,$process)) { 
1595                $subject = "ALERT: " . $item['name'] . ($thold_show_datasource ? " [$name]" : '') . ' ' . ($ra ? 'is still' : 'went') . ' ' . ($breach_up ? 'above' : 'below') . " calculated baseline threshold " . ($breach_up ? $item['thold_hi'] : $item['thold_low']) . " with $currentval"; 1613                    $subject = "?重警示: " . (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . '?程' . ' ' . ($ra ? '仍然' : '?在') . ($breach_up ? '高于' : '?常消失或不存在') . ",当前??:$currentval" . ',而非正常的' . ($breach_up ? $item['thold_hi'] : $item['thold_low']) . ',?尽快?理!';
1596  1614                    } else { 
  1615                           $subject = "?重警示: " . (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . ($thold_show_datasource ? " [$name]" : '') . ' ' . ($ra ? '仍然' : '?在') . ' ' . ($breach_up ? '高于' : '低于') . " ?算出的基??? " . ($breach_up ? $item['thold_hi'] : $item['thold_low']) . " 当前??: $currentval";
  1616        }
1597                if ($logset == 1) { 1617                if ($logset == 1) {
1598                    logger($item['name'], $breach_up, ($breach_up ? $item['thold_hi'] : $item['thold_low']), $currentval, $item['bl_fail_trigger'], $item['bl_fail_count'], $url); 1618                    logger($item['name'], $breach_up, ($breach_up ? $item['thold_hi'] : $item['thold_low']), $currentval, $item['bl_fail_trigger'], $item['bl_fail_count'], $url);
1599                } 1619                }
1600  1620 
1601                if (trim($alert_emails) != '') { 1621                if (trim($alert_emails) != '') {
1602                    thold_mail($alert_emails, '', $subject, $msg, $file_array); 1622                    thold_mail($alert_emails, '', $subject, $msg, $file_array);
1603                } 1623                }
1604  1624 
1605                thold_log(array( 1625                thold_log(array(
1606                    'type' => 1, 1626                    'type' => 1,
1607                    'time' => time(), 1627                    'time' => time(),
1608                    'host_id' => $item['host_id'], 1628                    'host_id' => $item['host_id'],
1609                    'graph_id' => $graph_id, 1629                    'graph_id' => $graph_id,
1610                    'threshold_id' => $item['id'], 1630                    'threshold_id' => $item['id'],
1611                    'threshold_value' => ($breach_up ? $item['thold_hi'] : $item['thold_low']), 1631                    'threshold_value' => ($breach_up ? $item['thold_hi'] : $item['thold_low']),
1612                    'current' => $currentval, 1632                    'current' => $currentval,
1613                    'status' => ($ra ? ST_NOTIFYRA:ST_NOTIFYAL), 1633                    'status' => ($ra ? ST_NOTIFYRA:ST_NOTIFYAL),
1614                    'description' => $subject, 1634                    'description' => $subject,
1615                    'emails' => $alert_emails)); 1635                    'emails' => $alert_emails));
1616            } else { 1636            } else {
1617                thold_log(array( 1637                thold_log(array(
1618                    'type' => 1, 1638                    'type' => 1,
1619                    'time' => time(), 1639                    'time' => time(),
1620                    'host_id' => $item['host_id'], 1640                    'host_id' => $item['host_id'],
1621                    'graph_id' => $graph_id, 1641                    'graph_id' => $graph_id,
1622                    'threshold_id' => $item['id'], 1642                    'threshold_id' => $item['id'],
1623                    'threshold_value' => ($breach_up ? $item['thold_hi'] : $item['thold_low']), 1643                    'threshold_value' => ($breach_up ? $item['thold_hi'] : $item['thold_low']),
1624                    'current' => $currentval, 1644                    'current' => $currentval,
1625                    'status' => ST_TRIGGERA, 1645                    'status' => ST_TRIGGERA,
1626                    'description' => $subject, 1646                    'description' => $subject,
1627                    'emails' => $alert_emails)); 1647                    'emails' => $alert_emails));
1628            } 1648            }
1629  1649 
1630            break; 1650            break;
1631        } 1651        }
1632  1652 
1633        db_execute("UPDATE thold_data SET thold_alert=0, thold_fail_count=0, 1653        db_execute("UPDATE thold_data SET thold_alert=0, thold_fail_count=0,
1634            bl_alert='" . $item['bl_alert'] . "', 1654            bl_alert='" . $item['bl_alert'] . "',
1635            bl_fail_count='" . $item['bl_fail_count'] . "', 1655            bl_fail_count='" . $item['bl_fail_count'] . "',
1636            thold_low='" . $item['thold_low'] . "', 1656            thold_low='" . $item['thold_low'] . "',
1637            thold_hi='" . $item['thold_hi'] . "', 1657            thold_hi='" . $item['thold_hi'] . "',
1638            bl_thold_valid='" . $item['bl_thold_valid'] . "' 1658            bl_thold_valid='" . $item['bl_thold_valid'] . "'
1639            WHERE rra_id='$rra_id' AND data_id=" . $item['data_id']); 1659            WHERE rra_id='$rra_id' AND data_id=" . $item['data_id']);
1640  1660 
1641        break; 1661        break;
1642    case 2:   /* time based */  1662    case 2:   /* time based */ 
1643        if ($currentval != '') { 1663        if ($currentval != '') {
1644            $breach_up = ($item['time_hi'] != '' && $currentval > $item['time_hi']); 1664            $breach_up = ($item['time_hi'] != '' && $currentval > $item['time_hi']);
1645            $breach_down = ($item['time_low'] != '' && $currentval < $item['time_low']); 1665            $breach_down = ($item['time_low'] != '' && $currentval < $item['time_low']);
1646            $warning_breach_up = ($item['time_warning_hi'] != '' && $currentval > $item['time_warning_hi']); 1666            $warning_breach_up = ($item['time_warning_hi'] != '' && $currentval > $item['time_warning_hi']);
1647            $warning_breach_down = ($item['time_warning_low'] != '' && $currentval < $item['time_warning_low']); 1667            $warning_breach_down = ($item['time_warning_low'] != '' && $currentval < $item['time_warning_low']);
1648        } else { 1668        } else {
1649            $breach_up = $breach_down = $warning_breach_up = $warning_breach_down = false; 1669            $breach_up = $breach_down = $warning_breach_up = $warning_breach_down = false;
1650        } 1670        }
1651  1671 
1652        $step = db_fetch_cell('SELECT rrd_step FROM data_template_data WHERE local_data_id = ' . $rra_id, FALSE); 1672        $step = db_fetch_cell('SELECT rrd_step FROM data_template_data WHERE local_data_id = ' . $rra_id, FALSE);
1653  1673 
1654        /* alerts */  1674        /* alerts */ 
1655        $trigger  = $item['time_fail_trigger']; 1675        $trigger  = $item['time_fail_trigger'];
1656        $time     = time() - ($item['time_fail_length'] * $step); 1676        $time     = time() - ($item['time_fail_length'] * $step);
1657        $failures = db_fetch_cell("SELECT count(id) FROM plugin_thold_log WHERE threshold_id=" . $item['id'] . " AND status IN (" . ST_TRIGGERA . "," . ST_NOTIFYRA . "," . ST_NOTIFYAL . ") AND time>" . $time); 1677        $failures = db_fetch_cell("SELECT count(id) FROM plugin_thold_log WHERE threshold_id=" . $item['id'] . " AND status IN (" . ST_TRIGGERA . "," . ST_NOTIFYRA . "," . ST_NOTIFYAL . ") AND time>" . $time);
1658  1678 
1659        /* warnings */  1679        /* warnings */ 
1660        $warning_trigger  = $item['time_warning_fail_trigger']; 1680        $warning_trigger  = $item['time_warning_fail_trigger'];
1661        $warning_time     = time() - ($item['time_warning_fail_length'] * $step); 1681        $warning_time     = time() - ($item['time_warning_fail_length'] * $step);
1662        $warning_failures = db_fetch_cell("SELECT count(id) FROM plugin_thold_log WHERE threshold_id=" . $item['id'] . " AND status IN (" . ST_NOTIFYWA . "," . ST_TRIGGERW . ") AND time>" . $warning_time) + $failures; 1682        $warning_failures = db_fetch_cell("SELECT count(id) FROM plugin_thold_log WHERE threshold_id=" . $item['id'] . " AND status IN (" . ST_NOTIFYWA . "," . ST_TRIGGERW . ") AND time>" . $warning_time) + $failures;
1663  1683 
1664        if ($breach_up || $breach_down) { 1684        if ($breach_up || $breach_down) {
1665            $notify = false; 1685            $notify = false;
1666  1686 
1667            thold_debug('Threshold Time Based check breached HI:' . $item['time_hi'] . ' LOW:' . $item['time_low'] . ' VALUE:'.$currentval); 1687            thold_debug('Threshold Time Based check breached HI:' . $item['time_hi'] . ' LOW:' . $item['time_low'] . ' VALUE:'.$currentval);
1668  1688 
1669            $item['thold_alert']      = ($breach_up ? STAT_HI:STAT_LO); 1689            $item['thold_alert']      = ($breach_up ? STAT_HI:STAT_LO);
1670            $item['thold_fail_count'] = $failures; 1690            $item['thold_fail_count'] = $failures;
1671  1691 
1672            /* we should only re-alert X minutes after last email, not every 5 pollings, etc... 1692            /* we should only re-alert X minutes after last email, not every 5 pollings, etc...
1673               re-alert? */  1693               re-alert? */ 
1674            $realerttime   = ($item['repeat_alert']-1) * $step; 1694            $realerttime   = ($item['repeat_alert']-1) * $step;
1675            $lastemailtime = db_fetch_cell("SELECT time 1695            $lastemailtime = db_fetch_cell("SELECT time
1676                FROM plugin_thold_log 1696                FROM plugin_thold_log
1677                WHERE threshold_id=" . $item['id'] . " 1697                WHERE threshold_id=" . $item['id'] . "
1678                AND status IN (" . ST_NOTIFYRA . "," . ST_NOTIFYAL . ") 1698                AND status IN (" . ST_NOTIFYRA . "," . ST_NOTIFYAL . ")
1679                ORDER BY time DESC 1699                ORDER BY time DESC
1680                LIMIT 1", FALSE); 1700                LIMIT 1", FALSE);
1681  1701 
1682            $ra = ($failures > $trigger && $item['repeat_alert'] && !empty($lastemailtime) && ($lastemailtime+$realerttime <= time())); 1702            $ra = ($failures > $trigger && $item['repeat_alert'] && !empty($lastemailtime) && ($lastemailtime+$realerttime <= time()));
1683  1703 
1684            $failures++; 1704            $failures++;
1685  1705 
1686            thold_debug("Alert Time:'$time', Alert Trigger:'$trigger', Alert Failures:'$failures', RealertTime:'$realerttime', LastTime:'$lastemailtime', RA:'$ra', Diff:'" . ($realerttime+$lastemailtime) . "'<'". time() . "'"); 1706            thold_debug("Alert Time:'$time', Alert Trigger:'$trigger', Alert Failures:'$failures', RealertTime:'$realerttime', LastTime:'$lastemailtime', RA:'$ra', Diff:'" . ($realerttime+$lastemailtime) . "'<'". time() . "'");
1687  1707 
1688  1708 
1689            if ($failures == $trigger || $ra) { 1709            if ($failures == $trigger || $ra) {
1690                $notify = true; 1710                $notify = true;
1691            } 1711            }
1692  1712      if (strstr($name,$process)) { 
1693            $subject = ($notify ? "ALERT: ":"TRIGGER: ") . $item['name'] . ($thold_show_datasource ? " [$name]" : '') . ' ' . ($failures > $trigger ? 'is still' : 'went') . ' ' . ($breach_up ? 'above' : 'below') . ' threshold of ' . ($breach_up ? $item['time_hi'] : $item['time_low']) . " with $currentval"; 1713                    $subject = ($notify ? "?重警示: ":"触?: ") . (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . '?程' . '?常消失或不存在,?尽快?理!';
1694  1714                    } else { 
  1715                         $subject = ($notify ? "?重警示: ":"触?: ") . (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . ($thold_show_datasource ? " [$name]" : '') . ' ' . ($failures > $trigger ? '仍然' : '?在') . ' ' . ($breach_up ? '高于' : '低于') . ' ????的 ' . ($breach_up ? $item['time_hi'] : $item['time_low']) . " 当前??: $currentval";
  1716      }
1695            if ($notify) { 1717            if ($notify) {
1696                thold_debug('Alerting is necessary'); 1718                thold_debug('Alerting is necessary');
1697  1719 
1698                if ($logset == 1) { 1720                if ($logset == 1) {
1699                    logger($item['name'], $breach_up, ($breach_up ? $item['time_hi'] : $item['time_low']), $currentval, $trigger, $failures, $url); 1721                    logger($item['name'], $breach_up, ($breach_up ? $item['time_hi'] : $item['time_low']), $currentval, $trigger, $failures, $url);
1700                } 1722                }
1701  1723 
1702                if (trim($alert_emails) != '') { 1724                if (trim($alert_emails) != '') {
1703                    thold_mail($alert_emails, '', $subject, $msg, $file_array); 1725                    thold_mail($alert_emails, '', $subject, $msg, $file_array);
1704                } 1726                }
1705  1727 
1706                thold_log(array( 1728                thold_log(array(
1707                    'type' => 2, 1729                    'type' => 2,
1708                    'time' => time(), 1730                    'time' => time(),
1709                    'host_id' => $item['host_id'], 1731                    'host_id' => $item['host_id'],
1710                    'graph_id' => $graph_id, 1732                    'graph_id' => $graph_id,
1711                    'threshold_id' => $item['id'], 1733                    'threshold_id' => $item['id'],
1712                    'threshold_value' => ($breach_up ? $item['time_hi'] : $item['time_low']), 1734                    'threshold_value' => ($breach_up ? $item['time_hi'] : $item['time_low']),
1713                    'current' => $currentval, 1735                    'current' => $currentval,
1714                    'status' => ($failures > $trigger ? ST_NOTIFYAL:ST_NOTIFYRA), 1736                    'status' => ($failures > $trigger ? ST_NOTIFYAL:ST_NOTIFYRA),
1715                    'description' => $subject, 1737                    'description' => $subject,
1716                    'emails' => $alert_emails)); 1738                    'emails' => $alert_emails));
1717            } else { 1739            } else {
1718                thold_log(array( 1740                thold_log(array(
1719                    'type' => 2, 1741                    'type' => 2,
1720                    'time' => time(), 1742                    'time' => time(),
1721                    'host_id' => $item['host_id'], 1743                    'host_id' => $item['host_id'],
1722                    'graph_id' => $graph_id, 1744                    'graph_id' => $graph_id,
1723                    'threshold_id' => $item['id'], 1745                    'threshold_id' => $item['id'],
1724                    'threshold_value' => ($breach_up ? $item['time_hi'] : $item['time_low']), 1746                    'threshold_value' => ($breach_up ? $item['time_hi'] : $item['time_low']),
1725                    'current' => $currentval, 1747                    'current' => $currentval,
1726                    'status' => ST_TRIGGERA, 1748                    'status' => ST_TRIGGERA,
1727                    'description' => $subject, 1749                    'description' => $subject,
1728                    'emails' => $alert_emails)); 1750                    'emails' => $alert_emails));
1729            } 1751            }
1730  1752 
1731            db_execute("UPDATE thold_data 1753            db_execute("UPDATE thold_data
1732                SET thold_alert=" . $item['thold_alert'] . ", 1754                SET thold_alert=" . $item['thold_alert'] . ",
1733                thold_fail_count=$failures 1755                thold_fail_count=$failures
1734                WHERE rra_id=$rra_id AND data_id=" . $item['data_id']); 1756                WHERE rra_id=$rra_id AND data_id=" . $item['data_id']);
1735        } elseif ($warning_breach_up || $warning_breach_down) { 1757        } elseif ($warning_breach_up || $warning_breach_down) {
1736            $notify = false; 1758            $notify = false;
1737  1759 
1738            $item['thold_alert'] = ($warning_breach_up ? STAT_HI:STAT_LO); 1760            $item['thold_alert'] = ($warning_breach_up ? STAT_HI:STAT_LO);
1739            $item['thold_warning_fail_count'] = $warning_failures; 1761            $item['thold_warning_fail_count'] = $warning_failures;
1740  1762 
1741            /* we should only re-alert X minutes after last email, not every 5 pollings, etc... 1763            /* we should only re-alert X minutes after last email, not every 5 pollings, etc...
1742               re-alert? */  1764               re-alert? */ 
1743            $realerttime   = ($item['time_warning_fail_length']-1) * $step; 1765            $realerttime   = ($item['time_warning_fail_length']-1) * $step;
1744            $lastemailtime = db_fetch_cell("SELECT time 1766            $lastemailtime = db_fetch_cell("SELECT time
1745                FROM plugin_thold_log 1767                FROM plugin_thold_log
1746                WHERE threshold_id=" . $item['id'] . " 1768                WHERE threshold_id=" . $item['id'] . "
1747                AND status IN (" . ST_NOTIFYRA . "," . ST_NOTIFYWA . ") 1769                AND status IN (" . ST_NOTIFYRA . "," . ST_NOTIFYWA . ")
1748                ORDER BY time DESC 1770                ORDER BY time DESC
1749                LIMIT 1", FALSE); 1771                LIMIT 1", FALSE);
1750  1772 
1751            $ra = ($warning_failures > $warning_trigger && $item['time_warning_fail_length'] && !empty($lastemailtime) && ($lastemailtime+$realerttime <= time())); 1773            $ra = ($warning_failures > $warning_trigger && $item['time_warning_fail_length'] && !empty($lastemailtime) && ($lastemailtime+$realerttime <= time()));
1752  1774 
1753            $warning_failures++; 1775            $warning_failures++;
1754  1776 
1755            thold_debug("Warn Time:'$warning_time', Warn Trigger:'$warning_trigger', Warn Failures:'$warning_failures', RealertTime:'$realerttime', LastTime:'$lastemailtime', RA:'$ra', Diff:'" . ($realerttime+$lastemailtime) . "'<'". time() . "'"); 1777            thold_debug("Warn Time:'$warning_time', Warn Trigger:'$warning_trigger', Warn Failures:'$warning_failures', RealertTime:'$realerttime', LastTime:'$lastemailtime', RA:'$ra', Diff:'" . ($realerttime+$lastemailtime) . "'<'". time() . "'");
1756  1778 
1757            if ($warning_failures == $warning_trigger || $ra) { 1779            if ($warning_failures == $warning_trigger || $ra) {
1758                $notify = true;; 1780                $notify = true;;
1759            } 1781            }
1760  1782      if (strstr($name,$process)) { 
1761            $subject = ($notify ? "WARNING: ":"TRIGGER: ") . $item['name'] . ($thold_show_datasource ? " [$name]" : '') . ' ' . ($warning_failures > $warning_trigger ? 'is still' : 'went') . ' ' . ($warning_breach_up ? 'above' : 'below') . ' threshold of ' . ($warning_breach_up ? $item['time_warning_hi'] : $item['time_warning_low']) . " with $currentval"; 1783                    $subject = ($notify ? "警告: ":"触?: ") . (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . '?程' . '?常消失或不存在,?尽快?理!';
1762  1784                    } else { 
  1785                         $subject = ($notify ? "警告: ":"触?: ") . (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . ($thold_show_datasource ? " [$name]" : '') . ' ' . ($warning_failures > $warning_trigger ? '仍然' : '?在') . ' ' . ($warning_breach_up ? '高于' : '低于') . ' ????的 ' . ($warning_breach_up ? $item['time_warning_hi'] : $item['time_warning_low']) . " 当前??: $currentval";
  1786      }
1763            if ($notify) { 1787            if ($notify) {
1764                if ($logset == 1) { 1788                if ($logset == 1) {
1765                    logger($item['name'], 'warning', ($warning_breach_up ? $item['time_warning_hi'] : $item['time_warning_low']), $currentval, $warning_trigger, $warning_failures, $url); 1789                    logger($item['name'], 'warning', ($warning_breach_up ? $item['time_warning_hi'] : $item['time_warning_low']), $currentval, $warning_trigger, $warning_failures, $url);
1766                } 1790                }
1767  1791 
1768                if (trim($alert_emails) != '') { 1792                if (trim($alert_emails) != '') {
1769                    thold_mail($warning_emails, '', $subject, $warn_msg, $file_array); 1793                    thold_mail($warning_emails, '', $subject, $warn_msg, $file_array);
1770                } 1794                }
1771  1795 
1772                thold_log(array( 1796                thold_log(array(
1773                    'type' => 2, 1797                    'type' => 2,
1774                    'time' => time(), 1798                    'time' => time(),
1775                    'host_id' => $item['host_id'], 1799                    'host_id' => $item['host_id'],
1776                    'graph_id' => $graph_id, 1800                    'graph_id' => $graph_id,
1777                    'threshold_id' => $item['id'], 1801                    'threshold_id' => $item['id'],
1778                    'threshold_value' => ($breach_up ? $item['time_hi'] : $item['time_low']), 1802                    'threshold_value' => ($breach_up ? $item['time_hi'] : $item['time_low']),
1779                    'current' => $currentval, 1803                    'current' => $currentval,
1780                    'status' => ($warning_failures > $warning_trigger ? ST_NOTIFYRA:ST_NOTIFYWA), 1804                    'status' => ($warning_failures > $warning_trigger ? ST_NOTIFYRA:ST_NOTIFYWA),
1781                    'description' => $subject, 1805                    'description' => $subject,
1782                    'emails' => $alert_emails)); 1806                    'emails' => $alert_emails));
1783            } elseif ($alertstat != 0 && $warning_failures < $warning_trigger && $failures < $trigger) { 1807            } elseif ($alertstat != 0 && $warning_failures < $warning_trigger && $failures < $trigger) {
1784                $subject = "ALERT -> WARNING: ". $item['name'] . ($thold_show_datasource ? " [$name]" : '') . " restored to warning threshold with value $currentval";  1808                if (strstr($name,$process)) { 
1785  1809                    $subject = "?警事件状?改?,从:?重警示 -> 警告: ". (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . '?程' . '?常消失或不存在,?尽快?理!'; 
  1810                    } else {
  1811                           $subject = "?警事件状?改?,从:?重警示 -> 警告: ". (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . ($thold_show_datasource ? " [$name]" : '') . " 恢??警告状?,??: $currentval";
  1812        }
1786                thold_log(array( 1813                thold_log(array(
1787                    'type' => 2, 1814                    'type' => 2,
1788                    'time' => time(), 1815                    'time' => time(),
1789                    'host_id' => $item['host_id'], 1816                    'host_id' => $item['host_id'],
1790                    'graph_id' => $graph_id, 1817                    'graph_id' => $graph_id,
1791                    'threshold_id' => $item['id'], 1818                    'threshold_id' => $item['id'],
1792                    'threshold_value' => ($warning_breach_up ? $item['time_hi'] : $item['time_low']), 1819                    'threshold_value' => ($warning_breach_up ? $item['time_hi'] : $item['time_low']),
1793                    'current' => $currentval, 1820                    'current' => $currentval,
1794                    'status' => ST_NOTIFYAW, 1821                    'status' => ST_NOTIFYAW,
1795                    'description' => $subject, 1822                    'description' => $subject,
1796                    'emails' => $alert_emails)); 1823                    'emails' => $alert_emails));
1797            }else{ 1824            }else{
1798                thold_log(array( 1825                thold_log(array(
1799                    'type' => 2, 1826                    'type' => 2,
1800                    'time' => time(), 1827                    'time' => time(),
1801                    'host_id' => $item['host_id'], 1828                    'host_id' => $item['host_id'],
1802                    'graph_id' => $graph_id, 1829                    'graph_id' => $graph_id,
1803                    'threshold_id' => $item['id'], 1830                    'threshold_id' => $item['id'],
1804                    'threshold_value' => ($warning_breach_up ? $item['time_hi'] : $item['time_low']), 1831                    'threshold_value' => ($warning_breach_up ? $item['time_hi'] : $item['time_low']),
1805                    'current' => $currentval, 1832                    'current' => $currentval,
1806                    'status' => ST_TRIGGERW, 1833                    'status' => ST_TRIGGERW,
1807                    'description' => $subject, 1834                    'description' => $subject,
1808                    'emails' => $warning_emails)); 1835                    'emails' => $warning_emails));
1809            } 1836            }
1810  1837 
1811            db_execute("UPDATE thold_data 1838            db_execute("UPDATE thold_data
1812                SET thold_alert=" . $item['thold_alert'] . ", 1839                SET thold_alert=" . $item['thold_alert'] . ",
1813                thold_warning_fail_count=$warning_failures, 1840                thold_warning_fail_count=$warning_failures,
1814                thold_fail_count=$failures 1841                thold_fail_count=$failures
1815                WHERE rra_id=$rra_id AND data_id=" . $item['data_id']); 1842                WHERE rra_id=$rra_id AND data_id=" . $item['data_id']);
1816        } else { 1843        } else {
1817            thold_debug('Threshold Time Based check is normal HI:' . $item['time_hi'] . ' LOW:' . $item['time_low'] . ' VALUE:'.$currentval); 1844            thold_debug('Threshold Time Based check is normal HI:' . $item['time_hi'] . ' LOW:' . $item['time_low'] . ' VALUE:'.$currentval);
1818  1845 
1819            if ($alertstat != 0 && $warning_failures < $warning_trigger && $item['restored_alert'] != 'on') { 1846            if ($alertstat != 0 && $warning_failures < $warning_trigger && $item['restored_alert'] != 'on') {
1820                if ($logset == 1) { 1847                if ($logset == 1) {
1821                    logger($item['name'], 'ok', 0, $currentval, $warning_trigger, $item['thold_warning_fail_count'], $url); 1848                    logger($item['name'], 'ok', 0, $currentval, $warning_trigger, $item['thold_warning_fail_count'], $url);
1822                } 1849                }
1823  1850        if (strstr($name,$process)) { 
1824                $subject = "NORMAL: ". $item['name'] . ($thold_show_datasource ? " [$name]" : '') . " restored to normal threshold with value $currentval"; 1851                    $subject = "恢?正常: ". (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . '?程' . " 恢??恢?正常状?,??:$currentval";
1825  1852                    } else { 
  1853                           $subject = "恢?正常: ". (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . ($thold_show_datasource ? " [$name]" : '') . " 恢??恢?正常状?,??:$currentval";
  1854        }
1826                if (trim($warning_emails) != '' && $item['restored_alert'] != 'on') { 1855                if (trim($warning_emails) != '' && $item['restored_alert'] != 'on') {
1827                    thold_mail($warning_emails, '', $subject, $msg, $file_array); 1856                    thold_mail($warning_emails, '', $subject, $msg, $file_array);
1828                } 1857                }
1829  1858 
1830                thold_log(array( 1859                thold_log(array(
1831                    'type' => 2, 1860                    'type' => 2,
1832                    'time' => time(), 1861                    'time' => time(),
1833                    'host_id' => $item['host_id'], 1862                    'host_id' => $item['host_id'],
1834                    'graph_id' => $graph_id, 1863                    'graph_id' => $graph_id,
1835                    'threshold_id' => $item['id'], 1864                    'threshold_id' => $item['id'],
1836                    'threshold_value' => '', 1865                    'threshold_value' => '',
1837                    'current' => $currentval, 1866                    'current' => $currentval,
1838                    'status' => ST_NOTIFYRS, 1867                    'status' => ST_NOTIFYRS,
1839                    'description' => $subject, 1868                    'description' => $subject,
1840                    'emails' => $warning_emails)); 1869                    'emails' => $warning_emails));
1841  1870 
1842                db_execute("UPDATE thold_data 1871                db_execute("UPDATE thold_data
1843                    SET thold_alert=0, thold_warning_fail_count=$warning_failures, thold_fail_count=$failures 1872                    SET thold_alert=0, thold_warning_fail_count=$warning_failures, thold_fail_count=$failures
1844                    WHERE rra_id=$rra_id AND data_id=" . $item['data_id']); 1873                    WHERE rra_id=$rra_id AND data_id=" . $item['data_id']);
1845            } elseif ($alertstat != 0 && $failures < $trigger && $item['restored_alert'] != 'on') { 1874            } elseif ($alertstat != 0 && $failures < $trigger && $item['restored_alert'] != 'on') {
1846                if ($logset == 1) { 1875                if ($logset == 1) {
1847                    logger($item['name'], 'warning', 0, $currentval, $trigger, $item['thold_fail_count'], $url); 1876                    logger($item['name'], 'warning', 0, $currentval, $trigger, $item['thold_fail_count'], $url);
1848                } 1877                }
1849  1878        if (strstr($name,$process)) { 
1850                $subject = "NORMAL: ". $item['name'] . ($thold_show_datasource ? " [$name]" : '') . " restored to warning threshold with value $currentval"; 1879                    $subject = "恢?正常: ". (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . '?程' . " 恢??恢?正常状?,??:$currentval";
1851  1880                    } else { 
  1881                           $subject = "恢?正常: ". (iconv("UTF-8", "GB2312//IGNORE", $item['name'])) . ($thold_show_datasource ? " [$name]" : '') . " 恢??恢?正常状?,??:$currentval";
  1882            }
1852                if (trim($alert_emails) != '' && $item['restored_alert'] != 'on') { 1883                if (trim($alert_emails) != '' && $item['restored_alert'] != 'on') {
1853                    thold_mail($alert_emails, '', $subject, $msg, $file_array); 1884                    thold_mail($alert_emails, '', $subject, $msg, $file_array);
1854                } 1885                }
1855  1886 
1856                thold_log(array( 1887                thold_log(array(
1857                    'type' => 2, 1888                    'type' => 2,
1858                    'time' => time(), 1889                    'time' => time(),
1859                    'host_id' => $item['host_id'], 1890                    'host_id' => $item['host_id'],
1860                    'graph_id' => $graph_id, 1891                    'graph_id' => $graph_id,
1861                    'threshold_id' => $item['id'], 1892                    'threshold_id' => $item['id'],
1862                    'threshold_value' => '', 1893                    'threshold_value' => '',
1863                    'current' => $currentval, 1894                    'current' => $currentval,
1864                    'status' => ST_NOTIFYRS, 1895                    'status' => ST_NOTIFYRS,
1865                    'description' => $subject, 1896                    'description' => $subject,
1866                    'emails' => $alert_emails)); 1897                    'emails' => $alert_emails));
1867  1898 
1868                db_execute("UPDATE thold_data 1899                db_execute("UPDATE thold_data
1869                    SET thold_alert=0, thold_warning_fail_count=$warning_failures, thold_fail_count=$failures 1900                    SET thold_alert=0, thold_warning_fail_count=$warning_failures, thold_fail_count=$failures
1870                    WHERE rra_id=$rra_id AND data_id=" . $item['data_id']); 1901                    WHERE rra_id=$rra_id AND data_id=" . $item['data_id']);
1871            } else { 1902            } else {
1872                db_execute("UPDATE thold_data 1903                db_execute("UPDATE thold_data
1873                    SET thold_fail_count=$failures, 1904                    SET thold_fail_count=$failures,
1874                    thold_warning_fail_count=$warning_failures 1905                    thold_warning_fail_count=$warning_failures
1875                    WHERE rra_id=$rra_id AND data_id=" . $item['data_id']); 1906                    WHERE rra_id=$rra_id AND data_id=" . $item['data_id']);
1876            } 1907            }
1877        } 1908        }
1878  1909 
1879        break; 1910        break;
1880    } 1911    }
1881} 1912}
1882  1913 
1883function thold_format_number($value, $digits=5) { 1914function thold_format_number($value, $digits=5) {
1884    if ($value == '') { 1915    if ($value == '') {
1885        return '-'; 1916        return '-';
1886    }elseif (strlen(round($value,0)) == strlen($value)) { 1917    }elseif (strlen(round($value,0)) == strlen($value)) {
1887        return $value; 1918        return $value;
1888    } else { 1919    } else {
1889        return rtrim(number_format($value, $digits), "0"); 1920        return rtrim(number_format($value, $digits), "0");
1890    } 1921    }
1891} 1922}
1892  1923 
1893function thold_format_name($template, $local_graph_id, $local_data_id, $data_source_name) { 1924function thold_format_name($template, $local_graph_id, $local_data_id, $data_source_name) {
1894    $desc = db_fetch_cell('SELECT name_cache 1925    $desc = db_fetch_cell('SELECT name_cache
1895        FROM data_template_data 1926        FROM data_template_data
1896        WHERE local_data_id=' . $local_data_id . '  1927        WHERE local_data_id=' . $local_data_id . ' 
1897        LIMIT 1'); 1928        LIMIT 1');
1898  1929 
1899    if (substr_count($template["name"], '|')) { 1930    if (substr_count($template["name"], '|')) {
1900        $gl = db_fetch_row("SELECT * FROM graph_local WHERE id=$local_graph_id"); 1931        $gl = db_fetch_row("SELECT * FROM graph_local WHERE id=$local_graph_id");
1901  1932 
1902        if (sizeof($gl)) { 1933        if (sizeof($gl)) {
1903            $name = expand_title($gl["host_id"], $gl["snmp_query_id"], $gl["snmp_index"], $template["name"]); 1934            $name = expand_title($gl["host_id"], $gl["snmp_query_id"], $gl["snmp_index"], $template["name"]);
1904        } else { 1935        } else {
1905            $name = $desc . ' [' . $data_source_name . ']'; 1936            $name = $desc . ' [' . $data_source_name . ']';
1906        } 1937        }
1907    } else { 1938    } else {
1908        $name = $desc . ' [' . $data_source_name . ']'; 1939        $name = $desc . ' [' . $data_source_name . ']';
1909    } 1940    }
1910  1941 
1911    return $name; 1942    return $name;
1912} 1943}
1913  1944 
1914function get_reference_types($rra = 0, $step = 300) { 1945function get_reference_types($rra = 0, $step = 300) {
1915    if ($step == 60) { 1946    if ($step == 60) {
1916        $timearray = array( 1947        $timearray = array(
1917            1 => '1 Minute', 1948            1 => '1 Minute',
1918            2 => '2 Minutes', 1949            2 => '2 Minutes',
1919            3 => '3 Minutes', 1950            3 => '3 Minutes',
1920            4 => '4 Minutes', 1951            4 => '4 Minutes',
1921            5 => '5 Minutes', 1952            5 => '5 Minutes',
1922            6 => '6 Minutes', 1953            6 => '6 Minutes',
1923            7 => '7 Minutes', 1954            7 => '7 Minutes',
1924            8 => '8 Minutes', 1955            8 => '8 Minutes',
1925            9 => '9 Minutes', 1956            9 => '9 Minutes',
1926            10 => '10 Minutes', 1957            10 => '10 Minutes',
1927            12 => '12 Minutes', 1958            12 => '12 Minutes',
1928            15 => '15 Minutes', 1959            15 => '15 Minutes',
1929            20 => '20 Minutes', 1960            20 => '20 Minutes',
1930            24 => '24 Minutes', 1961            24 => '24 Minutes',
1931            30 => '30 Minutes', 1962            30 => '30 Minutes',
1932            45 => '45 Minutes', 1963            45 => '45 Minutes',
1933            60 => '1 Hour', 1964            60 => '1 Hour',
1934            120 => '2 Hours', 1965            120 => '2 Hours',
1935            180 => '3 Hours', 1966            180 => '3 Hours',
1936            240 => '4 Hours', 1967            240 => '4 Hours',
1937            288 => '4.8 Hours', 1968            288 => '4.8 Hours',
1938            360 => '6 Hours', 1969            360 => '6 Hours',
1939            480 => '8 Hours', 1970            480 => '8 Hours',
1940            720 => '12 Hours', 1971            720 => '12 Hours',
1941            1440 => '1 Day', 1972            1440 => '1 Day',
1942            2880 => '2 Days', 1973            2880 => '2 Days',
1943            10080 => '1 Week', 1974            10080 => '1 Week',
1944            20160 => '2 Weeks', 1975            20160 => '2 Weeks',
1945            43200 => '1 Month'  1976            43200 => '1 Month' 
1946        ); 1977        );
1947    } else if ($step == 300) { 1978    } else if ($step == 300) {
1948        $timearray = array( 1979        $timearray = array(
1949            1 => '5 Minutes', 1980            1 => '5 Minutes',
1950            2 => '10 Minutes', 1981            2 => '10 Minutes',
1951            3 => '15 Minutes', 1982            3 => '15 Minutes',
1952            4 => '20 Minutes', 1983            4 => '20 Minutes',
1953            6 => '30 Minutes', 1984            6 => '30 Minutes',
1954            8 => '45 Minutes', 1985            8 => '45 Minutes',
1955            12 => 'Hour', 1986            12 => 'Hour',
1956            24 => '2 Hours', 1987            24 => '2 Hours',
1957            36 => '3 Hours', 1988            36 => '3 Hours',
1958            48 => '4 Hours', 1989            48 => '4 Hours',
1959            72 => '6 Hours', 1990            72 => '6 Hours',
1960            96 => '8 Hours', 1991            96 => '8 Hours',
1961            144 => '12 Hours', 1992            144 => '12 Hours',
1962            288 => '1 Day', 1993            288 => '1 Day',
1963            576 => '2 Days', 1994            576 => '2 Days',
1964            2016 => '1 Week', 1995            2016 => '1 Week',
1965            4032 => '2 Weeks', 1996            4032 => '2 Weeks',
1966            8640 => '1 Month'  1997            8640 => '1 Month' 
1967        ); 1998        );
1968    } else { 1999    } else {
1969        $timearray = array( 2000        $timearray = array(
1970            1 => '1 Polling', 2001            1 => '1 Polling',
1971            2 => '2 Pollings', 2002            2 => '2 Pollings',
1972            3 => '3 Pollings', 2003            3 => '3 Pollings',
1973            4 => '4 Pollings', 2004            4 => '4 Pollings',
1974            5 => '5 Pollings', 2005            5 => '5 Pollings',
1975            6 => '6 Pollings', 2006            6 => '6 Pollings',
1976            8 => '8 Pollings', 2007            8 => '8 Pollings',
1977            12 => '12 Pollings', 2008            12 => '12 Pollings',
1978            24 => '24 Pollings', 2009            24 => '24 Pollings',
1979            36 => '36 Pollings', 2010            36 => '36 Pollings',
1980            48 => '48 Pollings', 2011            48 => '48 Pollings',
1981            72 => '72 Pollings', 2012            72 => '72 Pollings',
1982            96 => '96 Pollings', 2013            96 => '96 Pollings',
1983            144 => '144 Pollings', 2014            144 => '144 Pollings',
1984            288 => '288 Pollings', 2015            288 => '288 Pollings',
1985            576 => '576 Pollings', 2016            576 => '576 Pollings',
1986            2016 => '2016 Pollings'  2017            2016 => '2016 Pollings' 
1987        ); 2018        );
1988    } 2019    }
1989  2020 
1990    $rra_steps = db_fetch_assoc("SELECT DISTINCT rra.steps 2021    $rra_steps = db_fetch_assoc("SELECT DISTINCT rra.steps
1991        FROM data_template_data d 2022        FROM data_template_data d
1992        JOIN data_template_data_rra a 2023        JOIN data_template_data_rra a
1993        ON d.id=a.data_template_data_id 2024        ON d.id=a.data_template_data_id
1994        JOIN rra 2025        JOIN rra
1995        ON a.rra_id=rra.id 2026        ON a.rra_id=rra.id
1996        WHERE rra.steps>1 " . 2027        WHERE rra.steps>1 " .
1997        ($rra > 0 ? "AND d.local_data_id=$rra":"") . " 2028        ($rra > 0 ? "AND d.local_data_id=$rra":"") . "
1998        ORDER BY steps"); 2029        ORDER BY steps");
1999  2030 
2000    $reference_types = array(); 2031    $reference_types = array();
2001    if (sizeof($rra_steps)) { 2032    if (sizeof($rra_steps)) {
2002    foreach($rra_steps as $rra_step) { 2033    foreach($rra_steps as $rra_step) {
2003        $seconds = $step * $rra_step['steps']; 2034        $seconds = $step * $rra_step['steps'];
2004        if (isset($timearray[$rra_step['steps']])) { 2035        if (isset($timearray[$rra_step['steps']])) {
2005            $reference_types[$seconds] = $timearray[$rra_step['steps']] . " Average" ; 2036            $reference_types[$seconds] = $timearray[$rra_step['steps']] . " Average" ;
2006        } 2037        }
2007    } 2038    }
2008    } 2039    }
2009  2040 
2010    return $reference_types; 2041    return $reference_types;
2011} 2042}
2012  2043 
2013function thold_request_check_changed($request, $session) { 2044function thold_request_check_changed($request, $session) {
2014    if ((isset($_REQUEST[$request])) && (isset($_SESSION[$session]))) { 2045    if ((isset($_REQUEST[$request])) && (isset($_SESSION[$session]))) {
2015        if ($_REQUEST[$request] != $_SESSION[$session]) { 2046        if ($_REQUEST[$request] != $_SESSION[$session]) {
2016            return 1; 2047            return 1;
2017        } 2048        }
2018    } 2049    }
2019} 2050}
2020  2051 
2021function logger($desc, $breach_up, $threshld, $currentval, $trigger, $triggerct, $urlbreach) { 2052function logger($desc, $breach_up, $threshld, $currentval, $trigger, $triggerct, $urlbreach) {
2022    define_syslog_variables(); 2053    define_syslog_variables();
2023  2054 
2024    $syslog_level = read_config_option('thold_syslog_level'); 2055    $syslog_level = read_config_option('thold_syslog_level');
2025    $syslog_facility = read_config_option('thold_syslog_facility'); 2056    $syslog_facility = read_config_option('thold_syslog_facility');
2026    if (!isset($syslog_level)) { 2057    if (!isset($syslog_level)) {
2027        $syslog_level = LOG_WARNING; 2058        $syslog_level = LOG_WARNING;
2028    } else if (isset($syslog_level) && ($syslog_level > 7 || $syslog_level < 0)) { 2059    } else if (isset($syslog_level) && ($syslog_level > 7 || $syslog_level < 0)) {
2029        $syslog_level = LOG_WARNING; 2060        $syslog_level = LOG_WARNING;
2030    } 2061    }
2031    if (!isset($syslog_facility)) { 2062    if (!isset($syslog_facility)) {
2032        $syslog_facility = LOG_DAEMON; 2063        $syslog_facility = LOG_DAEMON;
2033    } 2064    }
2034  2065 
2035    openlog('CactiTholdLog', LOG_PID | LOG_PERROR, $syslog_facility); 2066    openlog('CactiTholdLog', LOG_PID | LOG_PERROR, $syslog_facility);
2036  2067 
2037    if (strval($breach_up) == 'ok') { 2068    if (strval($breach_up) == 'ok') {
2038        syslog($syslog_level, $desc . ' restored to normal with ' . $currentval . ' at trigger ' . $trigger . ' out of ' . $triggerct . " - ". $urlbreach); 2069        syslog($syslog_level, $desc . ' 恢?正常至 ' . $currentval . ' 从触?? ' . $trigger . ' 恢? ' . $triggerct . " - ". $urlbreach);
2039    } else { 2070    } else {
2040        syslog($syslog_level, $desc . ' went ' . ($breach_up ? 'above' : 'below') . ' threshold of ' . $threshld . ' with ' . $currentval . ' at trigger ' . $trigger . ' out of ' . $triggerct . " - ". $urlbreach); 2071        syslog($syslog_level, $desc . ' ?于 ' . ($breach_up ? '高于' : '低于') . ' ????的 ' . $threshld . ' with ' . $currentval . ' 从触?? ' . $trigger . ' 恢? ' . $triggerct . " - ". $urlbreach);
2041    } 2072    }
2042} 2073}
2043  2074 
2044function thold_cdef_get_usable () { 2075function thold_cdef_get_usable () {
2045    $cdef_items = db_fetch_assoc("select * from cdef_items where value = 'CURRENT_DATA_SOURCE' order by cdef_id"); 2076    $cdef_items = db_fetch_assoc("select * from cdef_items where value = 'CURRENT_DATA_SOURCE' order by cdef_id");
2046    $cdef_usable = array(); 2077    $cdef_usable = array();
2047    if (sizeof($cdef_items)) { 2078    if (sizeof($cdef_items)) {
2048        foreach ($cdef_items as $cdef_item) { 2079        foreach ($cdef_items as $cdef_item) {
2049                $cdef_usable[] =  $cdef_item['cdef_id']; 2080                $cdef_usable[] =  $cdef_item['cdef_id'];
2050        } 2081        }
2051    } 2082    }
2052  2083 
2053    return $cdef_usable; 2084    return $cdef_usable;
2054} 2085}
2055  2086 
2056function thold_cdef_select_usable_names () { 2087function thold_cdef_select_usable_names () {
2057    $ids = thold_cdef_get_usable(); 2088    $ids = thold_cdef_get_usable();
2058    $cdefs = db_fetch_assoc('select id, name from cdef'); 2089    $cdefs = db_fetch_assoc('select id, name from cdef');
2059    $cdef_names[0] = ''; 2090    $cdef_names[0] = '';
2060    if (sizeof($cdefs)) { 2091    if (sizeof($cdefs)) {
2061        foreach ($cdefs as $cdef) { 2092        foreach ($cdefs as $cdef) {
2062            if (in_array($cdef['id'], $ids)) { 2093            if (in_array($cdef['id'], $ids)) {
2063                $cdef_names[$cdef['id']] =  $cdef['name']; 2094                $cdef_names[$cdef['id']] =  $cdef['name'];
2064            } 2095            }
2065        } 2096        }
2066    } 2097    }
2067    return $cdef_names; 2098    return $cdef_names;
2068} 2099}
2069  2100 
2070function thold_build_cdef ($id, $value, $rra, $ds) { 2101function thold_build_cdef ($id, $value, $rra, $ds) {
2071    $oldvalue = $value; 2102    $oldvalue = $value;
2072  2103 
2073    $cdefs = db_fetch_assoc("select * from cdef_items where cdef_id = $id order by sequence"); 2104    $cdefs = db_fetch_assoc("select * from cdef_items where cdef_id = $id order by sequence");
2074    if (sizeof($cdefs)) { 2105    if (sizeof($cdefs)) {
2075    foreach ($cdefs as $cdef) { 2106    foreach ($cdefs as $cdef) {
2076        if ($cdef['type'] == 4) { 2107        if ($cdef['type'] == 4) {
2077            $cdef['type'] = 6; 2108            $cdef['type'] = 6;
2078  2109 
2079            switch ($cdef['value']) { 2110            switch ($cdef['value']) {
2080            case 'CURRENT_DATA_SOURCE': 2111            case 'CURRENT_DATA_SOURCE':
2081                $cdef['value'] = $oldvalue; // get_current_value($rra, $ds, 0); 2112                $cdef['value'] = $oldvalue; // get_current_value($rra, $ds, 0);
2082                break; 2113                break;
2083            case 'CURRENT_GRAPH_MAXIMUM_VALUE': 2114            case 'CURRENT_GRAPH_MAXIMUM_VALUE':
2084                $cdef['value'] = get_current_value($rra, 'upper_limit', 0); 2115                $cdef['value'] = get_current_value($rra, 'upper_limit', 0);
2085                break; 2116                break;
2086            case 'CURRENT_GRAPH_MINIMUM_VALUE': 2117            case 'CURRENT_GRAPH_MINIMUM_VALUE':
2087                $cdef['value'] = get_current_value($rra, 'lower_limit', 0); 2118                $cdef['value'] = get_current_value($rra, 'lower_limit', 0);
2088                break; 2119                break;
2089            case 'CURRENT_DS_MINIMUM_VALUE': 2120            case 'CURRENT_DS_MINIMUM_VALUE':
2090                $cdef['value'] = get_current_value($rra, 'rrd_minimum', 0); 2121                $cdef['value'] = get_current_value($rra, 'rrd_minimum', 0);
2091                break; 2122                break;
2092            case 'CURRENT_DS_MAXIMUM_VALUE': 2123            case 'CURRENT_DS_MAXIMUM_VALUE':
2093                $cdef['value'] = get_current_value($rra, 'rrd_maximum', 0); 2124                $cdef['value'] = get_current_value($rra, 'rrd_maximum', 0);
2094                break; 2125                break;
2095            case 'VALUE_OF_HDD_TOTAL': 2126            case 'VALUE_OF_HDD_TOTAL':
2096                $cdef['value'] = get_current_value($rra, 'hdd_total', 0); 2127                $cdef['value'] = get_current_value($rra, 'hdd_total', 0);
2097                break; 2128                break;
2098            case 'ALL_DATA_SOURCES_NODUPS': // you can't have DUPs in a single data source, really... 2129            case 'ALL_DATA_SOURCES_NODUPS': // you can't have DUPs in a single data source, really...
2099            case 'ALL_DATA_SOURCES_DUPS': 2130            case 'ALL_DATA_SOURCES_DUPS':
2100                $cdef['value'] = 0; 2131                $cdef['value'] = 0;
2101                $all_dsns = array(); 2132                $all_dsns = array();
2102                $all_dsns = db_fetch_assoc("SELECT data_source_name FROM data_template_rrd WHERE local_data_id = $rra"); 2133                $all_dsns = db_fetch_assoc("SELECT data_source_name FROM data_template_rrd WHERE local_data_id = $rra");
2103                if (is_array($all_dsns)) { 2134                if (is_array($all_dsns)) {
2104                    foreach ($all_dsns as $dsn) { 2135                    foreach ($all_dsns as $dsn) {
2105                        $cdef['value'] += get_current_value($rra, $dsn['data_source_name'], 0); 2136                        $cdef['value'] += get_current_value($rra, $dsn['data_source_name'], 0);
2106                    } 2137                    }
2107                } 2138                }
2108                break; 2139                break;
2109            default: 2140            default:
2110                print 'CDEF property not implemented yet: ' . $cdef['value']; 2141                print 'CDEF property not implemented yet: ' . $cdef['value'];
2111                return $oldvalue; 2142                return $oldvalue;
2112                break; 2143                break;
2113            } 2144            }
2114        } elseif ($cdef['type'] == 6) { 2145        } elseif ($cdef['type'] == 6) {
2115            $regresult = preg_match('/^\|query_(.*)\|$/', $cdef['value'], $matches); 2146            $regresult = preg_match('/^\|query_(.*)\|$/', $cdef['value'], $matches);
2116  2147 
2117            if ($regresult > 0) { 2148            if ($regresult > 0) {
2118                // Grab result for query 2149                // Grab result for query
2119                $cdef['value'] = db_fetch_cell("SELECT `h`.`field_value` 2150                $cdef['value'] = db_fetch_cell("SELECT `h`.`field_value`
2120                    FROM `poller_item` p, `host_snmp_cache` h 2151                    FROM `poller_item` p, `host_snmp_cache` h
2121                    WHERE `p`.`local_data_id` = '" . $rra . "' 2152                    WHERE `p`.`local_data_id` = '" . $rra . "'
2122                    AND `p`.`host_id` = `h`.`host_id` 2153                    AND `p`.`host_id` = `h`.`host_id`
2123                    AND `h`.`field_name` = '" . $matches[1] . "' 2154                    AND `h`.`field_name` = '" . $matches[1] . "'
2124                    AND `p`.`rrd_name` = 'traffic_in' 2155                    AND `p`.`rrd_name` = 'traffic_in'
2125                    AND SUBSTRING_INDEX(`p`.`arg1`, '.', -1 ) = `h`.`snmp_index`", FALSE); 2156                    AND SUBSTRING_INDEX(`p`.`arg1`, '.', -1 ) = `h`.`snmp_index`", FALSE);
2126            } 2157            }
2127        } 2158        }
2128        $cdef_array[] = $cdef; 2159        $cdef_array[] = $cdef;
2129    } 2160    }
2130    } 2161    }
2131  2162 
2132    $x = count($cdef_array); 2163    $x = count($cdef_array);
2133  2164 
2134    if ($x == 0) return $oldvalue; 2165    if ($x == 0) return $oldvalue;
2135  2166 
2136    $stack = array(); // operation stack for RPN 2167    $stack = array(); // operation stack for RPN
2137    array_push($stack, $cdef_array[0]); // first one always goes on 2168    array_push($stack, $cdef_array[0]); // first one always goes on
2138    $cursor = 1; // current pointer through RPN operations list 2169    $cursor = 1; // current pointer through RPN operations list
2139  2170 
2140    while($cursor < $x) { 2171    while($cursor < $x) {
2141        $type = $cdef_array[$cursor]['type']; 2172        $type = $cdef_array[$cursor]['type'];
2142        switch($type) { 2173        switch($type) {
2143        case 6: 2174        case 6:
2144            array_push($stack, $cdef_array[$cursor]); 2175            array_push($stack, $cdef_array[$cursor]);
2145  2176 
2146            break; 2177            break;
2147        case 2: 2178        case 2:
2148            // this is a binary operation. pop two values, and then use them. 2179            // this is a binary operation. pop two values, and then use them.
2149            $v1 = thold_expression_rpn_pop($stack); 2180            $v1 = thold_expression_rpn_pop($stack);
2150            $v2 = thold_expression_rpn_pop($stack); 2181            $v2 = thold_expression_rpn_pop($stack);
2151            $result = thold_rpn($v2['value'], $v1['value'], $cdef_array[$cursor]['value']); 2182            $result = thold_rpn($v2['value'], $v1['value'], $cdef_array[$cursor]['value']);
2152            // put the result back on the stack. 2183            // put the result back on the stack.
2153            array_push($stack, array('type'=>6,'value'=>$result)); 2184            array_push($stack, array('type'=>6,'value'=>$result));
2154  2185 
2155            break; 2186            break;
2156        default: 2187        default:
2157            print 'Unknown RPN type: '; 2188            print 'Unknown RPN type: ';
2158            print $cdef_array[$cursor]['type']; 2189            print $cdef_array[$cursor]['type'];
2159            return($oldvalue); 2190            return($oldvalue);
2160  2191 
2161            break; 2192            break;
2162        } 2193        }
2163  2194 
2164        $cursor++; 2195        $cursor++;
2165    } 2196    }
2166  2197 
2167    return $stack[0]['value']; 2198    return $stack[0]['value'];
2168} 2199}
2169  2200 
2170function thold_rpn ($x, $y, $z) { 2201function thold_rpn ($x, $y, $z) {
2171    switch ($z) { 2202    switch ($z) {
2172    case 1: 2203    case 1:
2173        return $x + $y; 2204        return $x + $y;
2174  2205 
2175        break; 2206        break;
2176    case 2: 2207    case 2:
2177        return $x - $y; 2208        return $x - $y;
2178  2209 
2179        break; 2210        break;
2180    case 3: 2211    case 3:
2181        return $x * $y; 2212        return $x * $y;
2182  2213 
2183        break; 2214        break;
2184    case 4: 2215    case 4:
2185        if ($y == 0) { 2216        if ($y == 0) {
2186            return (-1); 2217            return (-1);
2187        } 2218        }
2188        return $x / $y; 2219        return $x / $y;
2189  2220 
2190        break; 2221        break;
2191    case 5: 2222    case 5:
2192        return $x % $y; 2223        return $x % $y;
2193  2224 
2194        break; 2225        break;
2195    } 2226    }
2196  2227 
2197    return ''; 2228    return '';
2198} 2229}
2199  2230 
2200function delete_old_thresholds () { 2231function delete_old_thresholds () {
2201    $result = db_fetch_assoc('SELECT id, data_id, rra_id FROM thold_data'); 2232    $result = db_fetch_assoc('SELECT id, data_id, rra_id FROM thold_data');
2202    if (sizeof($result)) { 2233    if (sizeof($result)) {
2203    foreach ($result as $row) { 2234    foreach ($result as $row) {
2204        $ds_item_desc = db_fetch_assoc('select id, data_source_name from data_template_rrd where id = ' . $row['data_id']); 2235        $ds_item_desc = db_fetch_assoc('select id, data_source_name from data_template_rrd where id = ' . $row['data_id']);
2205        if (!isset($ds_item_desc[0]['data_source_name'])) { 2236        if (!isset($ds_item_desc[0]['data_source_name'])) {
2206            db_execute('DELETE FROM thold_data WHERE id=' . $row['id']); 2237            db_execute('DELETE FROM thold_data WHERE id=' . $row['id']);
2207            db_execute('DELETE FROM plugin_thold_threshold_contact WHERE thold_id=' . $row['id']); 2238            db_execute('DELETE FROM plugin_thold_threshold_contact WHERE thold_id=' . $row['id']);
2208        } 2239        }
2209    } 2240    }
2210    } 2241    }
2211} 2242}
2212  2243 
2213function thold_rrd_last($rra) { 2244function thold_rrd_last($rra) {
2214    global $config; 2245    global $config;
2215  2246 
2216    $last_time_entry = @rrdtool_execute('last ' . trim(get_data_source_path($rra, true)), false, RRDTOOL_OUTPUT_STDOUT); 2247    $last_time_entry = @rrdtool_execute('last ' . trim(get_data_source_path($rra, true)), false, RRDTOOL_OUTPUT_STDOUT);
2217  2248 
2218    return trim($last_time_entry); 2249    return trim($last_time_entry);
2219} 2250}
2220  2251 
2221function get_current_value($rra, $ds, $cdef = 0) { 2252function get_current_value($rra, $ds, $cdef = 0) {
2222    global $config; 2253    global $config;
2223  2254 
2224    /* get the information to populate into the rrd files */  2255    /* get the information to populate into the rrd files */ 
2225    if (function_exists("boost_check_correct_enabled") && boost_check_correct_enabled()) { 2256    if (function_exists("boost_check_correct_enabled") && boost_check_correct_enabled()) {
2226        boost_process_poller_output(TRUE, $rra); 2257        boost_process_poller_output(TRUE, $rra);
2227    } 2258    }
2228  2259 
2229    $last_time_entry = thold_rrd_last($rra); 2260    $last_time_entry = thold_rrd_last($rra);
2230  2261 
2231    // This should fix and 'did you really mean month 899 errors', this is because your RRD has not polled yet 2262    // This should fix and 'did you really mean month 899 errors', this is because your RRD has not polled yet
2232    if ($last_time_entry == -1) { 2263    if ($last_time_entry == -1) {
2233        $last_time_entry = time(); 2264        $last_time_entry = time();
2234    } 2265    }
2235  2266 
2236    $data_template_data = db_fetch_row("SELECT * FROM data_template_data WHERE local_data_id=$rra"); 2267    $data_template_data = db_fetch_row("SELECT * FROM data_template_data WHERE local_data_id=$rra");
2237  2268 
2238    $step = $data_template_data['rrd_step']; 2269    $step = $data_template_data['rrd_step'];
2239  2270 
2240    // Round down to the nearest 100 2271    // Round down to the nearest 100
2241    $last_time_entry = (intval($last_time_entry /100) * 100) - $step; 2272    $last_time_entry = (intval($last_time_entry /100) * 100) - $step;
2242    $last_needed = $last_time_entry + $step; 2273    $last_needed = $last_time_entry + $step;
2243  2274 
2244    $result = rrdtool_function_fetch($rra, trim($last_time_entry), trim($last_needed)); 2275    $result = rrdtool_function_fetch($rra, trim($last_time_entry), trim($last_needed));
2245  2276 
2246    // Return Blank if the data source is not found (Newly created?) 2277    // Return Blank if the data source is not found (Newly created?)
2247    if (!isset( $result['data_source_names'])) return ''; 2278    if (!isset( $result['data_source_names'])) return '';
2248  2279 
2249    $idx = array_search($ds, $result['data_source_names']); 2280    $idx = array_search($ds, $result['data_source_names']);
2250  2281 
2251    // Return Blank if the value was not found (Cache Cleared?) 2282    // Return Blank if the value was not found (Cache Cleared?)
2252    if (!isset($result['values'][$idx][0])) { 2283    if (!isset($result['values'][$idx][0])) {
2253        return ''; 2284        return '';
2254    } 2285    }
2255  2286 
2256    $value = $result['values'][$idx][0]; 2287    $value = $result['values'][$idx][0];
2257    if ($cdef != 0) { 2288    if ($cdef != 0) {
2258        $value = thold_build_cdef($cdef, $value, $rra, $ds); 2289        $value = thold_build_cdef($cdef, $value, $rra, $ds);
2259    } 2290    }
2260  2291 
2261    return round($value, 4); 2292    return round($value, 4);
2262} 2293}
2263  2294 
2264function thold_get_ref_value($rra_id, $ds, $ref_time, $time_range) { 2295function thold_get_ref_value($rra_id, $ds, $ref_time, $time_range) {
2265    global $config; 2296    global $config;
2266  2297 
2267    $result = rrdtool_function_fetch($rra_id, $ref_time-$time_range, $ref_time-1, $time_range); 2298    $result = rrdtool_function_fetch($rra_id, $ref_time-$time_range, $ref_time-1, $time_range);
2268  2299 
2269    $idx = array_search($ds, $result['data_source_names']); 2300    $idx = array_search($ds, $result['data_source_names']);
2270    if (count($result['values'][$idx]) == 0) { 2301    if (count($result['values'][$idx]) == 0) {
2271        return false; 2302        return false;
2272    } 2303    }
2273  2304 
2274    return $result['values'][$idx]; 2305    return $result['values'][$idx];
2275} 2306}
2276  2307 
2277/* thold_check_exception_periods 2308/* thold_check_exception_periods
2278 @to-do: This function should check 'globally' declared exceptions, like 2309 @to-do: This function should check 'globally' declared exceptions, like
2279 holidays etc., as well as exceptions bound to the speciffic $rra_id. $rra_id 2310 holidays etc., as well as exceptions bound to the speciffic $rra_id. $rra_id
2280 should inherit exceptions that are assigned on the higher level (i.e. device). 2311 should inherit exceptions that are assigned on the higher level (i.e. device).
2281  2312 
2282*/  2313*/ 
2283function thold_check_exception_periods($rra_id, $ref_time, $ref_range) { 2314function thold_check_exception_periods($rra_id, $ref_time, $ref_range) {
2284    // TO-DO 2315    // TO-DO
2285    // Check if the reference time falls into global exceptions 2316    // Check if the reference time falls into global exceptions
2286    // Check if the current time falls into global exceptions 2317    // Check if the current time falls into global exceptions
2287    // Check if $rra_id + $ds have an exception (again both reference time and current time) 2318    // Check if $rra_id + $ds have an exception (again both reference time and current time)
2288    // Check if there are inheritances 2319    // Check if there are inheritances
2289  2320 
2290    // More on the exception concept: 2321    // More on the exception concept:
2291    // -Exceptions can be one time and recurring 2322    // -Exceptions can be one time and recurring
2292    // -Exceptions can be global and assigned to: 2323    // -Exceptions can be global and assigned to:
2293    //  -templates 2324    //  -templates
2294    //  -devices 2325    //  -devices
2295    //  -data sources 2326    //  -data sources
2296    // 2327    //
2297  2328 
2298    return false; 2329    return false;
2299} 2330}
2300  2331 
2301/* thold_check_baseline - 2332/* thold_check_baseline -
2302 Should be called after hard limits have been checked and only when they are OK 2333 Should be called after hard limits have been checked and only when they are OK
2303  2334 
2304 The function "goes back in time" $ref_time seconds and retrieves the data 2335 The function "goes back in time" $ref_time seconds and retrieves the data
2305 for $ref_range seconds. Then it finds minimum and maximum values and calculates 2336 for $ref_range seconds. Then it finds minimum and maximum values and calculates
2306 allowed deviations from those values. 2337 allowed deviations from those values.
2307  2338 
2308 @arg $rra_id - the data source to check the data 2339 @arg $rra_id - the data source to check the data
2309 @arg $ds - Index of the data_source in the RRD 2340 @arg $ds - Index of the data_source in the RRD
2310 @arg $ref_time - Integer value representing reference offset in seconds 2341 @arg $ref_time - Integer value representing reference offset in seconds
2311 @arg $ref_range - Integer value indicating reference time range in seconds 2342 @arg $ref_range - Integer value indicating reference time range in seconds
2312 @arg $current_value - Current "value" of the data source 2343 @arg $current_value - Current "value" of the data source
2313 @arg $pct_down - Allowed baseline deviation in % - if set to false will not be considered 2344 @arg $pct_down - Allowed baseline deviation in % - if set to false will not be considered
2314 @arg $pct_up - Allowed baseline deviation in % - if set to false will not be considered 2345 @arg $pct_up - Allowed baseline deviation in % - if set to false will not be considered
2315  2346 
2316 @returns (integer) - integer value that indicates status 2347 @returns (integer) - integer value that indicates status
2317   -2 if the exception is active 2348   -2 if the exception is active
2318   -1 if the reference value is not available 2349   -1 if the reference value is not available
2319   0 if the current value is within the boundaries 2350   0 if the current value is within the boundaries
2320   1 if the current value is below the calculated threshold 2351   1 if the current value is below the calculated threshold
2321   2 if the current value is above the calculated threshold 2352   2 if the current value is above the calculated threshold
2322 */  2353 */ 
2323function thold_check_baseline($rra_id, $ds, $current_value, &$item) { 2354function thold_check_baseline($rra_id, $ds, $current_value, &$item) {
2324    global $debug; 2355    global $debug;
2325  2356 
2326    $now = time(); 2357    $now = time();
2327  2358 
2328    // See if we have a valid cached thold_high and thold_low value 2359    // See if we have a valid cached thold_high and thold_low value
2329    if ($item['bl_thold_valid'] && $now < $item['bl_thold_valid']) { 2360    if ($item['bl_thold_valid'] && $now < $item['bl_thold_valid']) {
2330        if ($item['thold_hi'] && $current_value > $item['thold_hi']) { 2361        if ($item['thold_hi'] && $current_value > $item['thold_hi']) {
2331            $failed = 2; 2362            $failed = 2;
2332        } elseif ($item['thold_low'] && $current_value < $item['thold_low']) { 2363        } elseif ($item['thold_low'] && $current_value < $item['thold_low']) {
2333            $failed = 1; 2364            $failed = 1;
2334        } else { 2365        } else {
2335            $failed= 0; 2366            $failed= 0;
2336        } 2367        }
2337    } else { 2368    } else {
2338        $midnight =  gmmktime(0,0,0); 2369        $midnight =  gmmktime(0,0,0);
2339        $t0 = $midnight + floor(($now - $midnight) / $item['bl_ref_time_range']) * $item['bl_ref_time_range']; 2370        $t0 = $midnight + floor(($now - $midnight) / $item['bl_ref_time_range']) * $item['bl_ref_time_range'];
2340  2371 
2341        $ref_values = thold_get_ref_value($rra_id, $ds, $t0, $item['bl_ref_time_range']); 2372        $ref_values = thold_get_ref_value($rra_id, $ds, $t0, $item['bl_ref_time_range']);
2342  2373 
2343        if (!is_array($ref_values) || sizeof($ref_values) == 0) { 2374        if (!is_array($ref_values) || sizeof($ref_values) == 0) {
2344            $item['thold_low'] = ''; 2375            $item['thold_low'] = '';
2345            $item['thold_hi'] = ''; 2376            $item['thold_hi'] = '';
2346            $item['bl_thold_valid'] = $now; 2377            $item['bl_thold_valid'] = $now;
2347            $returnvalue=-1; 2378            $returnvalue=-1;
2348            return $returnvalue; // Baseline reference value not yet established 2379            return $returnvalue; // Baseline reference value not yet established
2349        } 2380        }
2350  2381 
2351        $ref_value = $ref_values[0]; 2382        $ref_value = $ref_values[0];
2352        if ($item['cdef'] != 0) { 2383        if ($item['cdef'] != 0) {
2353            $ref_value = thold_build_cdef($item['cdef'], $ref_value, $item['rra_id'], $item['data_id']); 2384            $ref_value = thold_build_cdef($item['cdef'], $ref_value, $item['rra_id'], $item['data_id']);
2354        } 2385        }
2355  2386 
2356        $blt_low  = ''; 2387        $blt_low  = '';
2357        $blt_high = ''; 2388        $blt_high = '';
2358  2389 
2359        if ($item['bl_pct_down'] != '') { 2390        if ($item['bl_pct_down'] != '') {
2360            $blt_low  = round($ref_value - abs($ref_value * $item['bl_pct_down'] / 100),2); 2391            $blt_low  = round($ref_value - abs($ref_value * $item['bl_pct_down'] / 100),2);
2361        } 2392        }
2362  2393 
2363        if ($item['bl_pct_up'] != '') { 2394        if ($item['bl_pct_up'] != '') {
2364            $blt_high = round($ref_value + abs($ref_value * $item['bl_pct_up'] / 100),2); 2395            $blt_high = round($ref_value + abs($ref_value * $item['bl_pct_up'] / 100),2);
2365        } 2396        }
2366  2397 
2367        // Cache the calculated or empty values 2398        // Cache the calculated or empty values
2368        $item['thold_low'] = $blt_low; 2399        $item['thold_low'] = $blt_low;
2369        $item['thold_hi']  = $blt_high; 2400        $item['thold_hi']  = $blt_high;
2370        $item['bl_thold_valid'] = $t0 + $item['bl_ref_time_range']; 2401        $item['bl_thold_valid'] = $t0 + $item['bl_ref_time_range'];
2371  2402 
2372        $failed = 0; 2403        $failed = 0;
2373  2404 
2374        // Check low boundary 2405        // Check low boundary
2375        if ($blt_low != '' && $current_value < $blt_low) { 2406        if ($blt_low != '' && $current_value < $blt_low) {
2376            $failed = 1; 2407            $failed = 1;
2377        } 2408        }
2378  2409 
2379        // Check up boundary 2410        // Check up boundary
2380        if ($failed == 0 && $blt_high != '' && $current_value > $blt_high) { 2411        if ($failed == 0 && $blt_high != '' && $current_value > $blt_high) {
2381            $failed = 2; 2412            $failed = 2;
2382        } 2413        }
2383    } 2414    }
2384  2415 
2385    if ($debug) { 2416    if ($debug) {
2386        echo "RRA: $rra_id : $ds\n"; 2417        echo "RRA: $rra_id : $ds\n";
2387        echo 'Ref. values count: ' . (isset($ref_values) ? count($ref_values):"N/A") . "\n"; 2418        echo 'Ref. values count: ' . (isset($ref_values) ? count($ref_values):"N/A") . "\n";
2388        echo "Ref. value (min): " . (isset($ref_value_min) ? $ref_value_min:"N/A") . "\n"; 2419        echo "Ref. value (min): " . (isset($ref_value_min) ? $ref_value_min:"N/A") . "\n";
2389        echo "Ref. value (max): " . (isset($ref_value_max) ? $ref_value_max:"N/A") . "\n"; 2420        echo "Ref. value (max): " . (isset($ref_value_max) ? $ref_value_max:"N/A") . "\n";
2390        echo "Cur. value: $current_value\n"; 2421        echo "Cur. value: $current_value\n";
2391        echo "Low bl thresh: " . (isset($blt_low) ? $blt_low:"N/A") . "\n"; 2422        echo "Low bl thresh: " . (isset($blt_low) ? $blt_low:"N/A") . "\n";
2392        echo "High bl thresh: " . (isset($blt_high) ? $blt_high:"N/A") . "\n"; 2423        echo "High bl thresh: " . (isset($blt_high) ? $blt_high:"N/A") . "\n";
2393        echo 'Check against baseline: '; 2424        echo 'Check against baseline: ';
2394        switch($failed) { 2425        switch($failed) {
2395            case 0: 2426            case 0:
2396            echo 'OK'; 2427            echo 'OK';
2397            break; 2428            break;
2398  2429 
2399            case 1: 2430            case 1:
2400            echo 'FAIL: Below baseline threshold!'; 2431            echo 'FAIL: Below baseline threshold!';
2401            break; 2432            break;
2402  2433 
2403            case 2: 2434            case 2:
2404            echo 'FAIL: Above baseline threshold!'; 2435            echo 'FAIL: Above baseline threshold!';
2405            break; 2436            break;
2406        } 2437        }
2407        echo "\n"; 2438        echo "\n";
2408        echo "------------------\n"; 2439        echo "------------------\n";
2409    } 2440    }
2410  2441 
2411    return $failed; 2442    return $failed;
2412} 2443}
2413  2444 
2414function save_thold() { 2445function save_thold() {
2415    global $rra, $banner, $hostid; 2446    global $rra, $banner, $hostid;
2416  2447 
2417    $template_enabled = isset($_POST['template_enabled']) && $_POST['template_enabled'] == 'on' ? $_POST['template_enabled'] : 'off'; 2448    $template_enabled = isset($_POST['template_enabled']) && $_POST['template_enabled'] == 'on' ? $_POST['template_enabled'] : 'off';
2418    if ($template_enabled == 'on') { 2449    if ($template_enabled == 'on') {
2419        input_validate_input_number($_POST['rra']); 2450        input_validate_input_number($_POST['rra']);
2420        input_validate_input_number($_POST['data_template_rrd_id']); 2451        input_validate_input_number($_POST['data_template_rrd_id']);
2421  2452 
2422        $rra_id = $_POST['rra']; 2453        $rra_id = $_POST['rra'];
2423        if (!thold_user_auth_threshold ($rra_id)) { 2454        if (!thold_user_auth_threshold ($rra_id)) {
2424            $banner = '<font color=red><strong>Permission Denied</strong></font>'; 2455            $banner = '<font color=red><strong>Permission Denied</strong></font>';
2425            return; 2456            return;
2426        } 2457        }
2427        $data_id = $_POST['data_template_rrd_id']; 2458        $data_id = $_POST['data_template_rrd_id'];
2428        $data = db_fetch_row("SELECT id, template FROM thold_data WHERE rra_id = $rra_id AND data_id = $data_id"); 2459        $data = db_fetch_row("SELECT id, template FROM thold_data WHERE rra_id = $rra_id AND data_id = $data_id");
2429        thold_template_update_threshold ($data['id'], $data['template']); 2460        thold_template_update_threshold ($data['id'], $data['template']);
2430        $banner = '<font color=green><strong>Record Updated</strong></font>'; 2461        $banner = '<font color=green><strong>Record Updated</strong></font>';
2431        plugin_thold_log_changes($data['id'], 'modified', array('id' => $data['id'], 'template_enabled' => 'on')); 2462        plugin_thold_log_changes($data['id'], 'modified', array('id' => $data['id'], 'template_enabled' => 'on'));
2432        return true; 2463        return true;
2433    } 2464    }
2434  2465 
2435    /* Make sure this is defined */  2466    /* Make sure this is defined */ 
2436    $_POST['thold_enabled'] = isset($_POST['thold_enabled']) ? 'on' : 'off'; 2467    $_POST['thold_enabled'] = isset($_POST['thold_enabled']) ? 'on' : 'off';
  2468    $_POST['mobile'] = isset($_POST['mobile']) ? 'on' : 'off';
2437    $_POST['template_enabled'] = isset($_POST['template_enabled']) ? 'on' : 'off'; 2469    $_POST['template_enabled'] = isset($_POST['template_enabled']) ? 'on' : 'off';
2438  2470 
2439    /* Do Some error Checks */  2471    /* Do Some error Checks */ 
2440    $banner = '<font color=red><strong>'; 2472    $banner = '<font color=red><strong>';
2441    if (($_POST['thold_type'] == 0 && (!isset($_POST['thold_hi']) || trim($_POST['thold_hi']) == '')) && 2473    if (($_POST['thold_type'] == 0 && (!isset($_POST['thold_hi']) || trim($_POST['thold_hi']) == '')) &&
2442        ($_POST['thold_type'] == 0 && (!isset($_POST['thold_low']) || trim($_POST['thold_low']) == ''))) { 2474        ($_POST['thold_type'] == 0 && (!isset($_POST['thold_low']) || trim($_POST['thold_low']) == ''))) {
2443        $banner .= 'You must specify either &quot;High Threshold&quot; or &quot;Low Threshold&quot; or both!<br>RECORD NOT UPDATED!</strong></font>'; 2475        $banner .= 'You must specify either &quot;High Threshold&quot; or &quot;Low Threshold&quot; or both!<br>RECORD NOT UPDATED!</strong></font>';
2444        return; 2476        return;
2445    } 2477    }
2446  2478 
2447    //if (($_POST['thold_type'] == 0) && (isset($_POST['thold_hi'])) && 2479    //if (($_POST['thold_type'] == 0) && (isset($_POST['thold_hi'])) &&
2448    //  (isset($_POST['thold_low'])) && (trim($_POST['thold_hi']) != '') && 2480    //  (isset($_POST['thold_low'])) && (trim($_POST['thold_hi']) != '') &&
2449    //  (trim($_POST['thold_low']) != '') && (round($_POST['thold_low'],4) >= round($_POST['thold_hi'],4))) { 2481    //  (trim($_POST['thold_low']) != '') && (round($_POST['thold_low'],4) >= round($_POST['thold_hi'],4))) {
2450    //  $banner .= 'Impossible thresholds: &quot;High Threshold&quot; smaller than or equal to &quot;Low Threshold&quot;<br>RECORD NOT UPDATED!</strong></font>'; 2482    //  $banner .= 'Impossible thresholds: &quot;High Threshold&quot; smaller than or equal to &quot;Low Threshold&quot;<br>RECORD NOT UPDATED!</strong></font>';
2451    //  return; 2483    //  return;
2452    //} 2484    //}
2453  2485 
2454    if ($_POST['thold_type'] == 1) { 2486    if ($_POST['thold_type'] == 1) {
2455        $banner .= 'With baseline thresholds enabled '; 2487        $banner .= 'With baseline thresholds enabled ';
2456        if (!thold_mandatory_field_ok('bl_ref_time_range', 'Time reference in the past')) { 2488        if (!thold_mandatory_field_ok('bl_ref_time_range', 'Time reference in the past')) {
2457            return; 2489            return;
2458        } 2490        }
2459        if ((!isset($_POST['bl_pct_down']) || trim($_POST['bl_pct_down']) == '') && (!isset($_POST['bl_pct_up']) || trim($_POST['bl_pct_up']) == '')) { 2491        if ((!isset($_POST['bl_pct_down']) || trim($_POST['bl_pct_down']) == '') && (!isset($_POST['bl_pct_up']) || trim($_POST['bl_pct_up']) == '')) {
2460            $banner .= 'You must specify either &quot;Baseline Deviation UP&quot; or &quot;Baseline Deviation DOWN&quot; or both!<br>RECORD NOT UPDATED!</strong></font>'; 2492            $banner .= 'You must specify either &quot;Baseline Deviation UP&quot; or &quot;Baseline Deviation DOWN&quot; or both!<br>RECORD NOT UPDATED!</strong></font>';
2461            return; 2493            return;
2462        } 2494        }
2463    } 2495    }
2464  2496 
2465    $existing = db_fetch_assoc('SELECT id FROM thold_data WHERE rra_id = ' . $rra . ' AND data_id = ' . $_POST['data_template_rrd_id']); 2497    $existing = db_fetch_assoc('SELECT id FROM thold_data WHERE rra_id = ' . $rra . ' AND data_id = ' . $_POST['data_template_rrd_id']);
2466    $save = array(); 2498    $save = array();
2467    if (count($existing)) { 2499    if (count($existing)) {
2468        $save['id'] = $existing[0]['id']; 2500        $save['id'] = $existing[0]['id'];
2469    } else { 2501    } else {
2470        $save['id'] = 0; 2502        $save['id'] = 0;
2471        $save['template'] = ''; 2503        $save['template'] = '';
2472    } 2504    }
2473  2505 
2474    input_validate_input_number(get_request_var_post('thold_hi')); 2506    input_validate_input_number(get_request_var_post('thold_hi'));
2475    input_validate_input_number(get_request_var_post('thold_low')); 2507    input_validate_input_number(get_request_var_post('thold_low'));
2476    input_validate_input_number(get_request_var_post('thold_fail_trigger')); 2508    input_validate_input_number(get_request_var_post('thold_fail_trigger'));
2477    input_validate_input_number(get_request_var_post('thold_warning_hi')); 2509    input_validate_input_number(get_request_var_post('thold_warning_hi'));
2478    input_validate_input_number(get_request_var_post('thold_warning_low')); 2510    input_validate_input_number(get_request_var_post('thold_warning_low'));
2479    input_validate_input_number(get_request_var_post('thold_warning_fail_trigger')); 2511    input_validate_input_number(get_request_var_post('thold_warning_fail_trigger'));
2480    input_validate_input_number(get_request_var_post('repeat_alert')); 2512    input_validate_input_number(get_request_var_post('repeat_alert'));
2481    input_validate_input_number(get_request_var_post('cdef')); 2513    input_validate_input_number(get_request_var_post('cdef'));
2482    input_validate_input_number($_POST['rra']); 2514    input_validate_input_number($_POST['rra']);
2483    input_validate_input_number($_POST['data_template_rrd_id']); 2515    input_validate_input_number($_POST['data_template_rrd_id']);
2484    input_validate_input_number(get_request_var_post('thold_type')); 2516    input_validate_input_number(get_request_var_post('thold_type'));
2485    input_validate_input_number(get_request_var_post('time_hi')); 2517    input_validate_input_number(get_request_var_post('time_hi'));
2486    input_validate_input_number(get_request_var_post('time_low')); 2518    input_validate_input_number(get_request_var_post('time_low'));
2487    input_validate_input_number(get_request_var_post('time_fail_trigger')); 2519    input_validate_input_number(get_request_var_post('time_fail_trigger'));
2488    input_validate_input_number(get_request_var_post('time_fail_length')); 2520    input_validate_input_number(get_request_var_post('time_fail_length'));
2489    input_validate_input_number(get_request_var_post('time_warning_hi')); 2521    input_validate_input_number(get_request_var_post('time_warning_hi'));
2490    input_validate_input_number(get_request_var_post('time_warning_low')); 2522    input_validate_input_number(get_request_var_post('time_warning_low'));
2491    input_validate_input_number(get_request_var_post('time_warning_fail_trigger')); 2523    input_validate_input_number(get_request_var_post('time_warning_fail_trigger'));
2492    input_validate_input_number(get_request_var_post('time_warning_fail_length')); 2524    input_validate_input_number(get_request_var_post('time_warning_fail_length'));
2493    input_validate_input_number(get_request_var_post('data_type')); 2525    input_validate_input_number(get_request_var_post('data_type'));
2494    input_validate_input_number(get_request_var_post('notify_warning')); 2526    input_validate_input_number(get_request_var_post('notify_warning'));
2495    input_validate_input_number(get_request_var_post('notify_alert')); 2527    input_validate_input_number(get_request_var_post('notify_alert'));
2496    input_validate_input_number(get_request_var_post('bl_ref_time_range')); 2528    input_validate_input_number(get_request_var_post('bl_ref_time_range'));
2497    input_validate_input_number(get_request_var_post('bl_pct_down')); 2529    input_validate_input_number(get_request_var_post('bl_pct_down'));
2498    input_validate_input_number(get_request_var_post('bl_pct_up')); 2530    input_validate_input_number(get_request_var_post('bl_pct_up'));
2499    input_validate_input_number(get_request_var_post('bl_fail_trigger')); 2531    input_validate_input_number(get_request_var_post('bl_fail_trigger'));
  2532    input_validate_input_number(get_request_var_post('smstime_exempt_enable'));
  2533    //input_validate_input_number(get_request_var_post('smstime_exempt_start'));
  2534    //input_validate_input_number(get_request_var_post('smstime_exempt_stop'));
2500  2535 
2501    $_POST['name']          = str_replace(array("\\", '"', "'"), '', $_POST['name']); 2536    $_POST['name']          = str_replace(array("\\", '"', "'"), '', $_POST['name']);
2502    $save['name']           = (trim($_POST['name'])) == '' ? '' : $_POST['name']; 2537    $save['name']           = (trim($_POST['name'])) == '' ? '' : $_POST['name'];
2503    $save['host_id']        = $hostid; 2538    $save['host_id']        = $hostid;
2504    $save['data_id']        = $_POST['data_template_rrd_id']; 2539    $save['data_id']        = $_POST['data_template_rrd_id'];
2505    $save['rra_id']         = $_POST['rra']; 2540    $save['rra_id']         = $_POST['rra'];
2506    $save['thold_enabled']  = isset($_POST['thold_enabled']) ? $_POST['thold_enabled'] : ''; 2541    $save['thold_enabled']  = isset($_POST['thold_enabled']) ? $_POST['thold_enabled'] : '';
  2542    $save['mobile']         = isset($_POST['mobile']) ? $_POST['mobile'] : '';
2507    $save['exempt']         = isset($_POST['exempt']) ? $_POST['exempt'] : 'off'; 2543    $save['exempt']         = isset($_POST['exempt']) ? $_POST['exempt'] : 'off';
2508    $save['restored_alert'] = isset($_POST['restored_alert']) ? $_POST['restored_alert'] : 'off'; 2544    $save['restored_alert'] = isset($_POST['restored_alert']) ? $_POST['restored_alert'] : 'off';
2509    $save['thold_type']     = $_POST['thold_type']; 2545    $save['thold_type']     = $_POST['thold_type'];
2510    // High / Low 2546    // High / Low
2511    $save['thold_hi']           = (trim($_POST['thold_hi'])) == '' ? '' : round($_POST['thold_hi'],4); 2547    $save['thold_hi']           = (trim($_POST['thold_hi'])) == '' ? '' : round($_POST['thold_hi'],4);
2512    $save['thold_low']          = (trim($_POST['thold_low'])) == '' ? '' : round($_POST['thold_low'],4); 2548    $save['thold_low']          = (trim($_POST['thold_low'])) == '' ? '' : round($_POST['thold_low'],4);
2513    $save['thold_fail_trigger'] = (trim($_POST['thold_fail_trigger'])) == '' ? read_config_option('alert_trigger') : $_POST['thold_fail_trigger']; 2549    $save['thold_fail_trigger'] = (trim($_POST['thold_fail_trigger'])) == '' ? read_config_option('alert_trigger') : $_POST['thold_fail_trigger'];
2514    // Time Based 2550    // Time Based
2515    $save['time_hi']           = (trim($_POST['time_hi'])) == '' ? '' : round($_POST['time_hi'],4); 2551    $save['time_hi']           = (trim($_POST['time_hi'])) == '' ? '' : round($_POST['time_hi'],4);
2516    $save['time_low']          = (trim($_POST['time_low'])) == '' ? '' : round($_POST['time_low'],4); 2552    $save['time_low']          = (trim($_POST['time_low'])) == '' ? '' : round($_POST['time_low'],4);
2517    $save['time_fail_trigger'] = (trim($_POST['time_fail_trigger'])) == '' ? read_config_option('thold_warning_time_fail_trigger') : $_POST['time_fail_trigger']; 2553    $save['time_fail_trigger'] = (trim($_POST['time_fail_trigger'])) == '' ? read_config_option('thold_warning_time_fail_trigger') : $_POST['time_fail_trigger'];
2518    $save['time_fail_length']  = (trim($_POST['time_fail_length'])) == '' ? (read_config_option('thold_warning_time_fail_length') > 0 ? read_config_option('thold_warning_time_fail_length') : 1) : $_POST['time_fail_length']; 2554    $save['time_fail_length']  = (trim($_POST['time_fail_length'])) == '' ? (read_config_option('thold_warning_time_fail_length') > 0 ? read_config_option('thold_warning_time_fail_length') : 1) : $_POST['time_fail_length'];
2519    // Warning High / Low 2555    // Warning High / Low
2520    $save['thold_warning_hi']  = (trim($_POST['thold_warning_hi'])) == '' ? '' : round($_POST['thold_warning_hi'],4); 2556    $save['thold_warning_hi']  = (trim($_POST['thold_warning_hi'])) == '' ? '' : round($_POST['thold_warning_hi'],4);
2521    $save['thold_warning_low'] = (trim($_POST['thold_warning_low'])) == '' ? '' : round($_POST['thold_warning_low'],4); 2557    $save['thold_warning_low'] = (trim($_POST['thold_warning_low'])) == '' ? '' : round($_POST['thold_warning_low'],4);
2522    $save['thold_warning_fail_trigger'] = (trim($_POST['thold_warning_fail_trigger'])) == '' ? read_config_option('alert_trigger') : $_POST['thold_warning_fail_trigger']; 2558    $save['thold_warning_fail_trigger'] = (trim($_POST['thold_warning_fail_trigger'])) == '' ? read_config_option('alert_trigger') : $_POST['thold_warning_fail_trigger'];
2523    // Warning Time Based 2559    // Warning Time Based
2524    $save['time_warning_hi']  = (trim($_POST['time_warning_hi'])) == '' ? '' : round($_POST['time_warning_hi'],4); 2560    $save['time_warning_hi']  = (trim($_POST['time_warning_hi'])) == '' ? '' : round($_POST['time_warning_hi'],4);
2525    $save['time_warning_low'] = (trim($_POST['time_warning_low'])) == '' ? '' : round($_POST['time_warning_low'],4); 2561    $save['time_warning_low'] = (trim($_POST['time_warning_low'])) == '' ? '' : round($_POST['time_warning_low'],4);
2526    $save['time_warning_fail_trigger'] = (trim($_POST['time_warning_fail_trigger'])) == '' ? read_config_option('thold_warning_time_fail_trigger') : $_POST['time_warning_fail_trigger']; 2562    $save['time_warning_fail_trigger'] = (trim($_POST['time_warning_fail_trigger'])) == '' ? read_config_option('thold_warning_time_fail_trigger') : $_POST['time_warning_fail_trigger'];
2527    $save['time_warning_fail_length']  = (trim($_POST['time_warning_fail_length'])) == '' ? (read_config_option('thold_warning_time_fail_length') > 0 ? read_config_option('thold_warning_time_fail_length') : 1) : $_POST['time_warning_fail_length']; 2563    $save['time_warning_fail_length']  = (trim($_POST['time_warning_fail_length'])) == '' ? (read_config_option('thold_warning_time_fail_length') > 0 ? read_config_option('thold_warning_time_fail_length') : 1) : $_POST['time_warning_fail_length'];
2528    // Baseline 2564    // Baseline
2529    $save['bl_thold_valid'] = '0'; 2565    $save['bl_thold_valid'] = '0';
2530    $save['bl_ref_time_range'] = (trim($_POST['bl_ref_time_range'])) == '' ? read_config_option('alert_bl_timerange_def') : $_POST['bl_ref_time_range']; 2566    $save['bl_ref_time_range'] = (trim($_POST['bl_ref_time_range'])) == '' ? read_config_option('alert_bl_timerange_def') : $_POST['bl_ref_time_range'];
2531    $save['bl_pct_down'] = (trim($_POST['bl_pct_down'])) == '' ? '' : $_POST['bl_pct_down']; 2567    $save['bl_pct_down'] = (trim($_POST['bl_pct_down'])) == '' ? '' : $_POST['bl_pct_down'];
2532    $save['bl_pct_up'] = (trim($_POST['bl_pct_up'])) == '' ? '' : $_POST['bl_pct_up']; 2568    $save['bl_pct_up'] = (trim($_POST['bl_pct_up'])) == '' ? '' : $_POST['bl_pct_up'];
2533    $save['bl_fail_trigger'] = (trim($_POST['bl_fail_trigger'])) == '' ? read_config_option("alert_bl_trigger") : $_POST['bl_fail_trigger']; 2569    $save['bl_fail_trigger'] = (trim($_POST['bl_fail_trigger'])) == '' ? read_config_option("alert_bl_trigger") : $_POST['bl_fail_trigger'];
2534  2570 
2535    $save['repeat_alert'] = (trim($_POST['repeat_alert'])) == '' ? '' : $_POST['repeat_alert']; 2571    $save['repeat_alert'] = (trim($_POST['repeat_alert'])) == '' ? '' : $_POST['repeat_alert'];
2536    $save['notify_extra'] = (trim($_POST['notify_extra'])) == '' ? '' : $_POST['notify_extra']; 2572    $save['notify_extra'] = (trim($_POST['notify_extra'])) == '' ? '' : $_POST['notify_extra'];
2537    $save['notify_warning_extra'] = (trim($_POST['notify_warning_extra'])) == '' ? '' : $_POST['notify_warning_extra']; 2573    $save['notify_warning_extra'] = (trim($_POST['notify_warning_extra'])) == '' ? '' : $_POST['notify_warning_extra'];
2538    $save['notify_warning'] = $_POST['notify_warning']; 2574    $save['notify_warning'] = $_POST['notify_warning'];
2539    $save['notify_alert']   = $_POST['notify_alert']; 2575    $save['notify_alert']   = $_POST['notify_alert'];
2540    $save['cdef']           = (trim($_POST['cdef'])) == '' ? '' : $_POST['cdef']; 2576    $save['cdef']           = (trim($_POST['cdef'])) == '' ? '' : $_POST['cdef'];
2541    $save['template_enabled'] = $_POST['template_enabled']; 2577    $save['template_enabled'] = $_POST['template_enabled'];
2542  2578 
2543    $save['data_type'] = $_POST['data_type']; 2579    $save['data_type'] = $_POST['data_type'];
2544    if (isset($_POST['percent_ds'])) { 2580    if (isset($_POST['percent_ds'])) {
2545        $save['percent_ds'] = $_POST['percent_ds']; 2581        $save['percent_ds'] = $_POST['percent_ds'];
2546    } else { 2582    } else {
2547        $save['percent_ds'] = ''; 2583        $save['percent_ds'] = '';
2548    } 2584    }
2549  2585 
2550    if (isset($_POST['expression'])) { 2586    if (isset($_POST['expression'])) {
2551        $save['expression'] = $_POST['expression']; 2587        $save['expression'] = $_POST['expression'];
2552    } else { 2588    } else {
2553        $save['expression'] = ''; 2589        $save['expression'] = '';
2554    } 2590    }
  2591    // SMS
  2592    $save['smstime_exempt_enable'] = $_POST['smstime_exempt_enable'];
  2593    $save['smstime_exempt_start']  = $_POST['smstime_exempt_start'];
  2594    $save['smstime_exempt_stop']   = $_POST['smstime_exempt_stop'];
  2595     
2555  2596 
2556    /* Get the Data Template, Graph Template, and Graph */  2597    /* Get the Data Template, Graph Template, and Graph */ 
2557    $rrdsql = db_fetch_row('SELECT id, data_template_id FROM data_template_rrd WHERE local_data_id=' . $save['rra_id'] . ' ORDER BY id'); 2598    $rrdsql = db_fetch_row('SELECT id, data_template_id FROM data_template_rrd WHERE local_data_id=' . $save['rra_id'] . ' ORDER BY id');
2558    $rrdlookup = $rrdsql['id']; 2599    $rrdlookup = $rrdsql['id'];
2559    $grapharr = db_fetch_row("SELECT local_graph_id, graph_template_id FROM graph_templates_item WHERE task_item_id=$rrdlookup and local_graph_id <> '' LIMIT 1"); 2600    $grapharr = db_fetch_row("SELECT local_graph_id, graph_template_id FROM graph_templates_item WHERE task_item_id=$rrdlookup and local_graph_id <> '' LIMIT 1");
2560  2601 
2561    $save['graph_id']       = $grapharr['local_graph_id']; 2602    $save['graph_id']       = $grapharr['local_graph_id'];
2562    $save['graph_template'] = $grapharr['graph_template_id']; 2603    $save['graph_template'] = $grapharr['graph_template_id'];
2563    $save['data_template']  = $rrdsql['data_template_id']; 2604    $save['data_template']  = $rrdsql['data_template_id'];
2564  2605 
2565    if (!thold_user_auth_threshold ($save['rra_id'])) { 2606    if (!thold_user_auth_threshold ($save['rra_id'])) {
2566        $banner = '<font color=red><strong>Permission Denied</strong></font>'; 2607        $banner = '<font color=red><strong>Permission Denied</strong></font>';
2567        return; 2608        return;
2568    } 2609    }
2569  2610     
2570    $id = sql_save($save , 'thold_data'); 2611    $id = sql_save($save , 'thold_data');
2571  2612 
2572    if (isset($_POST['notify_accounts']) && is_array($_POST['notify_accounts'])) { 2613    if (isset($_POST['notify_accounts']) && is_array($_POST['notify_accounts'])) {
2573        thold_save_threshold_contacts ($id, $_POST['notify_accounts']); 2614        thold_save_threshold_contacts ($id, $_POST['notify_accounts']);
2574    } elseif (!isset($_POST['notify_accounts'])) { 2615    } elseif (!isset($_POST['notify_accounts'])) {
2575        thold_save_threshold_contacts ($id, array()); 2616        thold_save_threshold_contacts ($id, array());
2576    } 2617    }
2577  2618 
2578    if ($id) { 2619    if ($id) {
2579        plugin_thold_log_changes($id, 'modified', $save); 2620        plugin_thold_log_changes($id, 'modified', $save);
2580        $thold = db_fetch_row("SELECT * FROM thold_data WHERE id=$id"); 2621        $thold = db_fetch_row("SELECT * FROM thold_data WHERE id=$id");
2581        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']); 2622        $ds = db_fetch_cell('SELECT data_source_name FROM data_template_rrd WHERE id=' . $thold['data_id']);
2582  2623 
2583        if ($thold["thold_type"] == 1) { 2624        if ($thold["thold_type"] == 1) {
2584            thold_check_threshold ($thold['rra_id'], $thold['data_id'], $ds, $thold['lastread'], $thold['cdef']); 2625            thold_check_threshold ($thold['rra_id'], $thold['data_id'], $ds, $thold['lastread'], $thold['cdef']);
2585        } 2626        }
2586    } 2627    }
2587  2628 
2588    $banner = '<font color=green><strong>Record Updated</strong></font>'; 2629    $banner = '<font color=green><strong>Record Updated</strong></font>';
2589} 2630}
2590  2631 
2591function thold_save_template_contacts ($id, $contacts) { 2632function thold_save_template_contacts ($id, $contacts) {
2592    db_execute('DELETE FROM plugin_thold_template_contact WHERE template_id = ' . $id); 2633    db_execute('DELETE FROM plugin_thold_template_contact WHERE template_id = ' . $id);
2593    // ADD SOME SECURITY!! 2634    // ADD SOME SECURITY!!
2594    if (!empty($contacts)) { 2635    if (!empty($contacts)) {
2595        foreach ($contacts as $contact) { 2636        foreach ($contacts as $contact) {
2596            db_execute("INSERT INTO plugin_thold_template_contact (template_id, contact_id) VALUES ($id, $contact)"); 2637            db_execute("INSERT INTO plugin_thold_template_contact (template_id, contact_id) VALUES ($id, $contact)");
2597        } 2638        }
2598    } 2639    }
2599} 2640}
2600  2641 
2601function thold_save_threshold_contacts ($id, $contacts) { 2642function thold_save_threshold_contacts ($id, $contacts) {
2602    db_execute('DELETE FROM plugin_thold_threshold_contact WHERE thold_id = ' . $id); 2643    db_execute('DELETE FROM plugin_thold_threshold_contact WHERE thold_id = ' . $id);
2603    // ADD SOME SECURITY!! 2644    // ADD SOME SECURITY!!
2604    foreach ($contacts as $contact) { 2645    foreach ($contacts as $contact) {
2605        db_execute("INSERT INTO plugin_thold_threshold_contact (thold_id, contact_id) VALUES ($id, $contact)"); 2646        db_execute("INSERT INTO plugin_thold_threshold_contact (thold_id, contact_id) VALUES ($id, $contact)");
2606    } 2647    }
2607} 2648}
2608  2649 
2609function thold_mandatory_field_ok($name, $friendly_name) { 2650function thold_mandatory_field_ok($name, $friendly_name) {
2610    global $banner; 2651    global $banner;
2611    if (!isset($_POST[$name]) || (isset($_POST[$name]) && (trim($_POST[$name]) == '' || $_POST[$name] <= 0))) { 2652    if (!isset($_POST[$name]) || (isset($_POST[$name]) && (trim($_POST[$name]) == '' || $_POST[$name] <= 0))) {
2612        $banner .= '&quot;' . $friendly_name . '&quot; must be set to positive integer value!<br>RECORD NOT UPDATED!</strong></font>'; 2653        $banner .= '&quot;' . $friendly_name . '&quot; must be set to positive integer value!<br>RECORD NOT UPDATED!</strong></font>';
2613        return false; 2654        return false;
2614    } 2655    }
2615    return true; 2656    return true;
2616} 2657}
2617  2658 
2618// Create tholds for all possible data elements for a host 2659// Create tholds for all possible data elements for a host
2619function autocreate($hostid) { 2660function autocreate($hostid) {
2620    $c = 0; 2661    $c = 0;
2621    $message = ''; 2662    $message = '';
2622  2663 
2623    $rralist = db_fetch_assoc("SELECT id, data_template_id FROM data_local where host_id='$hostid'"); 2664    $rralist = db_fetch_assoc("SELECT id, data_template_id FROM data_local where host_id='$hostid'");
2624  2665 
2625    if (!count($rralist)) { 2666    if (!count($rralist)) {
2626        $_SESSION['thold_message'] = '<font size=-2>No thresholds were created.</font>'; 2667        $_SESSION['thold_message'] = '<font size=-2>No thresholds were created.</font>';
2627        return 0; 2668        return 0;
2628    } 2669    }
2629  2670 
2630    foreach ($rralist as $row) { 2671    foreach ($rralist as $row) {
2631        $local_data_id = $row['id']; 2672        $local_data_id = $row['id'];
2632        $data_template_id = $row['data_template_id']; 2673        $data_template_id = $row['data_template_id'];
2633        $existing = db_fetch_assoc('SELECT id FROM thold_data WHERE rra_id = ' . $local_data_id . ' AND data_id = ' . $data_template_id); 2674        $existing = db_fetch_assoc('SELECT id FROM thold_data WHERE rra_id = ' . $local_data_id . ' AND data_id = ' . $data_template_id);
2634        $template = db_fetch_assoc('SELECT * FROM thold_template WHERE data_template_id = ' . $data_template_id); 2675        $template = db_fetch_assoc('SELECT * FROM thold_template WHERE data_template_id = ' . $data_template_id);
2635  2676 
2636        if (count($existing) == 0 && count($template)) { 2677        if (count($existing) == 0 && count($template)) {
2637            $rrdlookup = db_fetch_cell("SELECT id FROM data_template_rrd WHERE local_data_id=$local_data_id order by id LIMIT 1"); 2678            $rrdlookup = db_fetch_cell("SELECT id FROM data_template_rrd WHERE local_data_id=$local_data_id order by id LIMIT 1");
2638  2679 
2639            $grapharr = db_fetch_row("SELECT local_graph_id, graph_template_id FROM graph_templates_item WHERE task_item_id=$rrdlookup and local_graph_id <> '' LIMIT 1"); 2680            $grapharr = db_fetch_row("SELECT local_graph_id, graph_template_id FROM graph_templates_item WHERE task_item_id=$rrdlookup and local_graph_id <> '' LIMIT 1");
2640            $graph = (isset($grapharr['local_graph_id']) ? $grapharr['local_graph_id'] : ''); 2681            $graph = (isset($grapharr['local_graph_id']) ? $grapharr['local_graph_id'] : '');
2641  2682 
2642            if ($graph) { 2683            if ($graph) {
2643                for ($y = 0; $y < count($template); $y++) { 2684                for ($y = 0; $y < count($template); $y++) {
2644                    $data_source_name = $template[$y]['data_source_name']; 2685                    $data_source_name = $template[$y]['data_source_name'];
2645                    $insert = array(); 2686                    $insert = array();
2646  2687 
2647                    $desc = db_fetch_cell('SELECT name_cache FROM data_template_data WHERE local_data_id=' . $local_data_id . ' LIMIT 1'); 2688                    $desc = db_fetch_cell('SELECT name_cache FROM data_template_data WHERE local_data_id=' . $local_data_id . ' LIMIT 1');
2648  2689 
2649                    $insert['name']               = $desc . ' [' . $data_source_name . ']'; 2690                    $insert['name']               = $desc . ' [' . $data_source_name . ']';
2650                    $insert['host_id']            = $hostid; 2691                    $insert['host_id']            = $hostid;
2651                    $insert['rra_id']             = $local_data_id; 2692                    $insert['rra_id']             = $local_data_id;
2652                    $insert['graph_id']           = $graph; 2693                    $insert['graph_id']           = $graph;
2653                    $insert['data_template']      = $data_template_id; 2694                    $insert['data_template']      = $data_template_id;
2654                    $insert['graph_template']     = $grapharr['graph_template_id']; 2695                    $insert['graph_template']     = $grapharr['graph_template_id'];
2655                    $insert['thold_warning_hi'] = $template[$y]['thold_warning_hi']; 2696                    $insert['thold_warning_hi'] = $template[$y]['thold_warning_hi'];
2656                    $insert['thold_warning_low'] = $template[$y]['thold_warning_low']; 2697                    $insert['thold_warning_low'] = $template[$y]['thold_warning_low'];
2657                    $insert['thold_warning_fail_trigger'] = $template[$y]['thold_warning_fail_trigger']; 2698                    $insert['thold_warning_fail_trigger'] = $template[$y]['thold_warning_fail_trigger'];
2658                    $insert['thold_hi']           = $template[$y]['thold_hi']; 2699                    $insert['thold_hi']           = $template[$y]['thold_hi'];
2659                    $insert['thold_low']          = $template[$y]['thold_low']; 2700                    $insert['thold_low']          = $template[$y]['thold_low'];
2660                    $insert['thold_fail_trigger'] = $template[$y]['thold_fail_trigger']; 2701                    $insert['thold_fail_trigger'] = $template[$y]['thold_fail_trigger'];
2661                    $insert['thold_enabled']      = $template[$y]['thold_enabled']; 2702                    $insert['thold_enabled']      = $template[$y]['thold_enabled'];
  2703                    $insert['mobile']             = $template[$y]['mobile'];
2662                    $insert['bl_ref_time_range']  = $template[$y]['bl_ref_time_range']; 2704                    $insert['bl_ref_time_range']  = $template[$y]['bl_ref_time_range'];
2663                    $insert['bl_pct_down']        = $template[$y]['bl_pct_down']; 2705                    $insert['bl_pct_down']        = $template[$y]['bl_pct_down'];
2664                    $insert['bl_pct_up']          = $template[$y]['bl_pct_up']; 2706                    $insert['bl_pct_up']          = $template[$y]['bl_pct_up'];
2665                    $insert['bl_fail_trigger']    = $template[$y]['bl_fail_trigger']; 2707                    $insert['bl_fail_trigger']    = $template[$y]['bl_fail_trigger'];
2666                    $insert['bl_alert']           = $template[$y]['bl_alert']; 2708                    $insert['bl_alert']           = $template[$y]['bl_alert'];
2667                    $insert['repeat_alert']       = $template[$y]['repeat_alert']; 2709                    $insert['repeat_alert']       = $template[$y]['repeat_alert'];
2668                    $insert['notify_extra']       = $template[$y]['notify_extra']; 2710                    $insert['notify_extra']       = $template[$y]['notify_extra'];
2669                    $insert['notify_warning_extra'] = $template[$y]['notify_warning_extra']; 2711                    $insert['notify_warning_extra'] = $template[$y]['notify_warning_extra'];
2670                    $insert['notify_warning']     = $template[$y]['notify_warning']; 2712                    $insert['notify_warning']     = $template[$y]['notify_warning'];
2671                    $insert['notify_alert']       = $template[$y]['notify_alert']; 2713                    $insert['notify_alert']       = $template[$y]['notify_alert'];
2672                    $insert['cdef']               = $template[$y]['cdef']; 2714                    $insert['cdef']               = $template[$y]['cdef'];
2673                    $insert['template']           = $template[$y]['id']; 2715                    $insert['template']           = $template[$y]['id'];
2674                    $insert['template_enabled']   = 'on'; 2716                    $insert['template_enabled']   = 'on';
2675  2717 
2676                    $rrdlist = db_fetch_assoc("SELECT id, data_input_field_id FROM data_template_rrd where local_data_id='$local_data_id' and data_source_name = '$data_source_name'"); 2718                    $rrdlist = db_fetch_assoc("SELECT id, data_input_field_id FROM data_template_rrd where local_data_id='$local_data_id' and data_source_name = '$data_source_name'");
2677  2719 
2678                    $int = array('id', 'data_template_id', 'data_source_id', 'thold_fail_trigger', 'bl_ref_time_range', 'bl_pct_down', 'bl_pct_up', 'bl_fail_trigger', 'bl_alert', 'repeat_alert', 'cdef'); 2720                    $int = array('id', 'data_template_id', 'data_source_id', 'thold_fail_trigger', 'bl_ref_time_range', 'bl_pct_down', 'bl_pct_up', 'bl_fail_trigger', 'bl_alert', 'repeat_alert', 'cdef');
2679                    foreach ($rrdlist as $rrdrow) { 2721                    foreach ($rrdlist as $rrdrow) {
2680                        $data_rrd_id=$rrdrow['id']; 2722                        $data_rrd_id=$rrdrow['id'];
2681                        $insert['data_id'] = $data_rrd_id; 2723                        $insert['data_id'] = $data_rrd_id;
2682                        $existing = db_fetch_assoc("SELECT id FROM thold_data WHERE rra_id='$local_data_id' AND data_id='$data_rrd_id'"); 2724                        $existing = db_fetch_assoc("SELECT id FROM thold_data WHERE rra_id='$local_data_id' AND data_id='$data_rrd_id'");
2683                        if (count($existing) == 0) { 2725                        if (count($existing) == 0) {
2684                            $insert['id'] = 0; 2726                            $insert['id'] = 0;
2685                            $id = sql_save($insert, 'thold_data'); 2727                            $id = sql_save($insert, 'thold_data');
2686                            if ($id) { 2728                            if ($id) {
2687                                thold_template_update_threshold ($id, $insert['template']); 2729                                thold_template_update_threshold ($id, $insert['template']);
2688  2730 
2689                                $l = db_fetch_assoc("SELECT name FROM data_template where id=$data_template_id"); 2731                                $l = db_fetch_assoc("SELECT name FROM data_template where id=$data_template_id");
2690                                $tname = $l[0]['name']; 2732                                $tname = $l[0]['name'];
2691  2733 
2692                                $name = $data_source_name; 2734                                $name = $data_source_name;
2693                                if ($rrdrow['data_input_field_id'] != 0) { 2735                                if ($rrdrow['data_input_field_id'] != 0) {
2694                                    $l = db_fetch_assoc('SELECT name FROM data_input_fields where id=' . $rrdrow['data_input_field_id']); 2736                                    $l = db_fetch_assoc('SELECT name FROM data_input_fields where id=' . $rrdrow['data_input_field_id']);
2695                                    $name = $l[0]['name']; 2737                                    $name = $l[0]['name'];
2696                                } 2738                                }
2697                                plugin_thold_log_changes($id, 'auto_created', " $tname [$name]"); 2739                                plugin_thold_log_changes($id, 'auto_created', " $tname [$name]");
2698                                $message .= "Created threshold for the Graph '<i>$tname</i>' using the Data Source '<i>$name</i>'<br>"; 2740                                $message .= "Created threshold for the Graph '<i>$tname</i>' using the Data Source '<i>$name</i>'<br>";
2699                                $c++; 2741                                $c++;
2700                            } 2742                            }
2701                        } else { 2743                        } else {
2702                            foreach($existing as $r) { 2744                            foreach($existing as $r) {
2703                                $id = $r['id']; 2745                                $id = $r['id'];
2704                                $l = db_fetch_assoc("SELECT name FROM thold_data WHERE id=$id"); 2746                                $l = db_fetch_assoc("SELECT name FROM thold_data WHERE id=$id");
2705                                $name = $l[0]['name']; 2747                                $name = $l[0]['name'];
2706                                if ($name != $insert['name']) { 2748                                if ($name != $insert['name']) {
2707                                    db_execute("UPDATE thold_data SET name = '" . $insert['name'] . "' WHERE id=$id"); 2749                                    db_execute("UPDATE thold_data SET name = '" . $insert['name'] . "' WHERE id=$id");
2708                                    plugin_thold_log_changes($id, "updated_name: $name => " . $insert['name']); 2750                                    plugin_thold_log_changes($id, "updated_name: $name => " . $insert['name']);
2709                                    $message .= "Updated threshold $id: changed name from '<i>$name</i>' to '<i>" . $insert['name'] . "</i>'<br>"; 2751                                    $message .= "Updated threshold $id: changed name from '<i>$name</i>' to '<i>" . $insert['name'] . "</i>'<br>";
2710                                    $c++; 2752                                    $c++;
2711                                } 2753                                }
2712                            } 2754                            }
2713                        } 2755                        }
2714                    } 2756                    }
2715                } 2757                }
2716            } 2758            }
2717        } 2759        }
2718    } 2760    }
2719    $_SESSION['thold_message'] = "<font size=-2>$message</font>"; 2761    $_SESSION['thold_message'] = "<font size=-2>$message</font>";
2720    return $c; 2762    return $c;
2721} 2763}
2722  2764 
  2765 
2723/* Sends a group of graphs to a user */  2766/* Sends a group of graphs to a user */ 
2724function thold_mail($to, $from, $subject, $message, $filename, $headers = '') { 2767function thold_mail($to, $from, $subject, $message, $filename, $headers = '') {
2725    global $config; 2768    global $config;
2726    thold_debug('Preparing to send email'); 2769    thold_debug('Preparing to send email');
2727    include_once($config['base_path'] . '/plugins/settings/include/mailer.php'); 2770    include_once($config['base_path'] . '/plugins/settings/include/mailer.php');
2728    include_once($config['base_path'] . '/plugins/thold/setup.php'); 2771    include_once($config['base_path'] . '/plugins/thold/setup.php');
2729  2772 
2730    $subject = trim($subject); 2773    $subject = trim($subject);
2731  2774 
2732    $message = str_replace('<SUBJECT>', $subject, $message); 2775    $message = str_replace('<SUBJECT>', mb_convert_encoding(($subject),"utf-8","gb2312"), $message);
2733  2776 
2734    $how = read_config_option('settings_how'); 2777    $how = read_config_option('settings_how');
2735    if ($how < 0 && $how > 2) 2778    if ($how < 0 && $how > 2)
2736        $how = 0; 2779        $how = 0;
2737    if ($how == 0) { 2780    if ($how == 0) {
2738        $Mailer = new Mailer(array( 2781        $Mailer = new Mailer(array(
2739            'Type' => 'PHP')); 2782            'Type' => 'PHP'));
2740    } else if ($how == 1) { 2783    } else if ($how == 1) {
2741        $sendmail = read_config_option('settings_sendmail_path'); 2784        $sendmail = read_config_option('settings_sendmail_path');
2742        $Mailer = new Mailer(array( 2785        $Mailer = new Mailer(array(
2743            'Type' => 'DirectInject', 2786            'Type' => 'DirectInject',
2744            'DirectInject_Path' => $sendmail)); 2787            'DirectInject_Path' => $sendmail));
2745    } else if ($how == 2) { 2788    } else if ($how == 2) {
2746        $smtp_host = read_config_option('settings_smtp_host'); 2789        $smtp_host = read_config_option('settings_smtp_host');
2747        $smtp_port = read_config_option('settings_smtp_port'); 2790        $smtp_port = read_config_option('settings_smtp_port');
2748        $smtp_username = read_config_option('settings_smtp_username'); 2791        $smtp_username = read_config_option('settings_smtp_username');
2749        $smtp_password = read_config_option('settings_smtp_password'); 2792        $smtp_password = read_config_option('settings_smtp_password');
2750  2793 
2751        $Mailer = new Mailer(array( 2794        $Mailer = new Mailer(array(
2752            'Type' => 'SMTP', 2795            'Type' => 'SMTP',
2753            'SMTP_Host' => $smtp_host, 2796            'SMTP_Host' => $smtp_host,
2754            'SMTP_Port' => $smtp_port, 2797            'SMTP_Port' => $smtp_port,
2755            'SMTP_Username' => $smtp_username, 2798            'SMTP_Username' => $smtp_username,
2756            'SMTP_Password' => $smtp_password)); 2799            'SMTP_Password' => $smtp_password));
2757    } 2800    }
2758  2801 
2759    if ($from == '') { 2802    if ($from == '') {
2760        $from = read_config_option('thold_from_email'); 2803        $from = read_config_option('thold_from_email');
2761        $fromname = read_config_option('thold_from_name'); 2804        $fromname = read_config_option('thold_from_name');
2762        if ($from == '') { 2805        if ($from == '') {
2763            if (isset($_SERVER['HOSTNAME'])) { 2806            if (isset($_SERVER['HOSTNAME'])) {
2764                $from = 'Cacti@' . $_SERVER['HOSTNAME']; 2807                $from = 'Cacti@' . $_SERVER['HOSTNAME'];
2765            } else { 2808            } else {
2766                $from = 'Cacti@localhost'; 2809                $from = 'Cacti@localhost';
2767            } 2810            }
2768        } 2811        }
2769        if ($fromname == '') 2812        if ($fromname == '')
2770            $fromname = 'Cacti'; $from = $Mailer->email_format($fromname, $from); 2813            $fromname = 'Cacti'; $from = $Mailer->email_format($fromname, $from);
2771        if ($Mailer->header_set('From', $from) === false) { 2814        if ($Mailer->header_set('From', $from) === false) {
2772            print 'ERROR: ' . $Mailer->error() . "\n"; 2815            print 'ERROR: ' . $Mailer->error() . "\n";
2773            return $Mailer->error(); 2816            return $Mailer->error();
2774        } 2817        }
2775    } else { 2818    } else {
2776        $from = $Mailer->email_format('Cacti', $from); 2819        $from = $Mailer->email_format('Cacti', $from);
2777        if ($Mailer->header_set('From', $from) === false) { 2820        if ($Mailer->header_set('From', $from) === false) {
2778            print 'ERROR: ' . $Mailer->error() . "\n"; 2821            print 'ERROR: ' . $Mailer->error() . "\n";
2779            return $Mailer->error(); 2822            return $Mailer->error();
2780        } 2823        }
2781    } 2824    }
2782  2825 
2783    if ($to == '') 2826    if ($to == '')
2784        return 'Mailer Error: No <b>TO</b> address set!!<br>If using the <i>Test Mail</i> link, please set the <b>Alert e-mail</b> setting.'; 2827        return 'Mailer Error: No <b>TO</b> address set!!<br>If using the <i>Test Mail</i> link, please set the <b>Alert e-mail</b> setting.';
2785    $to = explode(',', $to); 2828      $to = explode(',', $to);
2786  2829       
  2830    $to_mail1 = array();
  2831    $to_mail2 = array();
  2832    $to_sms   = array();
  2833    $kk1 = 0;
  2834    $kk2 = 0;
  2835    $kk3 = 0;
  2836     
  2837    for($ii=0; $ii<=count($to); $ii++){
  2838        $user_id_check = db_fetch_cell("SELECT type FROM plugin_thold_contacts WHERE data ='$to[$ii]'");
  2839        if($user_id_check == 'email'){
  2840            $to_mail1[$kk1] = $to[$ii];
  2841            $kk1 = $kk1+1;
  2842        }
  2843        if($user_id_check == 'mobile_num'){
  2844            $to_sms[$kk2] = $to[$ii];
  2845            $kk2 = $kk2+1;
  2846        }
  2847        if(($user_id_check == '') and (strpos($to[$ii],'@'))){
  2848            $to_mail2[$kk3] = $to[$ii];
  2849            $kk3 = $kk3+1;
  2850        }
  2851      }
  2852       
  2853              
  2854  if((count($to_mail1) ==0) and (count($to_mail2))>=1){
  2855    $to = $to_mail2;
  2856  }
  2857  if((count($to_mail1) >=1) and (count($to_mail2))>=1){
  2858    $to = explode(',', (implode(',', $to_mail1).','.implode(',', $to_mail2)));
  2859  }
  2860  if((count($to_mail1) >=1) and (count($to_mail2))==0){
  2861    $to = $to_mail1;
  2862  }
  2863   
  2864          
  2865             
2787    foreach($to as $t) { 2866    foreach($to as $t) {
2788        if (trim($t) != '' && !$Mailer->header_set('To', $t)) { 2867        if (trim($t) != '' && !$Mailer->header_set('To', $t)) {
2789            print 'ERROR: ' . $Mailer->error() . "\n"; 2868            print 'ERROR: ' . $Mailer->error() . "\n";
2790            return $Mailer->error(); 2869            return $Mailer->error();
2791        } 2870        }
2792    } 2871    }
  2872     
2793  2873 
2794    $wordwrap = read_config_option('settings_wordwrap'); 2874    $wordwrap = read_config_option('settings_wordwrap');
2795    if ($wordwrap == '') 2875    if ($wordwrap == '')
2796        $wordwrap = 76; 2876        $wordwrap = 76;
2797    if ($wordwrap > 9999) 2877    if ($wordwrap > 9999)
2798        $wordwrap = 9999; 2878        $wordwrap = 9999;
2799    if ($wordwrap < 0) 2879    if ($wordwrap < 0)
2800        $wordwrap = 76; 2880        $wordwrap = 76;
2801  2881 
2802    $Mailer->Config['Mail']['WordWrap'] = $wordwrap; 2882    $Mailer->Config['Mail']['WordWrap'] = $wordwrap;
2803  2883 
2804    if (! $Mailer->header_set('Subject', $subject)) { 2884    if (! $Mailer->header_set('Subject', $subject)) {
2805        print 'ERROR: ' . $Mailer->error() . "\n"; 2885        print 'ERROR: ' . $Mailer->error() . "\n";
2806        return $Mailer->error(); 2886        return $Mailer->error();
2807    } 2887    }
2808  2888 
2809    if (is_array($filename) && !empty($filename) && strstr($message, '<GRAPH>') !==0) { 2889    if (is_array($filename) && !empty($filename) && strstr($message, '<GRAPH>') !==0) {
2810        foreach($filename as $val) { 2890        foreach($filename as $val) {
2811            $graph_data_array = array('output_flag'=> RRDTOOL_OUTPUT_STDOUT); 2891            $graph_data_array = array('output_flag'=> RRDTOOL_OUTPUT_STDOUT);
2812            if (function_exists('imagecreatefrompng') && function_exists('imagejpeg')) { 2892            if (function_exists('imagecreatefrompng') && function_exists('imagejpeg')) {
2813                $data = @png2jpeg(rrdtool_function_graph($val['local_graph_id'], $val['rra_id'], $graph_data_array)); 2893                $data = @png2jpeg(rrdtool_function_graph($val['local_graph_id'], $val['rra_id'], $graph_data_array));
2814                $ext = 'jpg'; 2894                $ext = 'jpg';
2815            } else { 2895            } else {
2816                $data = @rrdtool_function_graph($val['local_graph_id'], $val['rra_id'], $graph_data_array); 2896                $data = @rrdtool_function_graph($val['local_graph_id'], $val['rra_id'], $graph_data_array);
2817                $ext = 'png'; 2897                $ext = 'png';
2818            } 2898            }
2819            if ($data != '') { 2899            if ($data != '') {
2820                $cid = $Mailer->content_id(); 2900                $cid = $Mailer->content_id();
2821                if ($Mailer->attach($data, $val['filename'].".$ext", "image/$ext", 'inline', $cid) == false) { 2901                if ($Mailer->attach($data, $val['filename'].".$ext", "image/$ext", 'inline', $cid) == false) {
2822                    print 'ERROR: ' . $Mailer->error() . "\n"; 2902                    print 'ERROR: ' . $Mailer->error() . "\n";
2823                    return $Mailer->error(); 2903                    return $Mailer->error();
2824                } 2904                }
2825                $message = str_replace('<GRAPH>', "<br><br><img src='cid:$cid'>", $message); 2905                $message = str_replace('<GRAPH>', "<br><br><img src='cid:$cid'>", $message);
2826            } else { 2906            } else {
2827                $message = str_replace('<GRAPH>', "<br><img src='" . $val['file'] . "'><br>Could not open!<br>" . $val['file'], $message); 2907                $message = str_replace('<GRAPH>', "<br><img src='" . $val['file'] . "'><br>Could not open!<br>" . $val['file'], $message);
2828            } 2908            }
2829        } 2909        }
2830    } 2910    }
2831    $text = array('text' => '', 'html' => ''); 2911    $text = array('text' => '', 'html' => '');
2832    if ($filename == '') { 2912    if ($filename == '') {
2833        $message = str_replace('<br>',  "\n", $message); 2913        $message = str_replace('<br>',  "\n", $message);
2834        $message = str_replace('<BR>',  "\n", $message); 2914        $message = str_replace('<BR>',  "\n", $message);
2835        $message = str_replace('</BR>', "\n", $message); 2915        $message = str_replace('</BR>', "\n", $message);
2836        $text['text'] = strip_tags($message); 2916        $text['text'] = strip_tags($message);
2837    } else { 2917    } else {
2838        $text['html'] = $message . '<br>'; 2918        $text['html'] = $message . '<br>';
2839        $text['text'] = strip_tags(str_replace('<br>', "\n", $message)); 2919        $text['text'] = strip_tags(str_replace('<br>', "\n", $message));
2840    } 2920    }
2841  2921 
2842    $v = thold_version(); 2922    $v = thold_version();
2843    $Mailer->header_set('X-Mailer', 'Cacti-Thold-v' . $v['version']); 2923    $Mailer->header_set('X-Mailer', 'Cacti-Thold-v' . $v['version']);
2844    $Mailer->header_set('User-Agent', 'Cacti-Thold-v' . $v['version']); 2924    $Mailer->header_set('User-Agent', 'Cacti-Thold-v' . $v['version']);
2845    if (read_config_option('thold_email_prio') == 'on') { 2925    if (read_config_option('thold_email_prio') == 'on') {
2846        $Mailer->header_set('X-Priority', '1'); 2926        $Mailer->header_set('X-Priority', '1');
2847    } 2927    }
2848    thold_debug("Sending email to '" . trim(implode(',',$to),',') . "'"); 2928    thold_debug("Sending email to '" . trim(implode(',',$to),',') . "'");
  2929     
  2930         
  2931  /* 判断是否需要?送短信 EDIT BY tracky2008 */ 
  2932  /* 先截取$subject中第一个:到第一个]之?的字符串?得当前要?条目在数据?中的位置判断是否勾?了sms_enable,是否使用??段?? */ 
  2933 
  2934   $filepath = "/usr/local/apache/htdocs/cacti/plugins/thold/host_sms_config/hostdown_sms_config.xls";
  2935   if(preg_match("/\\((.+?)\\)/",$subject,$arr_temp)){
  2936     $subject_hostip = trim($arr_temp[1]);
  2937     $array_temp = array();
  2938     $array_temp = explode(';',read_excel($filepath,$subject_hostip));
  2939     $host_sms_check = $array_temp[0];
  2940     $host_sms_nums_temp = $array_temp[1];
  2941     if(!empty($host_sms_nums_temp) and ($host_sms_check == 'on')){
  2942       $host_sms_nums = array();
  2943       $host_sms_nums = explode(",",$host_sms_nums_temp);
  2944       if(count($host_sms_nums)>=1){
  2945         for($kkk=0; $kkk<=count($host_sms_nums); $kkk++){
  2946           thold_mms($host_sms_nums[$kkk],$subject);
  2947        }
  2948       }
  2949     }
  2950   }else{
  2951       preg_match("/:(.+?)]/",$subject,$arr_temp);
  2952       $subject_temp = (iconv("GB2312", "UTF-8//IGNORE", trim($arr_temp[1])))."]";
  2953     }
  2954 
  2955   $sms_enable_check = db_fetch_cell("SELECT mobile FROM thold_data WHERE name = '$subject_temp'");
  2956   $sms_exempt_check = db_fetch_cell("SELECT smstime_exempt_enable FROM thold_data WHERE name = '$subject_temp'");
  2957   $sms_exempt_check_start = db_fetch_cell("SELECT smstime_exempt_start FROM thold_data WHERE name = '$subject_temp'");
  2958   $sms_exempt_check_stop  = db_fetch_cell("SELECT smstime_exempt_stop FROM thold_data WHERE name = '$subject_temp'");
  2959    
  2960 
  2961   if($sms_enable_check == "on") {
  2962     if($sms_exempt_check == 0){
  2963       if(count($to_sms)>=1){
  2964        for($iii=0; $iii<=count($to_sms); $iii++){
  2965            thold_mms($to_sms[$iii],$subject);
  2966            }
  2967          }
  2968        }
  2969     if($sms_exempt_check == 1){
  2970       if(($sms_exempt_check_stop > $sms_exempt_check_stop) and !((date("G:i:s") >= $sms_exempt_check_start) and (date("G:i:s") <= $sms_exempt_check_stop))){
  2971        if(count($to_sms)>=1){
  2972          for($iii=0; $iii<=count($to_sms); $iii++){
  2973            thold_mms($to_sms[$iii],$subject);
  2974            }
  2975           }
  2976          }
  2977       if(($sms_exempt_check_stop < $sms_exempt_check_stop) and !(((date("G:i:s") >= $sms_exempt_check_start) and (date("G:i:s") <= '23:59:59')) and ((date("G:i:s") >= '0:00:00') or (date("G:i:s") <= $sms_exempt_check_stop)))){
  2978        if(count($to_sms)>=1){
  2979          for($iii=0; $iii<=count($to_sms); $iii++){
  2980            thold_mms($to_sms[$iii],$subject);
  2981            }
  2982           }
  2983        }
  2984      }
  2985    }
  2986   
  2987    
2849    if ($Mailer->send($text) == false) { 2988    if ($Mailer->send($text) == false) {
2850        print 'ERROR: ' . $Mailer->error() . "\n"; 2989        print 'ERROR: ' . $Mailer->error() . "\n";
2851        return $Mailer->error(); 2990        return $Mailer->error();
2852    } 2991    }
2853  2992 
2854    return ''; 2993    return '';
2855} 2994}
2856  2995 
  2996/*
  2997+--------------------------------------------------------------------------------------+
  2998 | Function:Read Excel (use phpexcel)                                                               |
  2999 | content: ?取定?好的主机IP与手机号?定列表,?定是否?送短信  EDIT BY tracky2008  |
  3000 +-------------------------------------------------------------------------------------+
  3001*/ 
  3002 
  3003 
  3004function read_excel($filepath,$host_ip) {
  3005  include_once('/usr/local/apache/htdocs/Classes/PHPExcel/IOFactory.php');
  3006  //$reader = PHPExcel_IOFactory::createReader('Excel2007'); // ?取 excel 文件
  3007  //$PHPExcel = $reader->load("test.xls"); //文件名称  
  3008  /*默?用excel2007?取excel,若格式不?,?用之前的版本?行?取*/  
  3009   
  3010  $Reader = new PHPExcel_Reader_Excel2007();
  3011    if(!$Reader->canRead($filepath)){
  3012      $Reader = new PHPExcel_Reader_Excel5();
  3013      if(!$Reader->canRead($filepath)){
  3014        echo 'no Excel';
  3015        return ;
  3016      }
  3017    }
  3018 
  3019  $PHPExcel = PHPExcel_IOFactory::load($filepath);
  3020  $sheet = $PHPExcel->getSheet(0); // ?取第一個工作表(?号从 0 ?始)  
  3021  $highestRow = $sheet->getHighestRow(); // 取得?行数  
  3022  $highestColumn = $sheet->getHighestColumn(); // 取得?列数  
  3023 
  3024  $arr = array(1=>'A',2=>'B',3=>'C',4=>'D',5=>'E',6=>'F',7=>'G',8=>'H',9=>'I',10=>'J',11=>'K',12=>'L',13=>'M', 14=>'N',15=>'O',16=>'P',17=>'Q',18=>'R',19=>'S',20=>'T',21=>'U',22=>'V',23=>'W',24=>'X',25=>'Y',26=>'Z');
  3025 
  3026  //echo $highestRow.$highestColumn;exit;
  3027 
  3028  //?取指定host_ip??的C、D?元格的?,并存入$val数?
  3029   
  3030  for ($row = 2; $row <= $highestRow; $row++) {
  3031    $val_hostip = $sheet->getCellByColumnAndRow(0, $row)->getValue();
  3032    if($val_hostip == $host_ip){
  3033      for ($column = 3; $column < 4; $column++)  {
  3034            $val_1 = $sheet->getCellByColumnAndRow(3, $row)->getValue();
  3035            if($val_1 !== ''){
  3036                $val_1 = $val_1;
  3037            }else{
  3038                $val_1 = 'off';
  3039            }
  3040            $val_2 = $sheet->getCellByColumnAndRow(4, $row)->getValue();
  3041            //echo $val[2];
  3042            $val = $val_1.";".$val_2;
  3043            return $val;
  3044      }
  3045    }
  3046  }
  3047}
  3048 
  3049/*
  3050 +-------------------------------------------------------------------------+
  3051 | Function:Send SMS                                                      |
  3052 | content: ?用oracle的存??程?送短信  EDIT BY tracky2008                                           |
  3053 +-------------------------------------------------------------------------+
  3054*/ 
  3055function thold_mms($number,$sms_content) {
  3056    /* 其中$number是手机号?,$sms_content是?送内容 */      
  3057   //?始存??程?用,注意PHP要使用OCI的?接方式?用Oracle必?安装PHP-OCI8的?展
  3058   //建立数据??接
  3059   $ora_user = "szsm"; //数据?用?名
  3060   $ora_password = "szsm"; //密?
  3061   //$oraconn_str = "//192.168.22.88:1521/test"; //?接串(cstr : connection_string)
  3062   $ora_remote = true; //是否?程?接
  3063   $ora_proc_name = "msgp_pck.sendsms2"; //存??程名
  3064    
  3065   if ($ora_remote) {
  3066      $conn = ocilogon($ora_user, $ora_password,"(DESCRIPTION =
  3067    (ADDRESS_LIST =
  3068      (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.22.88)(PORT = 1521))
  3069    )
  3070    (CONNECT_DATA =
  3071      (SERVICE_NAME = test)
  3072    ))",'zhs16gbk');
  3073    }
  3074      else {
  3075      $conn = ocilogon($ora_user, $ora_password);
  3076    }
  3077   $ora_sql = "BEGIN $ora_proc_name(:i_toid,:i_content,:i_priority,:i_createid,:o_serialno,:o_errorcode); END;";
  3078   // Parse
  3079   $stmt = oci_parse($conn,$ora_sql);
  3080    
  3081   //?行?定
  3082   //OCIBindByName($stmt, ":id", $id, 16);           //参数?明:?定php?量$id到位置:id,并?定?定?度16位
  3083 
  3084   $temp_str1 = 1;
  3085   $temp_str2 = "msgp";
  3086 
  3087    
  3088   OCIBindByName($stmt, ":i_toid", $number, 20);
  3089   OCIBindByName($stmt, ":i_content",  $sms_content, 500);
  3090   OCIBindByName($stmt, ":i_priority", $temp_str1, 20);
  3091   OCIBindByName($stmt, ":i_createid", $temp_str2, 500);
  3092   OCIBindByName($stmt, ":o_serialno", $serialno, 20);
  3093   OCIBindByName($stmt, ":o_errorcode", $sms_errorcode, 500);
  3094    
  3095   //?行?送
  3096    
  3097   OCIExecute($stmt);
  3098    
  3099   //???果?出至指定文件
  3100   $smserr_filename= "/usr/local/apache/htdocs/cacti/plugins/thold/sms.log";
  3101   if(!file_exists($smserr_filename)){//文件不存在就?建
  3102         @fopen($smslog_filename, "w+");
  3103     } else {
  3104        $smserr_log_file = @fopen($smserr_filename,"a");//追加写入模式
  3105        if($serialno = 0) {
  3106            $smserrlog_data = date("Y-m-d H:i:s") . $sms_errorcode . \r\n;
  3107             @fwrite($smserr_log_file, $smserrlog_data);
  3108         @fclose($smserr_log_file);
  3109        }
  3110            }
  3111}
  3112 
  3113 
2857function thold_template_update_threshold ($id, $template) { 3114function thold_template_update_threshold ($id, $template) {
2858    db_execute("UPDATE thold_data, thold_template 3115    db_execute("UPDATE thold_data, thold_template
2859        SET 3116        SET
2860        thold_data.template_enabled = 'on', 3117        thold_data.template_enabled = 'on',
2861        thold_data.thold_hi = thold_template.thold_hi, 3118        thold_data.thold_hi = thold_template.thold_hi,
2862        thold_data.thold_low = thold_template.thold_low, 3119        thold_data.thold_low = thold_template.thold_low,
2863        thold_data.thold_fail_trigger = thold_template.thold_fail_trigger, 3120        thold_data.thold_fail_trigger = thold_template.thold_fail_trigger,
2864        thold_data.time_hi = thold_template.time_hi, 3121        thold_data.time_hi = thold_template.time_hi,
2865        thold_data.time_low = thold_template.time_low, 3122        thold_data.time_low = thold_template.time_low,
2866        thold_data.time_fail_trigger = thold_template.time_fail_trigger, 3123        thold_data.time_fail_trigger = thold_template.time_fail_trigger,
2867        thold_data.time_fail_length = thold_template.time_fail_length, 3124        thold_data.time_fail_length = thold_template.time_fail_length,
2868        thold_data.thold_warning_hi = thold_template.thold_warning_hi, 3125        thold_data.thold_warning_hi = thold_template.thold_warning_hi,
2869        thold_data.thold_warning_low = thold_template.thold_warning_low, 3126        thold_data.thold_warning_low = thold_template.thold_warning_low,
2870        thold_data.thold_warning_fail_trigger = thold_template.thold_warning_fail_trigger, 3127        thold_data.thold_warning_fail_trigger = thold_template.thold_warning_fail_trigger,
2871        thold_data.time_warning_hi = thold_template.time_warning_hi, 3128        thold_data.time_warning_hi = thold_template.time_warning_hi,
2872        thold_data.time_warning_low = thold_template.time_warning_low, 3129        thold_data.time_warning_low = thold_template.time_warning_low,
2873        thold_data.time_warning_fail_trigger = thold_template.time_warning_fail_trigger, 3130        thold_data.time_warning_fail_trigger = thold_template.time_warning_fail_trigger,
2874        thold_data.time_warning_fail_length = thold_template.time_warning_fail_length, 3131        thold_data.time_warning_fail_length = thold_template.time_warning_fail_length,
2875        thold_data.thold_enabled = thold_template.thold_enabled, 3132        thold_data.thold_enabled = thold_template.thold_enabled,
  3133        thold_data.mobile = thold_template.mobile,
2876        thold_data.thold_type = thold_template.thold_type, 3134        thold_data.thold_type = thold_template.thold_type,
2877        thold_data.bl_ref_time_range = thold_template.bl_ref_time_range, 3135        thold_data.bl_ref_time_range = thold_template.bl_ref_time_range,
2878        thold_data.bl_pct_down = thold_template.bl_pct_down, 3136        thold_data.bl_pct_down = thold_template.bl_pct_down,
2879        thold_data.bl_pct_up = thold_template.bl_pct_up, 3137        thold_data.bl_pct_up = thold_template.bl_pct_up,
2880        thold_data.bl_fail_trigger = thold_template.bl_fail_trigger, 3138        thold_data.bl_fail_trigger = thold_template.bl_fail_trigger,
2881        thold_data.bl_alert = thold_template.bl_alert, 3139        thold_data.bl_alert = thold_template.bl_alert,
2882        thold_data.bl_thold_valid = 0, 3140        thold_data.bl_thold_valid = 0,
2883        thold_data.repeat_alert = thold_template.repeat_alert, 3141        thold_data.repeat_alert = thold_template.repeat_alert,
2884        thold_data.notify_extra = thold_template.notify_extra, 3142        thold_data.notify_extra = thold_template.notify_extra,
2885        thold_data.notify_warning_extra = thold_template.notify_warning_extra, 3143        thold_data.notify_warning_extra = thold_template.notify_warning_extra,
2886        thold_data.notify_warning = thold_template.notify_warning, 3144        thold_data.notify_warning = thold_template.notify_warning,
2887        thold_data.notify_alert = thold_template.notify_alert, 3145        thold_data.notify_alert = thold_template.notify_alert,
2888        thold_data.data_type = thold_template.data_type, 3146        thold_data.data_type = thold_template.data_type,
2889        thold_data.cdef = thold_template.cdef, 3147        thold_data.cdef = thold_template.cdef,
2890        thold_data.percent_ds = thold_template.percent_ds, 3148        thold_data.percent_ds = thold_template.percent_ds,
2891        thold_data.expression = thold_template.expression, 3149        thold_data.expression = thold_template.expression,
2892        thold_data.exempt = thold_template.exempt, 3150        thold_data.exempt = thold_template.exempt,
2893        thold_data.data_template = thold_template.data_template_id, 3151        thold_data.data_template = thold_template.data_template_id,
2894        thold_data.restored_alert = thold_template.restored_alert  3152        thold_data.restored_alert = thold_template.restored_alert, 
  3153        thold_data.smstime_exempt_enable = thold_template.smstime_exempt_enable,
  3154        thold_data.smstime_exempt_start = thold_template.smstime_exempt_start,
  3155        thold_data.smstime_exempt_stop = thold_template.smstime_exempt_stop
2895        WHERE thold_data.id=$id AND thold_template.id=$template"); 3156        WHERE thold_data.id=$id AND thold_template.id=$template");
2896    db_execute('DELETE FROM plugin_thold_threshold_contact where thold_id = ' . $id); 3157    db_execute('DELETE FROM plugin_thold_threshold_contact where thold_id = ' . $id);
2897    db_execute("INSERT INTO plugin_thold_threshold_contact (thold_id, contact_id) SELECT $id, contact_id FROM plugin_thold_template_contact WHERE template_id = $template"); 3158    db_execute("INSERT INTO plugin_thold_threshold_contact (thold_id, contact_id) SELECT $id, contact_id FROM plugin_thold_template_contact WHERE template_id = $template");
2898} 3159}
2899  3160 
2900function thold_template_update_thresholds ($id) { 3161function thold_template_update_thresholds ($id) {
2901    db_execute("UPDATE thold_data, thold_template 3162    db_execute("UPDATE thold_data, thold_template
2902        SET thold_data.thold_hi = thold_template.thold_hi, 3163        SET thold_data.thold_hi = thold_template.thold_hi,
2903        thold_data.thold_low = thold_template.thold_low, 3164        thold_data.thold_low = thold_template.thold_low,
2904        thold_data.thold_fail_trigger = thold_template.thold_fail_trigger, 3165        thold_data.thold_fail_trigger = thold_template.thold_fail_trigger,
2905        thold_data.time_hi = thold_template.time_hi, 3166        thold_data.time_hi = thold_template.time_hi,
2906        thold_data.time_low = thold_template.time_low, 3167        thold_data.time_low = thold_template.time_low,
2907        thold_data.time_fail_trigger = thold_template.time_fail_trigger, 3168        thold_data.time_fail_trigger = thold_template.time_fail_trigger,
2908        thold_data.time_fail_length = thold_template.time_fail_length, 3169        thold_data.time_fail_length = thold_template.time_fail_length,
2909        thold_data.thold_warning_hi = thold_template.thold_warning_hi, 3170        thold_data.thold_warning_hi = thold_template.thold_warning_hi,
2910        thold_data.thold_warning_low = thold_template.thold_warning_low, 3171        thold_data.thold_warning_low = thold_template.thold_warning_low,
2911        thold_data.thold_warning_fail_trigger = thold_template.thold_warning_fail_trigger, 3172        thold_data.thold_warning_fail_trigger = thold_template.thold_warning_fail_trigger,
2912        thold_data.time_warning_hi = thold_template.time_warning_hi, 3173        thold_data.time_warning_hi = thold_template.time_warning_hi,
2913        thold_data.time_warning_low = thold_template.time_warning_low, 3174        thold_data.time_warning_low = thold_template.time_warning_low,
2914        thold_data.time_warning_fail_trigger = thold_template.time_warning_fail_trigger, 3175        thold_data.time_warning_fail_trigger = thold_template.time_warning_fail_trigger,
2915        thold_data.time_warning_fail_length = thold_template.time_warning_fail_length, 3176        thold_data.time_warning_fail_length = thold_template.time_warning_fail_length,
2916        thold_data.thold_enabled = thold_template.thold_enabled, 3177        thold_data.thold_enabled = thold_template.thold_enabled,
  3178        thold_data.mobile = thold_template.mobile,
2917        thold_data.thold_type = thold_template.thold_type, 3179        thold_data.thold_type = thold_template.thold_type,
2918        thold_data.bl_ref_time_range = thold_template.bl_ref_time_range, 3180        thold_data.bl_ref_time_range = thold_template.bl_ref_time_range,
2919        thold_data.bl_pct_up = thold_template.bl_pct_up, 3181        thold_data.bl_pct_up = thold_template.bl_pct_up,
2920        thold_data.bl_pct_down = thold_template.bl_pct_down, 3182        thold_data.bl_pct_down = thold_template.bl_pct_down,
2921        thold_data.bl_pct_up = thold_template.bl_pct_up, 3183        thold_data.bl_pct_up = thold_template.bl_pct_up,
2922        thold_data.bl_fail_trigger = thold_template.bl_fail_trigger, 3184        thold_data.bl_fail_trigger = thold_template.bl_fail_trigger,
2923        thold_data.bl_alert = thold_template.bl_alert, 3185        thold_data.bl_alert = thold_template.bl_alert,
2924        thold_data.bl_thold_valid = 0, 3186        thold_data.bl_thold_valid = 0,
2925        thold_data.repeat_alert = thold_template.repeat_alert, 3187        thold_data.repeat_alert = thold_template.repeat_alert,
2926        thold_data.notify_extra = thold_template.notify_extra, 3188        thold_data.notify_extra = thold_template.notify_extra,
2927        thold_data.notify_warning_extra = thold_template.notify_warning_extra, 3189        thold_data.notify_warning_extra = thold_template.notify_warning_extra,
2928        thold_data.notify_warning = thold_template.notify_warning, 3190        thold_data.notify_warning = thold_template.notify_warning,
2929        thold_data.notify_alert = thold_template.notify_alert, 3191        thold_data.notify_alert = thold_template.notify_alert,
2930        thold_data.data_type = thold_template.data_type, 3192        thold_data.data_type = thold_template.data_type,
2931        thold_data.cdef = thold_template.cdef, 3193        thold_data.cdef = thold_template.cdef,
2932        thold_data.percent_ds = thold_template.percent_ds, 3194        thold_data.percent_ds = thold_template.percent_ds,
2933        thold_data.expression = thold_template.expression, 3195        thold_data.expression = thold_template.expression,
2934        thold_data.exempt = thold_template.exempt, 3196        thold_data.exempt = thold_template.exempt,
2935        thold_data.data_template = thold_template.data_template_id, 3197        thold_data.data_template = thold_template.data_template_id,
2936        thold_data.restored_alert = thold_template.restored_alert  3198        thold_data.restored_alert = thold_template.restored_alert, 
  3199        thold_data.smstime_exempt_enable = thold_template.smstime_exempt_enable,
  3200        thold_data.smstime_exempt_start = thold_template.smstime_exempt_start,
  3201        thold_data.smstime_exempt_stop = thold_template.smstime_exempt_stop
2937        WHERE thold_data.template=$id AND thold_data.template_enabled='on' AND thold_template.id=$id"); 3202        WHERE thold_data.template=$id AND thold_data.template_enabled='on' AND thold_template.id=$id");
2938    $rows = db_fetch_assoc("SELECT id, template FROM thold_data WHERE thold_data.template=$id AND thold_data.template_enabled='on'"); 3203    $rows = db_fetch_assoc("SELECT id, template FROM thold_data WHERE thold_data.template=$id AND thold_data.template_enabled='on'");
2939  3204 
2940    foreach ($rows as $row) { 3205    foreach ($rows as $row) {
2941        db_execute('DELETE FROM plugin_thold_threshold_contact where thold_id = ' . $row['id']); 3206        db_execute('DELETE FROM plugin_thold_threshold_contact where thold_id = ' . $row['id']);
2942        db_execute('INSERT INTO plugin_thold_threshold_contact (thold_id, contact_id) SELECT ' . $row['id'] . ', contact_id FROM plugin_thold_template_contact WHERE template_id = ' . $row['template']); 3207        db_execute('INSERT INTO plugin_thold_threshold_contact (thold_id, contact_id) SELECT ' . $row['id'] . ', contact_id FROM plugin_thold_template_contact WHERE template_id = ' . $row['template']);
2943    } 3208    }
2944} 3209}
2945  3210 
2946function thold_cacti_log($string) { 3211function thold_cacti_log($string) {
2947    global $config; 3212    global $config;
2948    $environ = 'THOLD'; 3213    $environ = 'THOLD';
2949    /* fill in the current date for printing in the log */  3214    /* fill in the current date for printing in the log */ 
2950    $date = date("m/d/Y h:i:s A"); 3215    $date = date("m/d/Y h:i:s A");
2951  3216 
2952    /* determine how to log data */  3217    /* determine how to log data */ 
2953    $logdestination = read_config_option("log_destination"); 3218    $logdestination = read_config_option("log_destination");
2954    $logfile        = read_config_option("path_cactilog"); 3219    $logfile        = read_config_option("path_cactilog");
2955  3220 
2956    /* format the message */  3221    /* format the message */ 
2957    $message = "$date - " . $environ . ": " . $string . "\n"; 3222    $message = "$date - " . $environ . ": " . $string . "\n";
2958  3223 
2959    /* Log to Logfile */  3224    /* Log to Logfile */ 
2960    if ((($logdestination == 1) || ($logdestination == 2)) && (read_config_option("log_verbosity") != POLLER_VERBOSITY_NONE)) { 3225    if ((($logdestination == 1) || ($logdestination == 2)) && (read_config_option("log_verbosity") != POLLER_VERBOSITY_NONE)) {
2961        if ($logfile == "") { 3226        if ($logfile == "") {
2962            $logfile = $config["base_path"] . "/log/cacti.log"; 3227            $logfile = $config["base_path"] . "/log/cacti.log";
2963        } 3228        }
2964  3229 
2965        /* echo the data to the log (append) */  3230        /* echo the data to the log (append) */ 
2966        $fp = @fopen($logfile, "a"); 3231        $fp = @fopen($logfile, "a");
2967  3232 
2968        if ($fp) { 3233        if ($fp) {
2969            @fwrite($fp, $message); 3234            @fwrite($fp, $message);
2970            fclose($fp); 3235            fclose($fp);
2971        } 3236        }
2972    } 3237    }
2973  3238 
2974    /* Log to Syslog/Eventlog */  3239    /* Log to Syslog/Eventlog */ 
2975    /* Syslog is currently Unstable in Win32 */  3240    /* Syslog is currently Unstable in Win32 */ 
2976    if (($logdestination == 2) || ($logdestination == 3)) { 3241    if (($logdestination == 2) || ($logdestination == 3)) {
2977        $string = strip_tags($string); 3242        $string = strip_tags($string);
2978        $log_type = ""; 3243        $log_type = "";
2979        if (substr_count($string,"ERROR:")) 3244        if (substr_count($string,"ERROR:"))
2980            $log_type = "err"; 3245            $log_type = "err";
2981        else if (substr_count($string,"WARNING:")) 3246        else if (substr_count($string,"WARNING:"))
2982            $log_type = "warn"; 3247            $log_type = "warn";
2983        else if (substr_count($string,"STATS:")) 3248        else if (substr_count($string,"STATS:"))
2984            $log_type = "stat"; 3249            $log_type = "stat";
2985        else if (substr_count($string,"NOTICE:")) 3250        else if (substr_count($string,"NOTICE:"))
2986            $log_type = "note"; 3251            $log_type = "note";
2987  3252 
2988        if (strlen($log_type)) { 3253        if (strlen($log_type)) {
2989            define_syslog_variables(); 3254            define_syslog_variables();
2990  3255 
2991            if ($config["cacti_server_os"] == "win32") 3256            if ($config["cacti_server_os"] == "win32")
2992                openlog("Cacti", LOG_NDELAY | LOG_PID, LOG_USER); 3257                openlog("Cacti", LOG_NDELAY | LOG_PID, LOG_USER);
2993            else 3258            else
2994                openlog("Cacti", LOG_NDELAY | LOG_PID, LOG_SYSLOG); 3259                openlog("Cacti", LOG_NDELAY | LOG_PID, LOG_SYSLOG);
2995  3260 
2996            if (($log_type == "err") && (read_config_option("log_perror"))) { 3261            if (($log_type == "err") && (read_config_option("log_perror"))) {
2997                syslog(LOG_CRIT, $environ . ": " . $string); 3262                syslog(LOG_CRIT, $environ . ": " . $string);
2998            } 3263            }
2999  3264 
3000            if (($log_type == "warn") && (read_config_option("log_pwarn"))) { 3265            if (($log_type == "warn") && (read_config_option("log_pwarn"))) {
3001                syslog(LOG_WARNING, $environ . ": " . $string); 3266                syslog(LOG_WARNING, $environ . ": " . $string);
3002            } 3267            }
3003  3268 
3004            if ((($log_type == "stat") || ($log_type == "note")) && (read_config_option("log_pstats"))) { 3269            if ((($log_type == "stat") || ($log_type == "note")) && (read_config_option("log_pstats"))) {
3005                syslog(LOG_INFO, $environ . ": " . $string); 3270                syslog(LOG_INFO, $environ . ": " . $string);
3006            } 3271            }
3007  3272 
3008            closelog(); 3273            closelog();
3009        } 3274        }
3010    } 3275    }
3011} 3276}
3012  3277 
3013function thold_threshold_enable($id) { 3278function thold_threshold_enable($id) {
3014    db_execute("UPDATE thold_data SET thold_enabled='on', thold_fail_count=0, thold_warning_fail_count=0, bl_fail_count=0, thold_alert=0, bl_alert=0 WHERE id=$id"); 3279    db_execute("UPDATE thold_data SET thold_enabled='on', thold_fail_count=0, thold_warning_fail_count=0, bl_fail_count=0, thold_alert=0, bl_alert=0 WHERE id=$id");
3015} 3280}
3016  3281 
3017function thold_threshold_disable($id) { 3282function thold_threshold_disable($id) {
3018    db_execute("UPDATE thold_data SET thold_enabled='off', thold_fail_count=0, thold_warning_fail_count=0, bl_fail_count=0, thold_alert=0, bl_alert=0 WHERE id=$id"); 3283    db_execute("UPDATE thold_data SET thold_enabled='off', thold_fail_count=0, thold_warning_fail_count=0, bl_fail_count=0, thold_alert=0, bl_alert=0 WHERE id=$id");
3019} 3284}
3020  3285 
3021/** 3286/**
3022 * This function is stolen from NECTAR 3287 * This function is stolen from NECTAR
3023 * convert png images stream to jpeg using php-gd 3288 * convert png images stream to jpeg using php-gd
3024 * 3289 *
3025 * @param unknown_type $png_data    the png image as a stream 3290 * @param unknown_type $png_data    the png image as a stream
3026 * @return unknown                    the jpeg image as a stream 3291 * @return unknown                    the jpeg image as a stream
3027 */  3292 */ 
3028function png2jpeg ($png_data) { 3293function png2jpeg ($png_data) {
3029    global $config; 3294    global $config;
3030    $ImageData = ''; 3295    $ImageData = '';
3031    if ($png_data != "") { 3296    if ($png_data != "") {
3032        $fn = "/tmp/" . time() . '.png'; 3297        $fn = "/tmp/" . time() . '.png';
3033  3298 
3034        /* write rrdtool's png file to scratch dir */  3299        /* write rrdtool's png file to scratch dir */ 
3035        $f = fopen($fn, 'wb'); 3300        $f = fopen($fn, 'wb');
3036        fwrite($f, $png_data); 3301        fwrite($f, $png_data);
3037        fclose($f); 3302        fclose($f);
3038  3303 
3039        /* create php-gd image object from file */  3304        /* create php-gd image object from file */ 
3040        $im = imagecreatefrompng($fn); 3305        $im = imagecreatefrompng($fn);
3041        if (!$im) { 3306        if (!$im) {
3042            /* check for errors */  3307            /* check for errors */ 
3043            $im = ImageCreate (150, 30); 3308            $im = ImageCreate (150, 30);
3044            /* create an empty image */  3309            /* create an empty image */ 
3045            $bgc = ImageColorAllocate ($im, 255, 255, 255); 3310            $bgc = ImageColorAllocate ($im, 255, 255, 255);
3046            $tc  = ImageColorAllocate ($im, 0, 0, 0); 3311            $tc  = ImageColorAllocate ($im, 0, 0, 0);
3047            ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc); 3312            ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc);
3048            /* print error message */  3313            /* print error message */ 
3049            ImageString($im, 1, 5, 5, "Error while opening: $imgname", $tc); 3314            ImageString($im, 1, 5, 5, "Error while opening: $imgname", $tc);
3050        } 3315        }
3051  3316 
3052        ob_start(); // start a new output buffer to capture jpeg image stream 3317        ob_start(); // start a new output buffer to capture jpeg image stream
3053        imagejpeg($im);    // output to buffer 3318        imagejpeg($im);    // output to buffer
3054        $ImageData = ob_get_contents(); // fetch image from buffer 3319        $ImageData = ob_get_contents(); // fetch image from buffer
3055        $ImageDataLength = ob_get_length(); 3320        $ImageDataLength = ob_get_length();
3056        ob_end_clean(); // stop this output buffer 3321        ob_end_clean(); // stop this output buffer
3057        imagedestroy($im); //clean up 3322        imagedestroy($im); //clean up
3058  3323 
3059        unlink($fn); // delete scratch file 3324        unlink($fn); // delete scratch file
3060    } 3325    }
3061    return $ImageData; 3326    return $ImageData;
3062} 3327}
3063  3328 
3064function get_thold_notification_emails($id) { 3329function get_thold_notification_emails($id) {
3065    if (!empty($id)) { 3330    if (!empty($id)) {
3066        return trim(db_fetch_cell('SELECT emails FROM plugin_notification_lists WHERE id=' . $id)); 3331        return trim(db_fetch_cell('SELECT emails FROM plugin_notification_lists WHERE id=' . $id));
3067    } else { 3332    } else {
3068        return ''; 3333        return '';
3069    } 3334    }
3070} 3335}
3071  3336 
3072/* get_hash_thold_template - returns the current unique hash for a thold_template 3337/* get_hash_thold_template - returns the current unique hash for a thold_template
3073   @arg $id - (int) the ID of the thold template to return a hash for 3338   @arg $id - (int) the ID of the thold template to return a hash for
3074   @returns - a 128-bit, hexadecimal hash */  3339   @returns - a 128-bit, hexadecimal hash */ 
3075function get_hash_thold_template($id) { 3340function get_hash_thold_template($id) {
3076    $hash = db_fetch_cell("SELECT hash FROM thold_template WHERE id=$id"); 3341    $hash = db_fetch_cell("SELECT hash FROM thold_template WHERE id=$id");
3077  3342 
3078    if (preg_match("/[a-fA-F0-9]{32}/", $hash)) { 3343    if (preg_match("/[a-fA-F0-9]{32}/", $hash)) {
3079        return $hash; 3344        return $hash;
3080    } else { 3345    } else {
3081        return generate_hash(); 3346        return generate_hash();
3082    } 3347    }
3083} 3348}
3084  3349 
3085function ia2xml($array) { 3350function ia2xml($array) {
3086    $xml = ""; 3351    $xml = "";
3087    if (sizeof($array)) { 3352    if (sizeof($array)) {
3088    foreach ($array as $key=>$value) { 3353    foreach ($array as $key=>$value) {
3089        if (is_array($value)) { 3354        if (is_array($value)) {
3090            $xml .= "\t<$key>" . ia2xml($value) . "</$key>\n"; 3355            $xml .= "\t<$key>" . ia2xml($value) . "</$key>\n";
3091        } else { 3356        } else {
3092            $xml .= "\t<$key>" . htmlspecialchars($value) . "</$key>\n"; 3357            $xml .= "\t<$key>" . htmlspecialchars($value) . "</$key>\n";
3093        } 3358        }
3094    } 3359    }
3095    } 3360    }
3096    return $xml; 3361    return $xml;
3097} 3362}
3098  3363 
3099function array2xml($array, $tag = 'template') { 3364function array2xml($array, $tag = 'template') {
3100    static $index = 1; 3365    static $index = 1;
3101  3366 
3102    $xml = "<$tag$index>\n" . ia2xml($array) . "</$tag$index>\n"; 3367    $xml = "<$tag$index>\n" . ia2xml($array) . "</$tag$index>\n";
3103  3368 
3104    $index++; 3369    $index++;
3105  3370 
3106    return $xml; 3371    return $xml;
3107} 3372}
3108  3373