Passed
Push — master ( 9c2cb2...01dd4d )
by Patrick
01:54
created
library/Trapdirector/TrapsProcess/Rule.php 3 patches
Indentation   +289 added lines, -289 removed lines patch added patch discarded remove patch
@@ -7,331 +7,331 @@
 block discarded – undo
7 7
 class Rule
8 8
 {
9 9
     
10
-    protected $logging; //< logging class
10
+	protected $logging; //< logging class
11 11
     
12
-    /**
13
-     * Setup Rule Class
14
-     * @param Logging $logClass : where to log
15
-     */
16
-    function __construct($logClass)
17
-    {
18
-        $this->logging=$logClass;
12
+	/**
13
+	 * Setup Rule Class
14
+	 * @param Logging $logClass : where to log
15
+	 */
16
+	function __construct($logClass)
17
+	{
18
+		$this->logging=$logClass;
19 19
 
20
-    }
20
+	}
21 21
 
22 22
 /**
23 23
  * Get full number 
24 24
  * @return array<number,string>
25 25
  */
26
-    private function get_number($rule,&$item)
27
-    {
28
-        $item2=$item+1;
29
-        while (
30
-            ($item2!=strlen($rule)) 
31
-            && (preg_match('/[\-0-9\.]/',$rule[$item2]))) 
32
-        { 
33
-            $item2++ ;
34
-        }
35
-        $val=substr($rule,$item,$item2-$item);
36
-        $item=$item2;
37
-        //echo "number ".$val."\n";
26
+	private function get_number($rule,&$item)
27
+	{
28
+		$item2=$item+1;
29
+		while (
30
+			($item2!=strlen($rule)) 
31
+			&& (preg_match('/[\-0-9\.]/',$rule[$item2]))) 
32
+		{ 
33
+			$item2++ ;
34
+		}
35
+		$val=substr($rule,$item,$item2-$item);
36
+		$item=$item2;
37
+		//echo "number ".$val."\n";
38 38
         
39
-        return array(0,$val);
40
-    }
39
+		return array(0,$val);
40
+	}
41 41
 
42
-    private function get_string($rule,&$item)
43
-    {
44
-        $item++;
45
-        $item2=$this->eval_getNext($rule,$item,'"');
46
-        $val=substr($rule,$item,$item2-$item-1);
47
-        $item=$item2;
48
-        //echo "string : ".$val."\n";
49
-        return array(1,$val);
42
+	private function get_string($rule,&$item)
43
+	{
44
+		$item++;
45
+		$item2=$this->eval_getNext($rule,$item,'"');
46
+		$val=substr($rule,$item,$item2-$item-1);
47
+		$item=$item2;
48
+		//echo "string : ".$val."\n";
49
+		return array(1,$val);
50 50
         
51
-    }
51
+	}
52 52
     
53
-    private function get_group($rule,&$item)
54
-    {
55
-        $item++;
56
-        $start=$item;
57
-        $parenthesis_count=0;
58
-        while (($item < strlen($rule)) // Not end of string AND
59
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
60
-        {
61
-            if ($rule[$item] == '"' )
62
-            { // pass through string
63
-                $item++;
64
-                $item=$this->eval_getNext($rule,$item,'"');
65
-            }
66
-            else{
67
-                if ($rule[$item] == '(')
68
-                {
69
-                    $parenthesis_count++;
70
-                }
71
-                if ($rule[$item] == ')')
72
-                {
73
-                    $parenthesis_count--;
74
-                }
75
-                $item++;
76
-            }
77
-        }
53
+	private function get_group($rule,&$item)
54
+	{
55
+		$item++;
56
+		$start=$item;
57
+		$parenthesis_count=0;
58
+		while (($item < strlen($rule)) // Not end of string AND
59
+			&& ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
60
+		{
61
+			if ($rule[$item] == '"' )
62
+			{ // pass through string
63
+				$item++;
64
+				$item=$this->eval_getNext($rule,$item,'"');
65
+			}
66
+			else{
67
+				if ($rule[$item] == '(')
68
+				{
69
+					$parenthesis_count++;
70
+				}
71
+				if ($rule[$item] == ')')
72
+				{
73
+					$parenthesis_count--;
74
+				}
75
+				$item++;
76
+			}
77
+		}
78 78
         
79
-        if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
80
-        $val=substr($rule,$start,$item-$start);
81
-        $item++;
82
-        $start=0;
83
-        //echo "group : ".$val."\n";
84
-        // returns evaluation of group as type 2 (boolean)
85
-        return array(2,$this->evaluation($val,$start));
86
-    }
79
+		if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
80
+		$val=substr($rule,$start,$item-$start);
81
+		$item++;
82
+		$start=0;
83
+		//echo "group : ".$val."\n";
84
+		// returns evaluation of group as type 2 (boolean)
85
+		return array(2,$this->evaluation($val,$start));
86
+	}
87 87
     
88
-    protected function eval_getElement($rule,&$item)
89
-    {
90
-        if ($item >= strlen($rule))
91
-        {
92
-            throw new Exception("Early end of string ".$rule ." at " .$item );
93
-        }
94
-        while ($rule[$item]==' ') $item++;
95
-        if (preg_match('/[\-0-9\.]/',$rule[$item]))
96
-        { // number
97
-            return $this->get_number($rule, $item);
98
-        }
99
-        if ($rule[$item] == '"')
100
-        { // string
101
-            return $this->get_string($rule, $item);
102
-        }
88
+	protected function eval_getElement($rule,&$item)
89
+	{
90
+		if ($item >= strlen($rule))
91
+		{
92
+			throw new Exception("Early end of string ".$rule ." at " .$item );
93
+		}
94
+		while ($rule[$item]==' ') $item++;
95
+		if (preg_match('/[\-0-9\.]/',$rule[$item]))
96
+		{ // number
97
+			return $this->get_number($rule, $item);
98
+		}
99
+		if ($rule[$item] == '"')
100
+		{ // string
101
+			return $this->get_string($rule, $item);
102
+		}
103 103
         
104
-        if ($rule[$item] == '(')
105
-        { // grouping
106
-            return $this->get_group($rule, $item);
107
-        }
108
-        throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
104
+		if ($rule[$item] == '(')
105
+		{ // grouping
106
+			return $this->get_group($rule, $item);
107
+		}
108
+		throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
109 109
         
110
-    }
110
+	}
111 111
     
112
-    protected function eval_getNext($rule,$item,$tok)
113
-    {
114
-        while (
115
-            ($rule[$item] != $tok ) 
116
-            && ($item < strlen($rule))) 
117
-        { 
118
-            $item++;
119
-        }
120
-        if ($item==strlen($rule)) {
121
-            throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
122
-        }
123
-        return $item+1;
124
-    }
112
+	protected function eval_getNext($rule,$item,$tok)
113
+	{
114
+		while (
115
+			($rule[$item] != $tok ) 
116
+			&& ($item < strlen($rule))) 
117
+		{ 
118
+			$item++;
119
+		}
120
+		if ($item==strlen($rule)) {
121
+			throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
122
+		}
123
+		return $item+1;
124
+	}
125 125
     
126
-    protected function eval_getOper($rule,&$item)
127
-    {
128
-        while ($rule[$item]==' ') $item++;
129
-        switch ($rule[$item])
130
-        {
131
-            case '<':
132
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
133
-                $item++; return array(0,"<");
134
-            case '>':
135
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
136
-                $item++; return array(0,">");
137
-            case '=':
138
-                $item++; return array(0,"=");
139
-            case '!':
140
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
141
-                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
142
-            case '~':
143
-                $item++; return array(0,"~");
144
-            case '|':
145
-                $item++; return array(1,"|");
146
-            case '&':
147
-                $item++; return array(1,"&");
148
-            default	:
149
-                throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
150
-        }
151
-    }
126
+	protected function eval_getOper($rule,&$item)
127
+	{
128
+		while ($rule[$item]==' ') $item++;
129
+		switch ($rule[$item])
130
+		{
131
+			case '<':
132
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
133
+				$item++; return array(0,"<");
134
+			case '>':
135
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
136
+				$item++; return array(0,">");
137
+			case '=':
138
+				$item++; return array(0,"=");
139
+			case '!':
140
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
141
+				throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
142
+			case '~':
143
+				$item++; return array(0,"~");
144
+			case '|':
145
+				$item++; return array(1,"|");
146
+			case '&':
147
+				$item++; return array(1,"&");
148
+			default	:
149
+				throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
150
+		}
151
+	}
152 152
     
153
-    private function check_negate_first($rule,&$item)
154
-    {
155
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
156
-        {
157
-            $item++;
158
-            return true;
159
-        }
160
-        else
161
-        {
162
-            return false;
163
-        }
164
-    }
153
+	private function check_negate_first($rule,&$item)
154
+	{
155
+		if ( $rule[$item] == '!') // If '!' found, negate next expression.
156
+		{
157
+			$item++;
158
+			return true;
159
+		}
160
+		else
161
+		{
162
+			return false;
163
+		}
164
+	}
165 165
 
166
-    private function do_compare($val1,$val2,$comp,$negate)
167
-    {
168
-        switch ($comp){
169
-            case '<':	$retVal= ($val1 < $val2); break;
170
-            case '<=':	$retVal= ($val1 <= $val2); break;
171
-            case '>':	$retVal= ($val1 > $val2); break;
172
-            case '>=':	$retVal= ($val1 >= $val2); break;
173
-            case '=':	$retVal= ($val1 == $val2); break;
174
-            case '!=':	$retVal= ($val1 != $val2); break;
175
-            case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
176
-            case '|':	$retVal= ($val1 || $val2); break;
177
-            case '&':	$retVal= ($val1 && $val2); break;
178
-            default:  throw new Exception("Error in expression - unknown comp : ".$comp);
179
-        }
180
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
166
+	private function do_compare($val1,$val2,$comp,$negate)
167
+	{
168
+		switch ($comp){
169
+			case '<':	$retVal= ($val1 < $val2); break;
170
+			case '<=':	$retVal= ($val1 <= $val2); break;
171
+			case '>':	$retVal= ($val1 > $val2); break;
172
+			case '>=':	$retVal= ($val1 >= $val2); break;
173
+			case '=':	$retVal= ($val1 == $val2); break;
174
+			case '!=':	$retVal= ($val1 != $val2); break;
175
+			case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
176
+			case '|':	$retVal= ($val1 || $val2); break;
177
+			case '&':	$retVal= ($val1 && $val2); break;
178
+			default:  throw new Exception("Error in expression - unknown comp : ".$comp);
179
+		}
180
+		if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
181 181
         
182
-        return $retVal;
183
-    }
182
+		return $retVal;
183
+	}
184 184
     
185
-    /** Evaluation : makes token and evaluate.
186
-     *	Public function for expressions testing
187
-     *	accepts : < > = <= >= !=  (typec = 0)
188
-     *	operators : & | (typec=1)
189
-     *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
190
-     *   comparison int vs strings will return null (error)
191
-     *	return : bool or null on error
192
-     */
193
-    public function evaluation($rule,&$item)
194
-    {
195
-        //echo "Evaluation of ".substr($rule,$item)."\n";
196
-        $negate=$this->check_negate_first($rule, $item);
197
-        // First element : number, string or ()
198
-        list($type1,$val1) = $this->eval_getElement($rule,$item);
199
-        //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
185
+	/** Evaluation : makes token and evaluate.
186
+	 *	Public function for expressions testing
187
+	 *	accepts : < > = <= >= !=  (typec = 0)
188
+	 *	operators : & | (typec=1)
189
+	 *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
190
+	 *   comparison int vs strings will return null (error)
191
+	 *	return : bool or null on error
192
+	 */
193
+	public function evaluation($rule,&$item)
194
+	{
195
+		//echo "Evaluation of ".substr($rule,$item)."\n";
196
+		$negate=$this->check_negate_first($rule, $item);
197
+		// First element : number, string or ()
198
+		list($type1,$val1) = $this->eval_getElement($rule,$item);
199
+		//echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
200 200
         
201
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
202
-        {
203
-            if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
204
-            if ($negate === true) $val1= ! $val1;
205
-            return $val1;
206
-        }
201
+		if ($item==strlen($rule)) // If only element, return value, but only boolean
202
+		{
203
+			if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
204
+			if ($negate === true) $val1= ! $val1;
205
+			return $val1;
206
+		}
207 207
         
208
-        // Second element : operator
209
-        list($typec,$comp) = $this->eval_getOper($rule,$item);
210
-        //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
208
+		// Second element : operator
209
+		list($typec,$comp) = $this->eval_getOper($rule,$item);
210
+		//echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
211 211
         
212
-        // Third element : number, string or ()
213
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
214
-        {
215
-            $item++;
216
-            if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
217
-            $val2= ! $this->evaluation($rule,$item);
218
-            $type2=2; // result is a boolean
219
-        }
220
-        else
221
-        {
222
-            list($type2,$val2) = $this->eval_getElement($rule,$item);
223
-        }
224
-        //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
212
+		// Third element : number, string or ()
213
+		if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
214
+		{
215
+			$item++;
216
+			if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
217
+			$val2= ! $this->evaluation($rule,$item);
218
+			$type2=2; // result is a boolean
219
+		}
220
+		else
221
+		{
222
+			list($type2,$val2) = $this->eval_getElement($rule,$item);
223
+		}
224
+		//echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
225 225
         
226
-        if ($type1!=$type2)  // cannot compare different types
227
-        {
228
-            throw new Exception("Cannot compare string & number : ".$rule);
229
-        }
230
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
231
-        {
232
-            throw new Exception("Cannot use boolean operators with string & number : ".$rule);
233
-        }
226
+		if ($type1!=$type2)  // cannot compare different types
227
+		{
228
+			throw new Exception("Cannot compare string & number : ".$rule);
229
+		}
230
+		if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
231
+		{
232
+			throw new Exception("Cannot use boolean operators with string & number : ".$rule);
233
+		}
234 234
         
235
-        $retVal = $this->do_compare($val1, $val2, $comp, $negate);
235
+		$retVal = $this->do_compare($val1, $val2, $comp, $negate);
236 236
         
237
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
238
-        // check for logical operator :
239
-        switch ($rule[$item])
240
-        {
241
-            case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
242
-            case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
237
+		if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
238
+		// check for logical operator :
239
+		switch ($rule[$item])
240
+		{
241
+			case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
242
+			case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
243 243
             
244
-            default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
245
-        }
246
-    }
244
+			default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
245
+		}
246
+	}
247 247
     
248
-    // Remove all whitespaces (when not quoted)
249
-    public function eval_cleanup($rule)
250
-    {
251
-        $item=0;
252
-        $rule2='';
253
-        while ($item < strlen($rule))
254
-        {
255
-            if ($rule[$item]==' ') { $item++; continue; }
256
-            if ($rule[$item]=='"')
257
-            {
258
-                $rule2.=$rule[$item];
259
-                $item++;
260
-                while (($item < strlen($rule)) && ($rule[$item]!='"') )
261
-                {
262
-                    $rule2.=$rule[$item];
263
-                    $item++;
264
-                }
265
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
266
-                $rule2.=$rule[$item];
267
-                $item++;
268
-                continue;
269
-            }
248
+	// Remove all whitespaces (when not quoted)
249
+	public function eval_cleanup($rule)
250
+	{
251
+		$item=0;
252
+		$rule2='';
253
+		while ($item < strlen($rule))
254
+		{
255
+			if ($rule[$item]==' ') { $item++; continue; }
256
+			if ($rule[$item]=='"')
257
+			{
258
+				$rule2.=$rule[$item];
259
+				$item++;
260
+				while (($item < strlen($rule)) && ($rule[$item]!='"') )
261
+				{
262
+					$rule2.=$rule[$item];
263
+					$item++;
264
+				}
265
+				if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
266
+				$rule2.=$rule[$item];
267
+				$item++;
268
+				continue;
269
+			}
270 270
             
271
-            $rule2.=$rule[$item];
272
-            $item++;
273
-        }
271
+			$rule2.=$rule[$item];
272
+			$item++;
273
+		}
274 274
         
275
-        return $rule2;
276
-    }
275
+		return $rule2;
276
+	}
277 277
     
278
-    /** Evaluation rule (uses eval_* functions recursively)
279
-     *	@param string $rule : rule ( _OID(.1.3.6.1.4.1.8072.2.3.2.1)=_OID(.1.3.6.1.2.1.1.3.0) )
280
-     *  @param array $oidList : OIDs values to sustitute.
281
-     *	@return bool : true : rule match, false : rule don't match , throw exception on error.
282
-     */
278
+	/** Evaluation rule (uses eval_* functions recursively)
279
+	 *	@param string $rule : rule ( _OID(.1.3.6.1.4.1.8072.2.3.2.1)=_OID(.1.3.6.1.2.1.1.3.0) )
280
+	 *  @param array $oidList : OIDs values to sustitute.
281
+	 *	@return bool : true : rule match, false : rule don't match , throw exception on error.
282
+	 */
283 283
     
284
-    public function eval_rule($rule,$oidList)
285
-    {
286
-        if ($rule==null || $rule == '') // Empty rule is always true
287
-        {
288
-            return true;
289
-        }
290
-        $matches=array();
291
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
292
-        {
293
-            $oid=$matches[1];
294
-            $found=0;
295
-            // ** replaced by .*
296
-            $oidR=preg_replace('/\*\*/', '.*', $oid);
297
-            // * replaced by [0-9]+ 
298
-            $oidR=preg_replace('/\*/', '[0-9]+', $oidR);
284
+	public function eval_rule($rule,$oidList)
285
+	{
286
+		if ($rule==null || $rule == '') // Empty rule is always true
287
+		{
288
+			return true;
289
+		}
290
+		$matches=array();
291
+		while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
292
+		{
293
+			$oid=$matches[1];
294
+			$found=0;
295
+			// ** replaced by .*
296
+			$oidR=preg_replace('/\*\*/', '.*', $oid);
297
+			// * replaced by [0-9]+ 
298
+			$oidR=preg_replace('/\*/', '[0-9]+', $oidR);
299 299
             
300
-            // replace * with \* in oid for preg_replace
301
-            $oid=preg_replace('/\*/', '\*', $oid);
300
+			// replace * with \* in oid for preg_replace
301
+			$oid=preg_replace('/\*/', '\*', $oid);
302 302
             
303
-            $this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
303
+			$this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
304 304
             
305
-            foreach($oidList as $val)
306
-            {
307
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
308
-                {
309
-                    if (!preg_match('/^-?[0-9]*\.?[0-9]+$/',$val->value))
310
-                    { // If not a number, change " to ' and put " around it
311
-                        $val->value=preg_replace('/"/',"'",$val->value);
312
-                        $val->value='"'.$val->value.'"';
313
-                    }
314
-                    $rep=0;
315
-                    $rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
316
-                    if ($rep==0)
317
-                    {
318
-                        $this->logging->log("Error in rule_eval",WARN,'');
319
-                        return false;
320
-                    }
321
-                    $found=1;
322
-                    break;
323
-                }
324
-            }
325
-            if ($found==0)
326
-            {	// OID not found : throw error
327
-                throw new Exception('OID '.$oid.' not found in trap');
328
-            }
329
-        }
330
-        $item=0;
331
-        $rule=$this->eval_cleanup($rule);
332
-        $this->logging->log('Rule after clenup: '.$rule,INFO );
305
+			foreach($oidList as $val)
306
+			{
307
+				if (preg_match("/^$oidR$/",$val->oid) == 1)
308
+				{
309
+					if (!preg_match('/^-?[0-9]*\.?[0-9]+$/',$val->value))
310
+					{ // If not a number, change " to ' and put " around it
311
+						$val->value=preg_replace('/"/',"'",$val->value);
312
+						$val->value='"'.$val->value.'"';
313
+					}
314
+					$rep=0;
315
+					$rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
316
+					if ($rep==0)
317
+					{
318
+						$this->logging->log("Error in rule_eval",WARN,'');
319
+						return false;
320
+					}
321
+					$found=1;
322
+					break;
323
+				}
324
+			}
325
+			if ($found==0)
326
+			{	// OID not found : throw error
327
+				throw new Exception('OID '.$oid.' not found in trap');
328
+			}
329
+		}
330
+		$item=0;
331
+		$rule=$this->eval_cleanup($rule);
332
+		$this->logging->log('Rule after clenup: '.$rule,INFO );
333 333
         
334
-        return  $this->evaluation($rule,$item);
335
-    }
334
+		return  $this->evaluation($rule,$item);
335
+	}
336 336
     
337 337
 }
338 338
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -23,47 +23,47 @@  discard block
 block discarded – undo
23 23
  * Get full number 
24 24
  * @return array<number,string>
25 25
  */
26
-    private function get_number($rule,&$item)
26
+    private function get_number($rule, &$item)
27 27
     {
28
-        $item2=$item+1;
28
+        $item2=$item + 1;
29 29
         while (
30
-            ($item2!=strlen($rule)) 
31
-            && (preg_match('/[\-0-9\.]/',$rule[$item2]))) 
30
+            ($item2 != strlen($rule)) 
31
+            && (preg_match('/[\-0-9\.]/', $rule[$item2]))) 
32 32
         { 
33
-            $item2++ ;
33
+            $item2++;
34 34
         }
35
-        $val=substr($rule,$item,$item2-$item);
35
+        $val=substr($rule, $item, $item2 - $item);
36 36
         $item=$item2;
37 37
         //echo "number ".$val."\n";
38 38
         
39
-        return array(0,$val);
39
+        return array(0, $val);
40 40
     }
41 41
 
42
-    private function get_string($rule,&$item)
42
+    private function get_string($rule, &$item)
43 43
     {
44 44
         $item++;
45
-        $item2=$this->eval_getNext($rule,$item,'"');
46
-        $val=substr($rule,$item,$item2-$item-1);
45
+        $item2=$this->eval_getNext($rule, $item, '"');
46
+        $val=substr($rule, $item, $item2 - $item - 1);
47 47
         $item=$item2;
48 48
         //echo "string : ".$val."\n";
49
-        return array(1,$val);
49
+        return array(1, $val);
50 50
         
51 51
     }
52 52
     
53
-    private function get_group($rule,&$item)
53
+    private function get_group($rule, &$item)
54 54
     {
55 55
         $item++;
56 56
         $start=$item;
57 57
         $parenthesis_count=0;
58 58
         while (($item < strlen($rule)) // Not end of string AND
59
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
59
+            && (($rule[$item] != ')') || $parenthesis_count > 0)) // Closing ')' or embeded ()
60 60
         {
61
-            if ($rule[$item] == '"' )
61
+            if ($rule[$item] == '"')
62 62
             { // pass through string
63 63
                 $item++;
64
-                $item=$this->eval_getNext($rule,$item,'"');
64
+                $item=$this->eval_getNext($rule, $item, '"');
65 65
             }
66
-            else{
66
+            else {
67 67
                 if ($rule[$item] == '(')
68 68
                 {
69 69
                     $parenthesis_count++;
@@ -76,23 +76,23 @@  discard block
 block discarded – undo
76 76
             }
77 77
         }
78 78
         
79
-        if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
80
-        $val=substr($rule,$start,$item-$start);
79
+        if ($item == strlen($rule)) {throw new Exception("no closing () in ".$rule." at ".$item); }
80
+        $val=substr($rule, $start, $item - $start);
81 81
         $item++;
82 82
         $start=0;
83 83
         //echo "group : ".$val."\n";
84 84
         // returns evaluation of group as type 2 (boolean)
85
-        return array(2,$this->evaluation($val,$start));
85
+        return array(2, $this->evaluation($val, $start));
86 86
     }
87 87
     
88
-    protected function eval_getElement($rule,&$item)
88
+    protected function eval_getElement($rule, &$item)
89 89
     {
90 90
         if ($item >= strlen($rule))
91 91
         {
92
-            throw new Exception("Early end of string ".$rule ." at " .$item );
92
+            throw new Exception("Early end of string ".$rule." at ".$item);
93 93
         }
94
-        while ($rule[$item]==' ') $item++;
95
-        if (preg_match('/[\-0-9\.]/',$rule[$item]))
94
+        while ($rule[$item] == ' ') $item++;
95
+        if (preg_match('/[\-0-9\.]/', $rule[$item]))
96 96
         { // number
97 97
             return $this->get_number($rule, $item);
98 98
         }
@@ -105,54 +105,54 @@  discard block
 block discarded – undo
105 105
         { // grouping
106 106
             return $this->get_group($rule, $item);
107 107
         }
108
-        throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
108
+        throw new Exception("number/string not found in ".$rule." at ".$item.' : '.$rule[$item]);
109 109
         
110 110
     }
111 111
     
112
-    protected function eval_getNext($rule,$item,$tok)
112
+    protected function eval_getNext($rule, $item, $tok)
113 113
     {
114 114
         while (
115
-            ($rule[$item] != $tok ) 
115
+            ($rule[$item] != $tok) 
116 116
             && ($item < strlen($rule))) 
117 117
         { 
118 118
             $item++;
119 119
         }
120
-        if ($item==strlen($rule)) {
121
-            throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
120
+        if ($item == strlen($rule)) {
121
+            throw new Exception("closing '".$tok."' not found in ".$rule." at ".$item);
122 122
         }
123
-        return $item+1;
123
+        return $item + 1;
124 124
     }
125 125
     
126
-    protected function eval_getOper($rule,&$item)
126
+    protected function eval_getOper($rule, &$item)
127 127
     {
128
-        while ($rule[$item]==' ') $item++;
128
+        while ($rule[$item] == ' ') $item++;
129 129
         switch ($rule[$item])
130 130
         {
131 131
             case '<':
132
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
133
-                $item++; return array(0,"<");
132
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, "<="); }
133
+                $item++; return array(0, "<");
134 134
             case '>':
135
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
136
-                $item++; return array(0,">");
135
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, ">="); }
136
+                $item++; return array(0, ">");
137 137
             case '=':
138
-                $item++; return array(0,"=");
138
+                $item++; return array(0, "=");
139 139
             case '!':
140
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
141
-                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
140
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, "!="); }
141
+                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule." at ".$item);
142 142
             case '~':
143
-                $item++; return array(0,"~");
143
+                $item++; return array(0, "~");
144 144
             case '|':
145
-                $item++; return array(1,"|");
145
+                $item++; return array(1, "|");
146 146
             case '&':
147
-                $item++; return array(1,"&");
147
+                $item++; return array(1, "&");
148 148
             default	:
149
-                throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
149
+                throw new Exception("Erreur in expr - operator not found in ".$rule." at ".$item);
150 150
         }
151 151
     }
152 152
     
153
-    private function check_negate_first($rule,&$item)
153
+    private function check_negate_first($rule, &$item)
154 154
     {
155
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
155
+        if ($rule[$item] == '!') // If '!' found, negate next expression.
156 156
         {
157 157
             $item++;
158 158
             return true;
@@ -163,21 +163,21 @@  discard block
 block discarded – undo
163 163
         }
164 164
     }
165 165
 
166
-    private function do_compare($val1,$val2,$comp,$negate)
166
+    private function do_compare($val1, $val2, $comp, $negate)
167 167
     {
168
-        switch ($comp){
169
-            case '<':	$retVal= ($val1 < $val2); break;
170
-            case '<=':	$retVal= ($val1 <= $val2); break;
171
-            case '>':	$retVal= ($val1 > $val2); break;
172
-            case '>=':	$retVal= ($val1 >= $val2); break;
173
-            case '=':	$retVal= ($val1 == $val2); break;
174
-            case '!=':	$retVal= ($val1 != $val2); break;
175
-            case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
176
-            case '|':	$retVal= ($val1 || $val2); break;
177
-            case '&':	$retVal= ($val1 && $val2); break;
168
+        switch ($comp) {
169
+            case '<':	$retVal=($val1 < $val2); break;
170
+            case '<=':	$retVal=($val1 <= $val2); break;
171
+            case '>':	$retVal=($val1 > $val2); break;
172
+            case '>=':	$retVal=($val1 >= $val2); break;
173
+            case '=':	$retVal=($val1 == $val2); break;
174
+            case '!=':	$retVal=($val1 != $val2); break;
175
+            case '~':	$retVal=(preg_match('/'.preg_replace('/"/', '', $val2).'/', $val1)); break;
176
+            case '|':	$retVal=($val1 || $val2); break;
177
+            case '&':	$retVal=($val1 && $val2); break;
178 178
             default:  throw new Exception("Error in expression - unknown comp : ".$comp);
179 179
         }
180
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
180
+        if ($negate === true) $retVal=!$retVal; // Inverse result if negate before expression
181 181
         
182 182
         return $retVal;
183 183
     }
@@ -190,56 +190,56 @@  discard block
 block discarded – undo
190 190
      *   comparison int vs strings will return null (error)
191 191
      *	return : bool or null on error
192 192
      */
193
-    public function evaluation($rule,&$item)
193
+    public function evaluation($rule, &$item)
194 194
     {
195 195
         //echo "Evaluation of ".substr($rule,$item)."\n";
196 196
         $negate=$this->check_negate_first($rule, $item);
197 197
         // First element : number, string or ()
198
-        list($type1,$val1) = $this->eval_getElement($rule,$item);
198
+        list($type1, $val1)=$this->eval_getElement($rule, $item);
199 199
         //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
200 200
         
201
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
201
+        if ($item == strlen($rule)) // If only element, return value, but only boolean
202 202
         {
203 203
             if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
204
-            if ($negate === true) $val1= ! $val1;
204
+            if ($negate === true) $val1=!$val1;
205 205
             return $val1;
206 206
         }
207 207
         
208 208
         // Second element : operator
209
-        list($typec,$comp) = $this->eval_getOper($rule,$item);
209
+        list($typec, $comp)=$this->eval_getOper($rule, $item);
210 210
         //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
211 211
         
212 212
         // Third element : number, string or ()
213
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
213
+        if ($rule[$item] == '!') // starts with a ! so evaluate whats next
214 214
         {
215 215
             $item++;
216 216
             if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
217
-            $val2= ! $this->evaluation($rule,$item);
217
+            $val2=!$this->evaluation($rule, $item);
218 218
             $type2=2; // result is a boolean
219 219
         }
220 220
         else
221 221
         {
222
-            list($type2,$val2) = $this->eval_getElement($rule,$item);
222
+            list($type2, $val2)=$this->eval_getElement($rule, $item);
223 223
         }
224 224
         //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
225 225
         
226
-        if ($type1!=$type2)  // cannot compare different types
226
+        if ($type1 != $type2)  // cannot compare different types
227 227
         {
228 228
             throw new Exception("Cannot compare string & number : ".$rule);
229 229
         }
230
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
230
+        if ($typec == 1 && $type1 != 2) // cannot use & or | with string/number
231 231
         {
232 232
             throw new Exception("Cannot use boolean operators with string & number : ".$rule);
233 233
         }
234 234
         
235
-        $retVal = $this->do_compare($val1, $val2, $comp, $negate);
235
+        $retVal=$this->do_compare($val1, $val2, $comp, $negate);
236 236
         
237
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
237
+        if ($item == strlen($rule)) return $retVal; // End of string : return evaluation
238 238
         // check for logical operator :
239 239
         switch ($rule[$item])
240 240
         {
241
-            case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
242
-            case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
241
+            case '|':	$item++; return ($retVal || $this->evaluation($rule, $item));
242
+            case '&':	$item++; return ($retVal && $this->evaluation($rule, $item));
243 243
             
244 244
             default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
245 245
         }
@@ -252,17 +252,17 @@  discard block
 block discarded – undo
252 252
         $rule2='';
253 253
         while ($item < strlen($rule))
254 254
         {
255
-            if ($rule[$item]==' ') { $item++; continue; }
256
-            if ($rule[$item]=='"')
255
+            if ($rule[$item] == ' ') { $item++; continue; }
256
+            if ($rule[$item] == '"')
257 257
             {
258 258
                 $rule2.=$rule[$item];
259 259
                 $item++;
260
-                while (($item < strlen($rule)) && ($rule[$item]!='"') )
260
+                while (($item < strlen($rule)) && ($rule[$item] != '"'))
261 261
                 {
262 262
                     $rule2.=$rule[$item];
263 263
                     $item++;
264 264
                 }
265
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
265
+                if ($item == strlen($rule)) throw new Exception("closing '\"' not found in ".$rule." at ".$item);
266 266
                 $rule2.=$rule[$item];
267 267
                 $item++;
268 268
                 continue;
@@ -281,14 +281,14 @@  discard block
 block discarded – undo
281 281
      *	@return bool : true : rule match, false : rule don't match , throw exception on error.
282 282
      */
283 283
     
284
-    public function eval_rule($rule,$oidList)
284
+    public function eval_rule($rule, $oidList)
285 285
     {
286
-        if ($rule==null || $rule == '') // Empty rule is always true
286
+        if ($rule == null || $rule == '') // Empty rule is always true
287 287
         {
288 288
             return true;
289 289
         }
290 290
         $matches=array();
291
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
291
+        while (preg_match('/_OID\(([0-9\.\*]+)\)/', $rule, $matches) == 1)
292 292
         {
293 293
             $oid=$matches[1];
294 294
             $found=0;
@@ -300,38 +300,38 @@  discard block
 block discarded – undo
300 300
             // replace * with \* in oid for preg_replace
301 301
             $oid=preg_replace('/\*/', '\*', $oid);
302 302
             
303
-            $this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
303
+            $this->logging->log('OID in rule : '.$oid.' / '.$oidR, DEBUG);
304 304
             
305
-            foreach($oidList as $val)
305
+            foreach ($oidList as $val)
306 306
             {
307
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
307
+                if (preg_match("/^$oidR$/", $val->oid) == 1)
308 308
                 {
309
-                    if (!preg_match('/^-?[0-9]*\.?[0-9]+$/',$val->value))
309
+                    if (!preg_match('/^-?[0-9]*\.?[0-9]+$/', $val->value))
310 310
                     { // If not a number, change " to ' and put " around it
311
-                        $val->value=preg_replace('/"/',"'",$val->value);
311
+                        $val->value=preg_replace('/"/', "'", $val->value);
312 312
                         $val->value='"'.$val->value.'"';
313 313
                     }
314 314
                     $rep=0;
315
-                    $rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
316
-                    if ($rep==0)
315
+                    $rule=preg_replace('/_OID\('.$oid.'\)/', $val->value, $rule, -1, $rep);
316
+                    if ($rep == 0)
317 317
                     {
318
-                        $this->logging->log("Error in rule_eval",WARN,'');
318
+                        $this->logging->log("Error in rule_eval", WARN, '');
319 319
                         return false;
320 320
                     }
321 321
                     $found=1;
322 322
                     break;
323 323
                 }
324 324
             }
325
-            if ($found==0)
325
+            if ($found == 0)
326 326
             {	// OID not found : throw error
327 327
                 throw new Exception('OID '.$oid.' not found in trap');
328 328
             }
329 329
         }
330 330
         $item=0;
331 331
         $rule=$this->eval_cleanup($rule);
332
-        $this->logging->log('Rule after clenup: '.$rule,INFO );
332
+        $this->logging->log('Rule after clenup: '.$rule, INFO);
333 333
         
334
-        return  $this->evaluation($rule,$item);
334
+        return  $this->evaluation($rule, $item);
335 335
     }
336 336
     
337 337
 }
338 338
\ No newline at end of file
Please login to merge, or discard this patch.
Braces   +47 added lines, -20 removed lines patch added patch discarded remove patch
@@ -56,14 +56,15 @@  discard block
 block discarded – undo
56 56
         $start=$item;
57 57
         $parenthesis_count=0;
58 58
         while (($item < strlen($rule)) // Not end of string AND
59
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
59
+            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) {
60
+        	// Closing ')' or embeded ()
60 61
         {
61 62
             if ($rule[$item] == '"' )
62 63
             { // pass through string
63 64
                 $item++;
65
+        }
64 66
                 $item=$this->eval_getNext($rule,$item,'"');
65
-            }
66
-            else{
67
+            } else{
67 68
                 if ($rule[$item] == '(')
68 69
                 {
69 70
                     $parenthesis_count++;
@@ -91,7 +92,9 @@  discard block
 block discarded – undo
91 92
         {
92 93
             throw new Exception("Early end of string ".$rule ." at " .$item );
93 94
         }
94
-        while ($rule[$item]==' ') $item++;
95
+        while ($rule[$item]==' ') {
96
+        	$item++;
97
+        }
95 98
         if (preg_match('/[\-0-9\.]/',$rule[$item]))
96 99
         { // number
97 100
             return $this->get_number($rule, $item);
@@ -125,7 +128,9 @@  discard block
 block discarded – undo
125 128
     
126 129
     protected function eval_getOper($rule,&$item)
127 130
     {
128
-        while ($rule[$item]==' ') $item++;
131
+        while ($rule[$item]==' ') {
132
+        	$item++;
133
+        }
129 134
         switch ($rule[$item])
130 135
         {
131 136
             case '<':
@@ -152,12 +157,13 @@  discard block
 block discarded – undo
152 157
     
153 158
     private function check_negate_first($rule,&$item)
154 159
     {
155
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
160
+        if ( $rule[$item] == '!') {
161
+        	// If '!' found, negate next expression.
156 162
         {
157 163
             $item++;
158
-            return true;
159 164
         }
160
-        else
165
+            return true;
166
+        } else
161 167
         {
162 168
             return false;
163 169
         }
@@ -177,7 +183,10 @@  discard block
 block discarded – undo
177 183
             case '&':	$retVal= ($val1 && $val2); break;
178 184
             default:  throw new Exception("Error in expression - unknown comp : ".$comp);
179 185
         }
180
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
186
+        if ($negate === true) {
187
+        	$retVal = ! $retVal;
188
+        }
189
+        // Inverse result if negate before expression
181 190
         
182 191
         return $retVal;
183 192
     }
@@ -198,10 +207,14 @@  discard block
 block discarded – undo
198 207
         list($type1,$val1) = $this->eval_getElement($rule,$item);
199 208
         //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
200 209
         
201
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
210
+        if ($item==strlen($rule)) {
211
+        	// If only element, return value, but only boolean
202 212
         {
203 213
             if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
204
-            if ($negate === true) $val1= ! $val1;
214
+        }
215
+            if ($negate === true) {
216
+            	$val1= ! $val1;
217
+            }
205 218
             return $val1;
206 219
         }
207 220
         
@@ -210,31 +223,41 @@  discard block
 block discarded – undo
210 223
         //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
211 224
         
212 225
         // Third element : number, string or ()
213
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
226
+        if ( $rule[$item] == '!') {
227
+        	// starts with a ! so evaluate whats next
214 228
         {
215 229
             $item++;
216
-            if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
230
+        }
231
+            if ($typec != 1) {
232
+            	throw new Exception("Mixing boolean and comparison : ".$rule);
233
+            }
217 234
             $val2= ! $this->evaluation($rule,$item);
218 235
             $type2=2; // result is a boolean
219
-        }
220
-        else
236
+        } else
221 237
         {
222 238
             list($type2,$val2) = $this->eval_getElement($rule,$item);
223 239
         }
224 240
         //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
225 241
         
226
-        if ($type1!=$type2)  // cannot compare different types
242
+        if ($type1!=$type2) {
243
+        	// cannot compare different types
227 244
         {
228 245
             throw new Exception("Cannot compare string & number : ".$rule);
229 246
         }
230
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
247
+        }
248
+        if ($typec==1 && $type1 !=2) {
249
+        	// cannot use & or | with string/number
231 250
         {
232 251
             throw new Exception("Cannot use boolean operators with string & number : ".$rule);
233 252
         }
253
+        }
234 254
         
235 255
         $retVal = $this->do_compare($val1, $val2, $comp, $negate);
236 256
         
237
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
257
+        if ($item==strlen($rule)) {
258
+        	return $retVal;
259
+        }
260
+        // End of string : return evaluation
238 261
         // check for logical operator :
239 262
         switch ($rule[$item])
240 263
         {
@@ -262,7 +285,9 @@  discard block
 block discarded – undo
262 285
                     $rule2.=$rule[$item];
263 286
                     $item++;
264 287
                 }
265
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
288
+                if ($item == strlen ($rule)) {
289
+                	throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
290
+                }
266 291
                 $rule2.=$rule[$item];
267 292
                 $item++;
268 293
                 continue;
@@ -283,10 +308,12 @@  discard block
 block discarded – undo
283 308
     
284 309
     public function eval_rule($rule,$oidList)
285 310
     {
286
-        if ($rule==null || $rule == '') // Empty rule is always true
311
+        if ($rule==null || $rule == '') {
312
+        	// Empty rule is always true
287 313
         {
288 314
             return true;
289 315
         }
316
+        }
290 317
         $matches=array();
291 318
         while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
292 319
         {
Please login to merge, or discard this patch.
bin/trap_class.php 3 patches
Indentation   +224 added lines, -224 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
 class Trap
19 19
 {
20 20
 	// Configuration files and dirs
21
-    /** @var string Icinga etc path */
21
+	/** @var string Icinga etc path */
22 22
 	protected $icingaweb2_etc;
23 23
 	protected $trap_module_config; //< config.ini of module	
24 24
 	protected $icingaweb2_ressources; //< resources.ini of icingaweb2
@@ -62,7 +62,7 @@  discard block
 block discarded – undo
62 62
 	
63 63
 	function __construct($etc_dir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
64 64
 	{
65
-	    // Paths of ini files
65
+		// Paths of ini files
66 66
 		$this->icingaweb2_etc=$etc_dir;
67 67
 		$this->trap_module_config=$this->icingaweb2_etc."/modules/trapdirector/config.ini";		
68 68
 		$this->icingaweb2_ressources=$this->icingaweb2_etc."/resources.ini";
@@ -71,23 +71,23 @@  discard block
 block discarded – undo
71 71
 		$this->logging = new Logging();
72 72
 		if ($baseLogLevel != null)
73 73
 		{
74
-		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
75
-		    $this->logSetup=true;
74
+			$this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
75
+			$this->logSetup=true;
76 76
 		}
77 77
 		else
78
-		    $this->logSetup=false;
78
+			$this->logSetup=false;
79 79
 		$this->logging->log('Loggin started', INFO);
80 80
 
81 81
 		// Get options from ini files
82 82
 		if (! is_file($this->trap_module_config))
83 83
 		{
84
-		    throw new Exception("Ini file ".$this->trap_module_config." does not exists");
84
+			throw new Exception("Ini file ".$this->trap_module_config." does not exists");
85 85
 		}
86 86
 		$trapConfig=parse_ini_file($this->trap_module_config,true);
87 87
 		if ($trapConfig == false)
88 88
 		{
89
-		    $this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
90
-		    throw new Exception("Error reading ini file : ".$this->trap_module_config);
89
+			$this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
90
+			throw new Exception("Error reading ini file : ".$this->trap_module_config);
91 91
 		}
92 92
 		$this->getMainOptions($trapConfig); // Get main options from ini file
93 93
 		$this->setupDatabase($trapConfig); // Setup database class
@@ -121,26 +121,26 @@  discard block
 block discarded – undo
121 121
 	 */
122 122
 	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
123 123
 	{
124
-	    if (!isset($option_array[$option_category][$option_name]))
125
-	    {
126
-	        if ($message === null)
127
-	        {
128
-	            $message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
129
-	        }
130
-	        $this->logging->log($message,$log_level);
131
-	        return false;
132
-	    }
133
-	    else
134
-	    {
135
-	        $option_var=$option_array[$option_category][$option_name];
136
-	        return true;
137
-	    }
124
+		if (!isset($option_array[$option_category][$option_name]))
125
+		{
126
+			if ($message === null)
127
+			{
128
+				$message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
129
+			}
130
+			$this->logging->log($message,$log_level);
131
+			return false;
132
+		}
133
+		else
134
+		{
135
+			$option_var=$option_array[$option_category][$option_name];
136
+			return true;
137
+		}
138 138
 	}
139 139
 	
140 140
 	/** 
141 141
 	 * Get options from ini file
142 142
 	 * @param array $trap_config : ini file array
143
-	*/
143
+	 */
144 144
 	protected function getMainOptions($trapConfig)
145 145
 	{
146 146
 
@@ -159,10 +159,10 @@  discard block
 block discarded – undo
159 159
 		// API options
160 160
 		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->api_hostname))
161 161
 		{
162
-		    $this->api_use=true;
163
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->api_port);
164
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->api_username);
165
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->api_password);
162
+			$this->api_use=true;
163
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->api_port);
164
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->api_username);
165
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->api_password);
166 166
 		}
167 167
 	}
168 168
 	
@@ -172,45 +172,45 @@  discard block
 block discarded – undo
172 172
 	 */
173 173
 	protected function setupDatabase($trapConfig)
174 174
 	{
175
-	    // Trap database
176
-	    if (!array_key_exists('database',$trapConfig['config']))
177
-        {
178
-            $this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
179
-            return;
180
-        }
181
-        $dbTrapName=$trapConfig['config']['database'];
182
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
175
+		// Trap database
176
+		if (!array_key_exists('database',$trapConfig['config']))
177
+		{
178
+			$this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
179
+			return;
180
+		}
181
+		$dbTrapName=$trapConfig['config']['database'];
182
+		$this->logging->log("Found database in config file: ".$dbTrapName,INFO );
183 183
 	    
184 184
 	   if ( ($dbConfig=parse_ini_file($this->icingaweb2_ressources,true)) === false)
185
-	    {
186
-	        $this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
187
-	        return;
188
-	    }
189
-	    if (!array_key_exists($dbTrapName,$dbConfig))
190
-	    {
191
-	        $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
192
-	        return;
193
-	    }
185
+		{
186
+			$this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
187
+			return;
188
+		}
189
+		if (!array_key_exists($dbTrapName,$dbConfig))
190
+		{
191
+			$this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
192
+			return;
193
+		}
194 194
 	    
195
-	    $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->db_prefix);
195
+		$this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->db_prefix);
196 196
 	    
197
-	    if ($this->api_use === true) return; // In case of API use, no IDO is necessary
197
+		if ($this->api_use === true) return; // In case of API use, no IDO is necessary
198 198
         
199
-	    // IDO Database
200
-	    if (!array_key_exists('IDOdatabase',$trapConfig['config']))
201
-	    {
202
-	        $this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
203
-	    }
204
-	    $dbIdoName=$trapConfig['config']['IDOdatabase'];
205
-
206
-	    $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
207
-        if (!array_key_exists($dbIdoName,$dbConfig))
208
-	    {
209
-	        $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
210
-	        return;
211
-	    }
199
+		// IDO Database
200
+		if (!array_key_exists('IDOdatabase',$trapConfig['config']))
201
+		{
202
+			$this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
203
+		}
204
+		$dbIdoName=$trapConfig['config']['IDOdatabase'];
205
+
206
+		$this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
207
+		if (!array_key_exists($dbIdoName,$dbConfig))
208
+		{
209
+			$this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
210
+			return;
211
+		}
212 212
 	    
213
-	    $this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
213
+		$this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
214 214
 	}
215 215
 	
216 216
 	/**
@@ -221,9 +221,9 @@  discard block
 block discarded – undo
221 221
 		// Database options
222 222
 		if ($this->logSetup === false) // Only if logging was no setup in constructor
223 223
 		{
224
-    		$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
225
-    		$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
226
-    		$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
224
+			$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
225
+			$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
226
+			$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
227 227
 		}
228 228
 	}
229 229
 
@@ -234,10 +234,10 @@  discard block
 block discarded – undo
234 234
 	}
235 235
 	
236 236
 	/** 
237
-	*   Get data from db_config
238
-	*	@param $element string name of param
239
-	*	@return mixed : value (or null)
240
-	*/	
237
+	 *   Get data from db_config
238
+	 *	@param $element string name of param
239
+	 *	@return mixed : value (or null)
240
+	 */	
241 241
 	protected function getDBConfig($element)
242 242
 	{
243 243
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -255,15 +255,15 @@  discard block
 block discarded – undo
255 255
 	}
256 256
 	
257 257
 	/** OBSOLETE Send log. Throws exception on critical error
258
-	*	@param	string $message Message to log
259
-	*	@param	int $level 1=critical 2=warning 3=trace 4=debug
260
-	*	@param  string $destination file/syslog/display
261
-	*	@return void
262
-	**/	
258
+	 *	@param	string $message Message to log
259
+	 *	@param	int $level 1=critical 2=warning 3=trace 4=debug
260
+	 *	@param  string $destination file/syslog/display
261
+	 *	@return void
262
+	 **/	
263 263
 	public function trapLog( $message, $level, $destination ='') // OBSOLETE
264 264
 	{	
265 265
 		// TODO : replace ref with $this->logging->log 
266
-	    $this->logging->log($message, $level, $destination);
266
+		$this->logging->log($message, $level, $destination);
267 267
 	}
268 268
 	
269 269
 	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
@@ -273,19 +273,19 @@  discard block
 block discarded – undo
273 273
 	
274 274
 	protected function getAPI()
275 275
 	{
276
-	    if ($this->icinga2api == null)
277
-	    {
278
-	        $this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
279
-	    }
280
-	    return $this->icinga2api;
276
+		if ($this->icinga2api == null)
277
+		{
278
+			$this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
279
+		}
280
+		return $this->icinga2api;
281 281
 	}
282 282
 	
283 283
 	
284 284
 	/** 
285 285
 	 * read data from stream
286
-	*	@param $stream string input stream, defaults to "php://stdin"
287
-	*	@return mixed array trap data or exception with error
288
-	*/
286
+	 *	@param $stream string input stream, defaults to "php://stdin"
287
+	 *	@return mixed array trap data or exception with error
288
+	 */
289 289
 	public function read_trap($stream='php://stdin')
290 290
 	{
291 291
 		//Read data from snmptrapd from stdin
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
 
294 294
 		if ($input_stream === false)
295 295
 		{
296
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
296
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
297 297
 			$this->logging->log("Error reading stdin !",ERROR,'');
298 298
 			return null; // note : exception thrown by logging
299 299
 		}
@@ -302,21 +302,21 @@  discard block
 block discarded – undo
302 302
 		$this->receivingHost=chop(fgets($input_stream));
303 303
 		if ($this->receivingHost === false)
304 304
 		{
305
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
305
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
306 306
 			$this->logging->log("Error reading Host !",ERROR,''); 
307 307
 		}
308 308
 		// line 2 IP:port=>IP:port
309 309
 		$IP=chop(fgets($input_stream));
310 310
 		if ($IP === false)
311 311
 		{
312
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
312
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
313 313
 			$this->logging->log("Error reading IP !",ERROR,''); 
314 314
 		}
315 315
 		$matches=array();
316 316
 		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
317 317
 		if ($ret_code===0 || $ret_code===false) 
318 318
 		{
319
-		    $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
319
+			$this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
320 320
 			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
321 321
 		} 
322 322
 		else 
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 			}
338 338
 			else 
339 339
 			{
340
-			    if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
340
+				if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
341 341
 				{
342 342
 					$this->trap_data['trap_oid']=$matches[2];
343 343
 				}
@@ -353,7 +353,7 @@  discard block
 block discarded – undo
353 353
 
354 354
 		if ($this->trap_data['trap_oid']=='unknown')
355 355
 		{
356
-		    $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
356
+			$this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
357 357
 			$this->logging->log('no trap oid found',ERROR,'');
358 358
 		} 
359 359
 
@@ -383,9 +383,9 @@  discard block
 block discarded – undo
383 383
 
384 384
 	/** 
385 385
 	 * Translate oid into array(MIB,Name)
386
-	* @param $oid string oid to translate
387
-	* @return mixed : null if not found or array(MIB,Name)
388
-	*/
386
+	 * @param $oid string oid to translate
387
+	 * @return mixed : null if not found or array(MIB,Name)
388
+	 */
389 389
 	public function translateOID($oid)
390 390
 	{
391 391
 		// try from database
@@ -418,7 +418,7 @@  discard block
 block discarded – undo
418 418
 		
419 419
 		// Try to get oid name from snmptranslate
420 420
 		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
421
-		    ' '.$oid);
421
+			' '.$oid);
422 422
 		$matches=array();
423 423
 		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
424 424
 		if ($ret_code===0 || $ret_code === false) {
@@ -431,9 +431,9 @@  discard block
 block discarded – undo
431 431
 	
432 432
 	/** 
433 433
 	 * Erase old trap records 
434
-	*	@param integer $days : erase traps when more than $days old
435
-	*	@return integer : number of lines deleted
436
-	**/
434
+	 *	@param integer $days : erase traps when more than $days old
435
+	 *	@return integer : number of lines deleted
436
+	 **/
437 437
 	public function eraseOldTraps($days=0)
438 438
 	{
439 439
 		if ($days==0)
@@ -458,72 +458,72 @@  discard block
 block discarded – undo
458 458
 	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
459 459
 	{
460 460
 	    
461
-	    $db_conn=$this->trapsDB->db_connect_trap();
461
+		$db_conn=$this->trapsDB->db_connect_trap();
462 462
 	    
463
-	    // add date time
464
-	    $insert_col ='date_received,status';
465
-	    $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
463
+		// add date time
464
+		$insert_col ='date_received,status';
465
+		$insert_val = "'" . date("Y-m-d H:i:s")."','error'";
466 466
         
467
-	    if ($sourceIP !=null)
468
-	    {
469
-	        $insert_col .=',source_ip';
470
-	        $insert_val .=",'". $sourceIP ."'";
471
-	    }
472
-	    if ($trapoid !=null)
473
-	    {
474
-	        $insert_col .=',trap_oid';
475
-	        $insert_val .=",'". $trapoid ."'";
476
-	    }
477
-	    $insert_col .=',status_detail';
478
-	    $insert_val .=",'". $message ."'";
467
+		if ($sourceIP !=null)
468
+		{
469
+			$insert_col .=',source_ip';
470
+			$insert_val .=",'". $sourceIP ."'";
471
+		}
472
+		if ($trapoid !=null)
473
+		{
474
+			$insert_col .=',trap_oid';
475
+			$insert_val .=",'". $trapoid ."'";
476
+		}
477
+		$insert_col .=',status_detail';
478
+		$insert_val .=",'". $message ."'";
479 479
 	    
480
-	    $sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
480
+		$sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
481 481
 	    
482
-	    switch ($this->trapsDB->trapDBType)
483
-	    {
484
-	        case 'pgsql':
485
-	            $sql .= ' RETURNING id;';
486
-	            $this->logging->log('sql : '.$sql,INFO);
487
-	            if (($ret_code=$db_conn->query($sql)) === false) {
488
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
489
-	            }
490
-	            $this->logging->log('SQL insertion OK',INFO );
491
-	            // Get last id to insert oid/values in secondary table
492
-	            if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
482
+		switch ($this->trapsDB->trapDBType)
483
+		{
484
+			case 'pgsql':
485
+				$sql .= ' RETURNING id;';
486
+				$this->logging->log('sql : '.$sql,INFO);
487
+				if (($ret_code=$db_conn->query($sql)) === false) {
488
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
489
+				}
490
+				$this->logging->log('SQL insertion OK',INFO );
491
+				// Get last id to insert oid/values in secondary table
492
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
493 493
 	                
494
-	                $this->logging->log('Erreur recuperation id',1,'');
495
-	            }
496
-	            if (! isset($inserted_id_ret['id'])) {
497
-	                $this->logging->log('Error getting id',1,'');
498
-	            }
499
-	            $this->trap_id=$inserted_id_ret['id'];
500
-	            break;
501
-	        case 'mysql':
502
-	            $sql .= ';';
503
-	            $this->logging->log('sql : '.$sql,INFO );
504
-	            if ($db_conn->query($sql) === false) {
505
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
506
-	            }
507
-	            $this->logging->log('SQL insertion OK',INFO );
508
-	            // Get last id to insert oid/values in secondary table
509
-	            $sql='SELECT LAST_INSERT_ID();';
510
-	            if (($ret_code=$db_conn->query($sql)) === false) {
511
-	                $this->logging->log('Erreur recuperation id',1,'');
512
-	            }
494
+					$this->logging->log('Erreur recuperation id',1,'');
495
+				}
496
+				if (! isset($inserted_id_ret['id'])) {
497
+					$this->logging->log('Error getting id',1,'');
498
+				}
499
+				$this->trap_id=$inserted_id_ret['id'];
500
+				break;
501
+			case 'mysql':
502
+				$sql .= ';';
503
+				$this->logging->log('sql : '.$sql,INFO );
504
+				if ($db_conn->query($sql) === false) {
505
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
506
+				}
507
+				$this->logging->log('SQL insertion OK',INFO );
508
+				// Get last id to insert oid/values in secondary table
509
+				$sql='SELECT LAST_INSERT_ID();';
510
+				if (($ret_code=$db_conn->query($sql)) === false) {
511
+					$this->logging->log('Erreur recuperation id',1,'');
512
+				}
513 513
 	            
514
-	            $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
515
-	            if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
516
-	            $this->trap_id=$inserted_id;
517
-	            break;
518
-	        default:
519
-	            $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
520
-	    }
514
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
515
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
516
+				$this->trap_id=$inserted_id;
517
+				break;
518
+			default:
519
+				$this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
520
+		}
521 521
 	    
522
-	    $this->logging->log('id found: '. $this->trap_id,INFO );    
522
+		$this->logging->log('id found: '. $this->trap_id,INFO );    
523 523
 	}
524 524
 	
525 525
 	/** Write trap data to trap database
526
-	*/
526
+	 */
527 527
 	public function writeTrapToDB()
528 528
 	{
529 529
 		
@@ -621,10 +621,10 @@  discard block
 block discarded – undo
621 621
 	}
622 622
 
623 623
 	/** Get rules from rule database with ip and oid
624
-	*	@param $ip string ipv4 or ipv6
625
-	*	@param $oid string oid in numeric
626
-	*	@return mixed|boolean : PDO object or false
627
-	*/	
624
+	 *	@param $ip string ipv4 or ipv6
625
+	 *	@param $oid string oid in numeric
626
+	 *	@return mixed|boolean : PDO object or false
627
+	 */	
628 628
 	protected function getRules($ip,$oid)
629 629
 	{
630 630
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -683,9 +683,9 @@  discard block
 block discarded – undo
683 683
 	}
684 684
 
685 685
 	/** Add rule match to rule
686
-	*	@param id int : rule id
687
-	*   @param set int : value to set
688
-	*/
686
+	 *	@param id int : rule id
687
+	 *   @param set int : value to set
688
+	 */
689 689
 	protected function add_rule_match($id, $set)
690 690
 	{
691 691
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -702,65 +702,65 @@  discard block
 block discarded – undo
702 702
 	 * @param integer $state numerical staus 
703 703
 	 * @param string $display
704 704
 	 * @returnn bool true is service check was sent without error
705
-	*/
705
+	 */
706 706
 	public function serviceCheckResult($host,$service,$state,$display)
707 707
 	{
708
-	    if ($this->api_use === false)
709
-	    {
710
-    		$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
711
-    			$host.';' .$service .';' . $state . ';'.$display;
712
-    		$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
708
+		if ($this->api_use === false)
709
+		{
710
+			$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
711
+				$host.';' .$service .';' . $state . ';'.$display;
712
+			$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
713 713
     		
714
-    		// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
715
-    		exec('echo "'.$send.'" > ' .$this->icinga2cmd);
716
-    		return true;
717
-	    }
718
-	    else
719
-	    {
720
-	        // Get perfdata if found
721
-	        $matches=array();
722
-	        if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
723
-	        {
724
-	            $display=$matches[1];
725
-	            $perfdata=$matches[2];
726
-	        }
727
-	        else
728
-	        {
729
-	            $perfdata='';
730
-	        }
714
+			// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
715
+			exec('echo "'.$send.'" > ' .$this->icinga2cmd);
716
+			return true;
717
+		}
718
+		else
719
+		{
720
+			// Get perfdata if found
721
+			$matches=array();
722
+			if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
723
+			{
724
+				$display=$matches[1];
725
+				$perfdata=$matches[2];
726
+			}
727
+			else
728
+			{
729
+				$perfdata='';
730
+			}
731 731
 	        
732
-	        $api = $this->getAPI();
733
-	        $api->setCredentials($this->api_username, $this->api_password);
734
-	        list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
735
-	        if ($retcode == false)
736
-	        {
737
-	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
738
-	            return false;
739
-	        }
740
-	        else 
741
-	        {
742
-	            $this->logging->log( "Sent result : " .$retmessage,INFO );
743
-	            return true;
744
-	        }
745
-	    }
732
+			$api = $this->getAPI();
733
+			$api->setCredentials($this->api_username, $this->api_password);
734
+			list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
735
+			if ($retcode == false)
736
+			{
737
+				$this->logging->log( "Error sending result : " .$retmessage,WARN,'');
738
+				return false;
739
+			}
740
+			else 
741
+			{
742
+				$this->logging->log( "Sent result : " .$retmessage,INFO );
743
+				return true;
744
+			}
745
+		}
746 746
 	}
747 747
 	
748 748
 	public function getHostByIP($ip)
749 749
 	{
750
-	    $api = $this->getAPI();
751
-	    $api->setCredentials($this->api_username, $this->api_password);
752
-	    return $api->getHostByIP($ip);
750
+		$api = $this->getAPI();
751
+		$api->setCredentials($this->api_username, $this->api_password);
752
+		return $api->getHostByIP($ip);
753 753
 	}
754 754
 	
755 755
 	/** Resolve display. 
756
-	*	Changes _OID(<oid>) to value if found or text "<not in trap>"
757
-	*	@param $display string
758
-	*	@return string display
759
-	*/
756
+	 *	Changes _OID(<oid>) to value if found or text "<not in trap>"
757
+	 *	@param $display string
758
+	 *	@return string display
759
+	 */
760 760
 	protected function applyDisplay($display)
761 761
 	{
762
-	    $matches=array();
763
-	    while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
762
+		$matches=array();
763
+		while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
764 764
 		{
765 765
 			$oid=$matches[1];
766 766
 			$found=0;
@@ -794,7 +794,7 @@  discard block
 block discarded – undo
794 794
 	}
795 795
 	
796 796
 	/** Match rules for current trap and do action
797
-	*/
797
+	 */
798 798
 	public function applyRules()
799 799
 	{
800 800
 		$rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
@@ -832,12 +832,12 @@  discard block
 block discarded – undo
832 832
 					{
833 833
 						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
834 834
 						{
835
-						    $this->trap_action.='Error sending status : check cmd/API';
835
+							$this->trap_action.='Error sending status : check cmd/API';
836 836
 						}
837 837
 						else
838 838
 						{
839
-						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
840
-						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
839
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
840
+							$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
841 841
 						}
842 842
 					}
843 843
 					else
@@ -854,15 +854,15 @@  discard block
 block discarded – undo
854 854
 					$this->logging->log('action NOK : '.$action,INFO );
855 855
 					if ($action >= 0)
856 856
 					{
857
-					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
858
-					    {
859
-					        $this->trap_action.='Error sending status : check cmd/API';
860
-					    }
861
-					    else
862
-					    {
863
-    						$this->add_rule_match($rule['id'],$rule['num_match']+1);
864
-    						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
865
-					    }
857
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
858
+						{
859
+							$this->trap_action.='Error sending status : check cmd/API';
860
+						}
861
+						else
862
+						{
863
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
864
+							$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
865
+						}
866 866
 					}
867 867
 					else
868 868
 					{
@@ -885,9 +885,9 @@  discard block
 block discarded – undo
885 885
 			}
886 886
 			catch (Exception $e) 
887 887
 			{ 
888
-			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
889
-			    $this->trap_action.=' ERR : '.$e->getMessage();
890
-			    $this->trap_data['status']='error';
888
+				$this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
889
+				$this->trap_action.=' ERR : '.$e->getMessage();
890
+				$this->trap_data['status']='error';
891 891
 			}
892 892
 			
893 893
 		}
@@ -902,8 +902,8 @@  discard block
 block discarded – undo
902 902
 	}
903 903
 
904 904
 	/** Add Time a action to rule
905
-	*	@param string $time : time to process to insert in SQL
906
-	*/
905
+	 *	@param string $time : time to process to insert in SQL
906
+	 */
907 907
 	public function add_rule_final($time)
908 908
 	{
909 909
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -920,9 +920,9 @@  discard block
 block discarded – undo
920 920
 	/*********** UTILITIES *********************/
921 921
 	
922 922
 	/** reset service to OK after time defined in rule
923
-	*	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better 
924
-	*	@return integer : not in use
925
-	**/
923
+	 *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better 
924
+	 *	@return integer : not in use
925
+	 **/
926 926
 	public function reset_services()
927 927
 	{
928 928
 		// Get all services not in 'ok' state
Please login to merge, or discard this patch.
Spacing   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -38,9 +38,9 @@  discard block
 block discarded – undo
38 38
 
39 39
 	// Logs
40 40
 	/** @var Logging Logging class. */
41
-	protected $logging;    //< Logging class.
41
+	protected $logging; //< Logging class.
42 42
 	/** @var bool true if log was setup in constructor */
43
-	protected $logSetup;   //< bool true if log was setup in constructor
43
+	protected $logSetup; //< bool true if log was setup in constructor
44 44
 	
45 45
 	// Databases
46 46
 	public $trapsDB; //< Database class
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 	/** @var Rule rule class */
61 61
 	public $ruleClass;
62 62
 	
63
-	function __construct($etc_dir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
63
+	function __construct($etc_dir='/etc/icingaweb2', $baseLogLevel=null, $baseLogMode='syslog', $baseLogFile='')
64 64
 	{
65 65
 	    // Paths of ini files
66 66
 		$this->icingaweb2_etc=$etc_dir;
@@ -68,10 +68,10 @@  discard block
 block discarded – undo
68 68
 		$this->icingaweb2_ressources=$this->icingaweb2_etc."/resources.ini";
69 69
 
70 70
 		// Setup logging
71
-		$this->logging = new Logging();
71
+		$this->logging=new Logging();
72 72
 		if ($baseLogLevel != null)
73 73
 		{
74
-		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
74
+		    $this->logging->setLogging($baseLogLevel, $baseLogMode, $baseLogFile);
75 75
 		    $this->logSetup=true;
76 76
 		}
77 77
 		else
@@ -79,14 +79,14 @@  discard block
 block discarded – undo
79 79
 		$this->logging->log('Loggin started', INFO);
80 80
 
81 81
 		// Get options from ini files
82
-		if (! is_file($this->trap_module_config))
82
+		if (!is_file($this->trap_module_config))
83 83
 		{
84 84
 		    throw new Exception("Ini file ".$this->trap_module_config." does not exists");
85 85
 		}
86
-		$trapConfig=parse_ini_file($this->trap_module_config,true);
86
+		$trapConfig=parse_ini_file($this->trap_module_config, true);
87 87
 		if ($trapConfig == false)
88 88
 		{
89
-		    $this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
89
+		    $this->logging->log("Error reading ini file : ".$this->trap_module_config, ERROR, 'syslog');
90 90
 		    throw new Exception("Error reading ini file : ".$this->trap_module_config);
91 91
 		}
92 92
 		$this->getMainOptions($trapConfig); // Get main options from ini file
@@ -95,9 +95,9 @@  discard block
 block discarded – undo
95 95
 		$this->getDatabaseOptions(); // Get options in database
96 96
 		if ($this->api_use === true) $this->getAPI(); // Setup API
97 97
 		
98
-		$this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
98
+		$this->mibClass=new Mib($this->logging, $this->trapsDB, $this->snmptranslate, $this->snmptranslate_dirs); // Create Mib class
99 99
 		
100
-		$this->ruleClass = new Rule($this->logging); //< Create Rule class
100
+		$this->ruleClass=new Rule($this->logging); //< Create Rule class
101 101
 		
102 102
 		$this->trap_data=array(
103 103
 			'source_ip'	=> 'unknown',
@@ -119,15 +119,15 @@  discard block
 block discarded – undo
119 119
 	 * @param string $message warning message if not found
120 120
 	 * @return boolean true if found, or false
121 121
 	 */
122
-	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
122
+	protected function getOptionIfSet($option_array, $option_category, $option_name, &$option_var, $log_level=2, $message=null)
123 123
 	{
124 124
 	    if (!isset($option_array[$option_category][$option_name]))
125 125
 	    {
126 126
 	        if ($message === null)
127 127
 	        {
128
-	            $message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
128
+	            $message='No '.$option_name.' in config file: '.$this->trap_module_config;
129 129
 	        }
130
-	        $this->logging->log($message,$log_level);
130
+	        $this->logging->log($message, $log_level);
131 131
 	        return false;
132 132
 	    }
133 133
 	    else
@@ -145,24 +145,24 @@  discard block
 block discarded – undo
145 145
 	{
146 146
 
147 147
 		// Snmptranslate binary path
148
-		$this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
148
+		$this->getOptionIfSet($trapConfig, 'config', 'snmptranslate', $this->snmptranslate);
149 149
 
150 150
 		// mibs path
151
-		$this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
151
+		$this->getOptionIfSet($trapConfig, 'config', 'snmptranslate_dirs', $this->snmptranslate_dirs);
152 152
 
153 153
 		// icinga2cmd path
154
-		$this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
154
+		$this->getOptionIfSet($trapConfig, 'config', 'icingacmd', $this->icinga2cmd);
155 155
 		
156 156
 		// table prefix
157
-		$this->getOptionIfSet($trapConfig,'config','database_prefix', $this->db_prefix);
157
+		$this->getOptionIfSet($trapConfig, 'config', 'database_prefix', $this->db_prefix);
158 158
 
159 159
 		// API options
160
-		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->api_hostname))
160
+		if ($this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_host', $this->api_hostname))
161 161
 		{
162 162
 		    $this->api_use=true;
163
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->api_port);
164
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->api_username);
165
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->api_password);
163
+		    $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_port', $this->api_port);
164
+		    $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_user', $this->api_username);
165
+		    $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_password', $this->api_password);
166 166
 		}
167 167
 	}
168 168
 	
@@ -173,40 +173,40 @@  discard block
 block discarded – undo
173 173
 	protected function setupDatabase($trapConfig)
174 174
 	{
175 175
 	    // Trap database
176
-	    if (!array_key_exists('database',$trapConfig['config']))
176
+	    if (!array_key_exists('database', $trapConfig['config']))
177 177
         {
178
-            $this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
178
+            $this->logging->log("No database in config file: ".$this->trap_module_config, ERROR, '');
179 179
             return;
180 180
         }
181 181
         $dbTrapName=$trapConfig['config']['database'];
182
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
182
+        $this->logging->log("Found database in config file: ".$dbTrapName, INFO);
183 183
 	    
184
-	   if ( ($dbConfig=parse_ini_file($this->icingaweb2_ressources,true)) === false)
184
+	   if (($dbConfig=parse_ini_file($this->icingaweb2_ressources, true)) === false)
185 185
 	    {
186
-	        $this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
186
+	        $this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources, ERROR, '');
187 187
 	        return;
188 188
 	    }
189
-	    if (!array_key_exists($dbTrapName,$dbConfig))
189
+	    if (!array_key_exists($dbTrapName, $dbConfig))
190 190
 	    {
191
-	        $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
191
+	        $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources, ERROR, '');
192 192
 	        return;
193 193
 	    }
194 194
 	    
195
-	    $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->db_prefix);
195
+	    $this->trapsDB=new Database($this->logging, $dbConfig[$dbTrapName], $this->db_prefix);
196 196
 	    
197 197
 	    if ($this->api_use === true) return; // In case of API use, no IDO is necessary
198 198
         
199 199
 	    // IDO Database
200
-	    if (!array_key_exists('IDOdatabase',$trapConfig['config']))
200
+	    if (!array_key_exists('IDOdatabase', $trapConfig['config']))
201 201
 	    {
202
-	        $this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
202
+	        $this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config, ERROR, '');
203 203
 	    }
204 204
 	    $dbIdoName=$trapConfig['config']['IDOdatabase'];
205 205
 
206
-	    $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
207
-        if (!array_key_exists($dbIdoName,$dbConfig))
206
+	    $this->logging->log("Found IDO database in config file: ".$dbIdoName, INFO);
207
+        if (!array_key_exists($dbIdoName, $dbConfig))
208 208
 	    {
209
-	        $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
209
+	        $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources, ERROR, '');
210 210
 	        return;
211 211
 	    }
212 212
 	    
@@ -221,13 +221,13 @@  discard block
 block discarded – undo
221 221
 		// Database options
222 222
 		if ($this->logSetup === false) // Only if logging was no setup in constructor
223 223
 		{
224
-    		$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
225
-    		$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
226
-    		$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
224
+    		$this->getDBConfigIfSet('log_level', $this->logging->debugLevel);
225
+    		$this->getDBConfigIfSet('log_destination', $this->logging->outputMode);
226
+    		$this->getDBConfigIfSet('log_file', $this->logging->outputFile);
227 227
 		}
228 228
 	}
229 229
 
230
-	protected function getDBConfigIfSet($element,&$variable)
230
+	protected function getDBConfigIfSet($element, &$variable)
231 231
 	{
232 232
 		$value=$this->getDBConfig($element);
233 233
 		if ($value != 'null') $variable=$value;
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
 		$db_conn=$this->trapsDB->db_connect_trap();
244 244
 		$sql='SELECT value from '.$this->db_prefix.'db_config WHERE ( name=\''.$element.'\' )';
245 245
 		if (($ret_code=$db_conn->query($sql)) === false) {
246
-			$this->logging->log('No result in query : ' . $sql,WARN,'');
246
+			$this->logging->log('No result in query : '.$sql, WARN, '');
247 247
 			return null;
248 248
 		}
249 249
 		$value=$ret_code->fetch();
@@ -260,22 +260,22 @@  discard block
 block discarded – undo
260 260
 	*	@param  string $destination file/syslog/display
261 261
 	*	@return void
262 262
 	**/	
263
-	public function trapLog( $message, $level, $destination ='') // OBSOLETE
263
+	public function trapLog($message, $level, $destination='') // OBSOLETE
264 264
 	{	
265 265
 		// TODO : replace ref with $this->logging->log 
266 266
 	    $this->logging->log($message, $level, $destination);
267 267
 	}
268 268
 	
269
-	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
269
+	public function setLogging($debugLvl, $outputType, $outputOption=null)  // OBSOLETE
270 270
 	{
271
-		$this->logging->setLogging($debugLvl, $outputType,$outputOption);
271
+		$this->logging->setLogging($debugLvl, $outputType, $outputOption);
272 272
 	}
273 273
 	
274 274
 	protected function getAPI()
275 275
 	{
276 276
 	    if ($this->icinga2api == null)
277 277
 	    {
278
-	        $this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
278
+	        $this->icinga2api=new Icinga2API($this->api_hostname, $this->api_port);
279 279
 	    }
280 280
 	    return $this->icinga2api;
281 281
 	}
@@ -294,7 +294,7 @@  discard block
 block discarded – undo
294 294
 		if ($input_stream === false)
295 295
 		{
296 296
 		    $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
297
-			$this->logging->log("Error reading stdin !",ERROR,'');
297
+			$this->logging->log("Error reading stdin !", ERROR, '');
298 298
 			return null; // note : exception thrown by logging
299 299
 		}
300 300
 
@@ -303,21 +303,21 @@  discard block
 block discarded – undo
303 303
 		if ($this->receivingHost === false)
304 304
 		{
305 305
 		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
306
-			$this->logging->log("Error reading Host !",ERROR,''); 
306
+			$this->logging->log("Error reading Host !", ERROR, ''); 
307 307
 		}
308 308
 		// line 2 IP:port=>IP:port
309 309
 		$IP=chop(fgets($input_stream));
310 310
 		if ($IP === false)
311 311
 		{
312 312
 		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
313
-			$this->logging->log("Error reading IP !",ERROR,''); 
313
+			$this->logging->log("Error reading IP !", ERROR, ''); 
314 314
 		}
315 315
 		$matches=array();
316
-		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
317
-		if ($ret_code===0 || $ret_code===false) 
316
+		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/', $IP, $matches);
317
+		if ($ret_code === 0 || $ret_code === false) 
318 318
 		{
319 319
 		    $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
320
-			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
320
+			$this->logging->log('Error parsing IP : '.$IP, ERROR, '');
321 321
 		} 
322 322
 		else 
323 323
 		{		
@@ -327,34 +327,34 @@  discard block
 block discarded – undo
327 327
 			$this->trap_data['destination_port']=$matches[4];
328 328
 		}
329 329
 
330
-		while (($vars=fgets($input_stream)) !==false)
330
+		while (($vars=fgets($input_stream)) !== false)
331 331
 		{
332 332
 			$vars=chop($vars);
333
-			$ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
334
-			if ($ret_code===0 || $ret_code===false)
333
+			$ret_code=preg_match('/^([^ ]+) (.*)$/', $vars, $matches);
334
+			if ($ret_code === 0 || $ret_code === false)
335 335
 			{
336
-				$this->logging->log('No match on trap data : '.$vars,WARN,'');
336
+				$this->logging->log('No match on trap data : '.$vars, WARN, '');
337 337
 			}
338 338
 			else 
339 339
 			{
340
-			    if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
340
+			    if (($matches[1] == '.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1] == '.1.3.6.1.6.3.1.1.4.1'))
341 341
 				{
342 342
 					$this->trap_data['trap_oid']=$matches[2];
343 343
 				}
344 344
 				else
345 345
 				{
346
-					$object= new stdClass;
347
-					$object->oid =$matches[1];
348
-					$object->value = $matches[2];
349
-					array_push($this->trap_data_ext,$object);
346
+					$object=new stdClass;
347
+					$object->oid=$matches[1];
348
+					$object->value=$matches[2];
349
+					array_push($this->trap_data_ext, $object);
350 350
 				}
351 351
 			}
352 352
 		}
353 353
 
354
-		if ($this->trap_data['trap_oid']=='unknown')
354
+		if ($this->trap_data['trap_oid'] == 'unknown')
355 355
 		{
356
-		    $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
357
-			$this->logging->log('no trap oid found',ERROR,'');
356
+		    $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)", $this->trap_data['source_ip']);
357
+			$this->logging->log('no trap oid found', ERROR, '');
358 358
 		} 
359 359
 
360 360
 		// Translate oids.
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
 		}
377 377
 		
378 378
 
379
-		$this->trap_data['status']= 'waiting';
379
+		$this->trap_data['status']='waiting';
380 380
 		
381 381
 		return $this->trap_data;
382 382
 	}
@@ -392,40 +392,40 @@  discard block
 block discarded – undo
392 392
 		$db_conn=$this->trapsDB->db_connect_trap();
393 393
 		
394 394
 		$sql='SELECT mib,name from '.$this->db_prefix.'mib_cache WHERE oid=\''.$oid.'\';';
395
-		$this->logging->log('SQL query : '.$sql,DEBUG );
395
+		$this->logging->log('SQL query : '.$sql, DEBUG);
396 396
 		if (($ret_code=$db_conn->query($sql)) === false) {
397
-			$this->logging->log('No result in query : ' . $sql,ERROR,'');
397
+			$this->logging->log('No result in query : '.$sql, ERROR, '');
398 398
 		}
399 399
 		$name=$ret_code->fetch();
400 400
 		if ($name['name'] != null)
401 401
 		{
402
-			return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
402
+			return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
403 403
 		}
404 404
 		
405 405
 		// Also check if it is an instance of OID
406
-		$oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
406
+		$oid_instance=preg_replace('/\.[0-9]+$/', '', $oid);
407 407
 		
408 408
 		$sql='SELECT mib,name from '.$this->db_prefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
409
-		$this->logging->log('SQL query : '.$sql,DEBUG );
409
+		$this->logging->log('SQL query : '.$sql, DEBUG);
410 410
 		if (($ret_code=$db_conn->query($sql)) === false) {
411
-			$this->logging->log('No result in query : ' . $sql,ERROR,'');
411
+			$this->logging->log('No result in query : '.$sql, ERROR, '');
412 412
 		}
413 413
 		$name=$ret_code->fetch();
414 414
 		if ($name['name'] != null)
415 415
 		{
416
-			return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
416
+			return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
417 417
 		}
418 418
 		
419 419
 		// Try to get oid name from snmptranslate
420
-		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
420
+		$translate=exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
421 421
 		    ' '.$oid);
422 422
 		$matches=array();
423
-		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
424
-		if ($ret_code===0 || $ret_code === false) {
423
+		$ret_code=preg_match('/(.*)::(.*)/', $translate, $matches);
424
+		if ($ret_code === 0 || $ret_code === false) {
425 425
 			return NULL;
426 426
 		} else {
427
-			$this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
428
-			return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
427
+			$this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid, INFO);
428
+			return array('trap_name_mib'=>$matches[1], 'trap_name'=>$matches[2]);
429 429
 		}	
430 430
 	}
431 431
 	
@@ -436,90 +436,90 @@  discard block
 block discarded – undo
436 436
 	**/
437 437
 	public function eraseOldTraps($days=0)
438 438
 	{
439
-		if ($days==0)
439
+		if ($days == 0)
440 440
 		{
441 441
 			if (($days=$this->getDBConfig('db_remove_days')) == null)
442 442
 			{
443
-				$this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
443
+				$this->logging->log('No days specified & no db value : no tap erase', WARN, '');
444 444
 				return;
445 445
 			}
446 446
 		}
447 447
 		$db_conn=$this->trapsDB->db_connect_trap();
448
-		$daysago = strtotime("-".$days." day");
449
-		$sql= 'delete from '.$this->db_prefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
448
+		$daysago=strtotime("-".$days." day");
449
+		$sql='delete from '.$this->db_prefix.'received where date_received < \''.date("Y-m-d H:i:s", $daysago).'\';';
450 450
 		if ($db_conn->query($sql) === false) {
451
-			$this->logging->log('Error erasing traps : '.$sql,ERROR,'');
451
+			$this->logging->log('Error erasing traps : '.$sql, ERROR, '');
452 452
 		}
453
-		$this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
453
+		$this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql, INFO);
454 454
 	}
455 455
 
456 456
 	/** Write error to received trap database
457 457
 	 */
458
-	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
458
+	public function writeTrapErrorToDB($message, $sourceIP=null, $trapoid=null)
459 459
 	{
460 460
 	    
461 461
 	    $db_conn=$this->trapsDB->db_connect_trap();
462 462
 	    
463 463
 	    // add date time
464
-	    $insert_col ='date_received,status';
465
-	    $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
464
+	    $insert_col='date_received,status';
465
+	    $insert_val="'".date("Y-m-d H:i:s")."','error'";
466 466
         
467
-	    if ($sourceIP !=null)
467
+	    if ($sourceIP != null)
468 468
 	    {
469
-	        $insert_col .=',source_ip';
470
-	        $insert_val .=",'". $sourceIP ."'";
469
+	        $insert_col.=',source_ip';
470
+	        $insert_val.=",'".$sourceIP."'";
471 471
 	    }
472
-	    if ($trapoid !=null)
472
+	    if ($trapoid != null)
473 473
 	    {
474
-	        $insert_col .=',trap_oid';
475
-	        $insert_val .=",'". $trapoid ."'";
474
+	        $insert_col.=',trap_oid';
475
+	        $insert_val.=",'".$trapoid."'";
476 476
 	    }
477
-	    $insert_col .=',status_detail';
478
-	    $insert_val .=",'". $message ."'";
477
+	    $insert_col.=',status_detail';
478
+	    $insert_val.=",'".$message."'";
479 479
 	    
480
-	    $sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
480
+	    $sql='INSERT INTO '.$this->db_prefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
481 481
 	    
482 482
 	    switch ($this->trapsDB->trapDBType)
483 483
 	    {
484 484
 	        case 'pgsql':
485
-	            $sql .= ' RETURNING id;';
486
-	            $this->logging->log('sql : '.$sql,INFO);
485
+	            $sql.=' RETURNING id;';
486
+	            $this->logging->log('sql : '.$sql, INFO);
487 487
 	            if (($ret_code=$db_conn->query($sql)) === false) {
488
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
488
+	                $this->logging->log('Error SQL insert : '.$sql, 1, '');
489 489
 	            }
490
-	            $this->logging->log('SQL insertion OK',INFO );
490
+	            $this->logging->log('SQL insertion OK', INFO);
491 491
 	            // Get last id to insert oid/values in secondary table
492 492
 	            if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
493 493
 	                
494
-	                $this->logging->log('Erreur recuperation id',1,'');
494
+	                $this->logging->log('Erreur recuperation id', 1, '');
495 495
 	            }
496
-	            if (! isset($inserted_id_ret['id'])) {
497
-	                $this->logging->log('Error getting id',1,'');
496
+	            if (!isset($inserted_id_ret['id'])) {
497
+	                $this->logging->log('Error getting id', 1, '');
498 498
 	            }
499 499
 	            $this->trap_id=$inserted_id_ret['id'];
500 500
 	            break;
501 501
 	        case 'mysql':
502
-	            $sql .= ';';
503
-	            $this->logging->log('sql : '.$sql,INFO );
502
+	            $sql.=';';
503
+	            $this->logging->log('sql : '.$sql, INFO);
504 504
 	            if ($db_conn->query($sql) === false) {
505
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
505
+	                $this->logging->log('Error SQL insert : '.$sql, 1, '');
506 506
 	            }
507
-	            $this->logging->log('SQL insertion OK',INFO );
507
+	            $this->logging->log('SQL insertion OK', INFO);
508 508
 	            // Get last id to insert oid/values in secondary table
509 509
 	            $sql='SELECT LAST_INSERT_ID();';
510 510
 	            if (($ret_code=$db_conn->query($sql)) === false) {
511
-	                $this->logging->log('Erreur recuperation id',1,'');
511
+	                $this->logging->log('Erreur recuperation id', 1, '');
512 512
 	            }
513 513
 	            
514 514
 	            $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
515
-	            if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
515
+	            if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
516 516
 	            $this->trap_id=$inserted_id;
517 517
 	            break;
518 518
 	        default:
519
-	            $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
519
+	            $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType, 1, '');
520 520
 	    }
521 521
 	    
522
-	    $this->logging->log('id found: '. $this->trap_id,INFO );    
522
+	    $this->logging->log('id found: '.$this->trap_id, INFO);    
523 523
 	}
524 524
 	
525 525
 	/** Write trap data to trap database
@@ -536,86 +536,86 @@  discard block
 block discarded – undo
536 536
 		$insert_col='';
537 537
 		$insert_val='';
538 538
 		// add date time
539
-		$this->trap_data['date_received'] = date("Y-m-d H:i:s");
539
+		$this->trap_data['date_received']=date("Y-m-d H:i:s");
540 540
 
541 541
 		$firstcol=1;
542 542
 		foreach ($this->trap_data as $col => $val)
543 543
 		{
544
-			if ($firstcol==0) 
544
+			if ($firstcol == 0) 
545 545
 			{
546
-				$insert_col .=',';
547
-				$insert_val .=',';
546
+				$insert_col.=',';
547
+				$insert_val.=',';
548 548
 			}
549
-			$insert_col .= $col ;
550
-			$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
549
+			$insert_col.=$col;
550
+			$insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
551 551
 			$firstcol=0;
552 552
 		}
553 553
 		
554
-		$sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
554
+		$sql='INSERT INTO '.$this->db_prefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
555 555
 		switch ($this->trapsDB->trapDBType)
556 556
 		{
557 557
 			case 'pgsql': 
558
-				$sql .= ' RETURNING id;';
559
-				$this->logging->log('sql : '.$sql,INFO );
558
+				$sql.=' RETURNING id;';
559
+				$this->logging->log('sql : '.$sql, INFO);
560 560
 				if (($ret_code=$db_conn->query($sql)) === false) {
561
-					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
561
+					$this->logging->log('Error SQL insert : '.$sql, ERROR, '');
562 562
 				}
563
-				$this->logging->log('SQL insertion OK',INFO );
563
+				$this->logging->log('SQL insertion OK', INFO);
564 564
 				// Get last id to insert oid/values in secondary table
565 565
 				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
566 566
 														   
567
-					$this->logging->log('Erreur recuperation id',ERROR,'');
567
+					$this->logging->log('Erreur recuperation id', ERROR, '');
568 568
 				}
569
-				if (! isset($inserted_id_ret['id'])) {
570
-					$this->logging->log('Error getting id',ERROR,'');
569
+				if (!isset($inserted_id_ret['id'])) {
570
+					$this->logging->log('Error getting id', ERROR, '');
571 571
 				}
572 572
 				$this->trap_id=$inserted_id_ret['id'];
573 573
 			break;
574 574
 			case 'mysql': 
575
-				$sql .= ';';
576
-				$this->logging->log('sql : '.$sql,INFO );
575
+				$sql.=';';
576
+				$this->logging->log('sql : '.$sql, INFO);
577 577
 				if ($db_conn->query($sql) === false) {
578
-					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
578
+					$this->logging->log('Error SQL insert : '.$sql, ERROR, '');
579 579
 				}
580
-				$this->logging->log('SQL insertion OK',INFO );
580
+				$this->logging->log('SQL insertion OK', INFO);
581 581
 				// Get last id to insert oid/values in secondary table
582 582
 				$sql='SELECT LAST_INSERT_ID();';
583 583
 				if (($ret_code=$db_conn->query($sql)) === false) {
584
-					$this->logging->log('Erreur recuperation id',ERROR,'');
584
+					$this->logging->log('Erreur recuperation id', ERROR, '');
585 585
 				}
586 586
 
587 587
 				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
588
-				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
588
+				if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
589 589
 				$this->trap_id=$inserted_id;
590 590
 			break;
591 591
 			default: 
592
-				$this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
592
+				$this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType, ERROR, '');
593 593
 		}
594
-		$this->logging->log('id found: '.$this->trap_id,INFO );
594
+		$this->logging->log('id found: '.$this->trap_id, INFO);
595 595
 		
596 596
 		// Fill trap extended data table
597 597
 		foreach ($this->trap_data_ext as $value) {			
598 598
 			// TODO : detect if trap value is encoded and decode it to UTF-8 for database
599 599
 			$firstcol=1;
600
-			$value->trap_id = $this->trap_id;
600
+			$value->trap_id=$this->trap_id;
601 601
 			$insert_col='';
602 602
 			$insert_val='';
603 603
 			foreach ($value as $col => $val)
604 604
 			{
605
-				if ($firstcol==0) 
605
+				if ($firstcol == 0) 
606 606
 				{
607
-					$insert_col .=',';
608
-					$insert_val .=',';
607
+					$insert_col.=',';
608
+					$insert_val.=',';
609 609
 				}
610
-				$insert_col .= $col;
611
-				$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
610
+				$insert_col.=$col;
611
+				$insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
612 612
 				$firstcol=0;
613 613
 			}
614 614
 
615
-			$sql= 'INSERT INTO '.$this->db_prefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';			
615
+			$sql='INSERT INTO '.$this->db_prefix.'received_data ('.$insert_col.') VALUES ('.$insert_val.');';			
616 616
 
617 617
 			if ($db_conn->query($sql) === false) {
618
-				$this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
618
+				$this->logging->log('Erreur insertion data : '.$sql, WARN, '');
619 619
 			}	
620 620
 		}	
621 621
 	}
@@ -625,14 +625,14 @@  discard block
 block discarded – undo
625 625
 	*	@param $oid string oid in numeric
626 626
 	*	@return mixed|boolean : PDO object or false
627 627
 	*/	
628
-	protected function getRules($ip,$oid)
628
+	protected function getRules($ip, $oid)
629 629
 	{
630 630
 		$db_conn=$this->trapsDB->db_connect_trap();
631 631
 		// fetch rules based on IP in rule and OID
632 632
 		$sql='SELECT * from '.$this->db_prefix.'rules WHERE trap_oid=\''.$oid.'\' ';
633
-		$this->logging->log('SQL query : '.$sql,DEBUG );
633
+		$this->logging->log('SQL query : '.$sql, DEBUG);
634 634
 		if (($ret_code=$db_conn->query($sql)) === false) {
635
-			$this->logging->log('No result in query : ' . $sql,WARN,'');
635
+			$this->logging->log('No result in query : '.$sql, WARN, '');
636 636
 			return false;
637 637
 		}
638 638
 		$rules_all=$ret_code->fetchAll();
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
 		$rule_ret_key=0;
642 642
 		foreach ($rules_all as $key => $rule)
643 643
 		{
644
-			if ($rule['ip4']==$ip || $rule['ip6']==$ip)
644
+			if ($rule['ip4'] == $ip || $rule['ip6'] == $ip)
645 645
 			{
646 646
 				$rules_ret[$rule_ret_key]=$rules_all[$key];
647 647
 				//TODO : get host name by API (and check if correct in rule).
@@ -649,7 +649,7 @@  discard block
 block discarded – undo
649 649
 				continue;
650 650
 			}
651 651
 			// TODO : get hosts IP by API
652
-			if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
652
+			if (isset($rule['host_group_name']) && $rule['host_group_name'] != null)
653 653
 			{ // get ips of group members by oid
654 654
 				$db_conn2=$this->trapsDB->db_connect_ido();
655 655
 				$sql="SELECT m.host_object_id, a.address as ip4, a.address6 as ip6, b.name1 as host_name
@@ -660,15 +660,15 @@  discard block
 block discarded – undo
660 660
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
661 661
 						WHERE o.name1='".$rule['host_group_name']."';";
662 662
 				if (($ret_code2=$db_conn2->query($sql)) === false) {
663
-					$this->logging->log('No result in query : ' . $sql,WARN,'');
663
+					$this->logging->log('No result in query : '.$sql, WARN, '');
664 664
 					continue;
665 665
 				}
666 666
 				$grouphosts=$ret_code2->fetchAll();
667 667
 				//echo "rule grp :\n";print_r($grouphosts);echo "\n";
668
-				foreach ( $grouphosts as $host)
668
+				foreach ($grouphosts as $host)
669 669
 				{
670 670
 					//echo $host['ip4']."\n";
671
-					if ($host['ip4']==$ip || $host['ip6']==$ip)
671
+					if ($host['ip4'] == $ip || $host['ip6'] == $ip)
672 672
 					{
673 673
 						//echo "Rule added \n";
674 674
 						$rules_ret[$rule_ret_key]=$rules_all[$key];
@@ -691,7 +691,7 @@  discard block
 block discarded – undo
691 691
 		$db_conn=$this->trapsDB->db_connect_trap();
692 692
 		$sql="UPDATE ".$this->db_prefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
693 693
 		if ($db_conn->query($sql) === false) {
694
-			$this->logging->log('Error in update query : ' . $sql,WARN,'');
694
+			$this->logging->log('Error in update query : '.$sql, WARN, '');
695 695
 		}
696 696
 	}
697 697
 	
@@ -703,23 +703,23 @@  discard block
 block discarded – undo
703 703
 	 * @param string $display
704 704
 	 * @returnn bool true is service check was sent without error
705 705
 	*/
706
-	public function serviceCheckResult($host,$service,$state,$display)
706
+	public function serviceCheckResult($host, $service, $state, $display)
707 707
 	{
708 708
 	    if ($this->api_use === false)
709 709
 	    {
710
-    		$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
711
-    			$host.';' .$service .';' . $state . ';'.$display;
712
-    		$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
710
+    		$send='['.date('U').'] PROCESS_SERVICE_CHECK_RESULT;'.
711
+    			$host.';'.$service.';'.$state.';'.$display;
712
+    		$this->logging->log($send." : to : ".$this->icinga2cmd, INFO);
713 713
     		
714 714
     		// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
715
-    		exec('echo "'.$send.'" > ' .$this->icinga2cmd);
715
+    		exec('echo "'.$send.'" > '.$this->icinga2cmd);
716 716
     		return true;
717 717
 	    }
718 718
 	    else
719 719
 	    {
720 720
 	        // Get perfdata if found
721 721
 	        $matches=array();
722
-	        if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
722
+	        if (preg_match('/(.*)\|(.*)/', $display, $matches) == 1)
723 723
 	        {
724 724
 	            $display=$matches[1];
725 725
 	            $perfdata=$matches[2];
@@ -729,17 +729,17 @@  discard block
 block discarded – undo
729 729
 	            $perfdata='';
730 730
 	        }
731 731
 	        
732
-	        $api = $this->getAPI();
732
+	        $api=$this->getAPI();
733 733
 	        $api->setCredentials($this->api_username, $this->api_password);
734
-	        list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
734
+	        list($retcode, $retmessage)=$api->serviceCheckResult($host, $service, $state, $display, $perfdata);
735 735
 	        if ($retcode == false)
736 736
 	        {
737
-	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
737
+	            $this->logging->log("Error sending result : ".$retmessage, WARN, '');
738 738
 	            return false;
739 739
 	        }
740 740
 	        else 
741 741
 	        {
742
-	            $this->logging->log( "Sent result : " .$retmessage,INFO );
742
+	            $this->logging->log("Sent result : ".$retmessage, INFO);
743 743
 	            return true;
744 744
 	        }
745 745
 	    }
@@ -747,7 +747,7 @@  discard block
 block discarded – undo
747 747
 	
748 748
 	public function getHostByIP($ip)
749 749
 	{
750
-	    $api = $this->getAPI();
750
+	    $api=$this->getAPI();
751 751
 	    $api->setCredentials($this->api_username, $this->api_password);
752 752
 	    return $api->getHostByIP($ip);
753 753
 	}
@@ -760,32 +760,32 @@  discard block
 block discarded – undo
760 760
 	protected function applyDisplay($display)
761 761
 	{
762 762
 	    $matches=array();
763
-	    while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
763
+	    while (preg_match('/_OID\(([0-9\.]+)\)/', $display, $matches) == 1)
764 764
 		{
765 765
 			$oid=$matches[1];
766 766
 			$found=0;
767
-			foreach($this->trap_data_ext as $val)
767
+			foreach ($this->trap_data_ext as $val)
768 768
 			{
769 769
 				if ($oid == $val->oid)
770 770
 				{
771
-					$val->value=preg_replace('/"/','',$val->value);
771
+					$val->value=preg_replace('/"/', '', $val->value);
772 772
 					$rep=0;
773
-					$display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
774
-					if ($rep==0)
773
+					$display=preg_replace('/_OID\('.$oid.'\)/', $val->value, $display, -1, $rep);
774
+					if ($rep == 0)
775 775
 					{
776
-						$this->logging->log("Error in display",WARN,'');
776
+						$this->logging->log("Error in display", WARN, '');
777 777
 						return $display;
778 778
 					}
779 779
 					$found=1;
780 780
 					break;
781 781
 				}
782 782
 			}
783
-			if ($found==0)
783
+			if ($found == 0)
784 784
 			{
785
-				$display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
786
-				if ($rep==0)
785
+				$display=preg_replace('/_OID\('.$oid.'\)/', '<not in trap>', $display, -1, $rep);
786
+				if ($rep == 0)
787 787
 				{
788
-					$this->logging->log("Error in display",WARN,'');
788
+					$this->logging->log("Error in display", WARN, '');
789 789
 					return $display;
790 790
 				}				
791 791
 			}
@@ -797,11 +797,11 @@  discard block
 block discarded – undo
797 797
 	*/
798 798
 	public function applyRules()
799 799
 	{
800
-		$rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
800
+		$rules=$this->getRules($this->trap_data['source_ip'], $this->trap_data['trap_oid']);
801 801
 		
802
-		if ($rules===false || count($rules)==0)
802
+		if ($rules === false || count($rules) == 0)
803 803
 		{
804
-			$this->logging->log('No rules found for this trap',INFO );
804
+			$this->logging->log('No rules found for this trap', INFO);
805 805
 			$this->trap_data['status']='unknown';
806 806
 			$this->trap_to_db=true;
807 807
 			return;
@@ -816,59 +816,59 @@  discard block
 block discarded – undo
816 816
 			$service_name=$rule['service_name'];
817 817
 			
818 818
 			$display=$this->applyDisplay($rule['display']);
819
-			$this->trap_action = ($this->trap_action==null)? '' : $this->trap_action . ', ';
819
+			$this->trap_action=($this->trap_action == null) ? '' : $this->trap_action.', ';
820 820
 			try
821 821
 			{
822
-				$this->logging->log('Rule to eval : '.$rule['rule'],INFO );
823
-				$evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trap_data_ext) ;
822
+				$this->logging->log('Rule to eval : '.$rule['rule'], INFO);
823
+				$evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trap_data_ext);
824 824
 				//->eval_rule($rule['rule']);
825 825
 				
826 826
 				if ($evalr == true)
827 827
 				{
828 828
 					//$this->logging->log('rules OOK: '.print_r($rule),INFO );
829 829
 					$action=$rule['action_match'];
830
-					$this->logging->log('action OK : '.$action,INFO );
830
+					$this->logging->log('action OK : '.$action, INFO);
831 831
 					if ($action >= 0)
832 832
 					{
833
-						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
833
+						if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
834 834
 						{
835 835
 						    $this->trap_action.='Error sending status : check cmd/API';
836 836
 						}
837 837
 						else
838 838
 						{
839
-						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
839
+						    $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
840 840
 						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
841 841
 						}
842 842
 					}
843 843
 					else
844 844
 					{
845
-						$this->add_rule_match($rule['id'],$rule['num_match']+1);
845
+						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
846 846
 					}
847
-					$this->trap_to_db=($action==-2)?false:true;
847
+					$this->trap_to_db=($action == -2) ?false:true;
848 848
 				}
849 849
 				else
850 850
 				{
851 851
 					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
852 852
 					
853 853
 					$action=$rule['action_nomatch'];
854
-					$this->logging->log('action NOK : '.$action,INFO );
854
+					$this->logging->log('action NOK : '.$action, INFO);
855 855
 					if ($action >= 0)
856 856
 					{
857
-					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
857
+					    if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
858 858
 					    {
859 859
 					        $this->trap_action.='Error sending status : check cmd/API';
860 860
 					    }
861 861
 					    else
862 862
 					    {
863
-    						$this->add_rule_match($rule['id'],$rule['num_match']+1);
863
+    						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
864 864
     						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
865 865
 					    }
866 866
 					}
867 867
 					else
868 868
 					{
869
-						$this->add_rule_match($rule['id'],$rule['num_match']+1);
869
+						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
870 870
 					}
871
-					$this->trap_to_db=($action==-2)?false:true;					
871
+					$this->trap_to_db=($action == -2) ?false:true;					
872 872
 				}
873 873
 				// Put name in source_name
874 874
 				if (!isset($this->trap_data['source_name']))
@@ -877,7 +877,7 @@  discard block
 block discarded – undo
877 877
 				}
878 878
 				else
879 879
 				{
880
-					if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
880
+					if (!preg_match('/'.$rule['host_name'].'/', $this->trap_data['source_name']))
881 881
 					{ // only add if not present
882 882
 						$this->trap_data['source_name'].=','.$rule['host_name'];
883 883
 					}
@@ -885,13 +885,13 @@  discard block
 block discarded – undo
885 885
 			}
886 886
 			catch (Exception $e) 
887 887
 			{ 
888
-			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
888
+			    $this->logging->log('Error in rule eval : '.$e->getMessage(), WARN, '');
889 889
 			    $this->trap_action.=' ERR : '.$e->getMessage();
890 890
 			    $this->trap_data['status']='error';
891 891
 			}
892 892
 			
893 893
 		}
894
-		if ($this->trap_data['status']=='error')
894
+		if ($this->trap_data['status'] == 'error')
895 895
 		{
896 896
 		  $this->trap_to_db=true; // Always put errors in DB for the use can see
897 897
 		}
@@ -907,13 +907,13 @@  discard block
 block discarded – undo
907 907
 	public function add_rule_final($time)
908 908
 	{
909 909
 		$db_conn=$this->trapsDB->db_connect_trap();
910
-		if ($this->trap_action==null) 
910
+		if ($this->trap_action == null) 
911 911
 		{
912 912
 			$this->trap_action='No action';
913 913
 		}
914 914
 		$sql="UPDATE ".$this->db_prefix."received SET process_time = '".$time."' , status_detail='".$this->trap_action."'  WHERE (id = '".$this->trap_id."');";
915 915
 		if ($db_conn->query($sql) === false) {
916
-			$this->logging->log('Error in update query : ' . $sql,WARN,'');
916
+			$this->logging->log('Error in update query : '.$sql, WARN, '');
917 917
 		}
918 918
 	}
919 919
 	
@@ -936,7 +936,7 @@  discard block
 block discarded – undo
936 936
     WHERE s.current_state != 0;";
937 937
 		$db_conn=$this->trapsDB->db_connect_ido();
938 938
 		if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
939
-			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
939
+			$this->logging->log('No result in query : '.$sql_query, ERROR, '');
940 940
 			return 0;
941 941
 		}
942 942
 		$services=$services_db->fetchAll();
@@ -945,7 +945,7 @@  discard block
 block discarded – undo
945 945
 		$sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->db_prefix."rules where revert_ok != 0;";
946 946
 		$db_conn2=$this->trapsDB->db_connect_trap();
947 947
 		if (($rules_db=$db_conn2->query($sql_query)) === false) {
948
-			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
948
+			$this->logging->log('No result in query : '.$sql_query, ERROR, '');
949 949
 			return 0;
950 950
 		}
951 951
 		$rules=$rules_db->fetchAll();
@@ -961,13 +961,13 @@  discard block
 block discarded – undo
961 961
 					$service['host_name'] == $rule['host_name'] &&
962 962
 					($service['last_check'] + $rule['revert_ok']) < $now)
963 963
 				{
964
-					$this->serviceCheckResult($service['host_name'],$service['service_name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
964
+					$this->serviceCheckResult($service['host_name'], $service['service_name'], 0, 'Reset service to OK after '.$rule['revert_ok'].' seconds');
965 965
 					$numreset++;
966 966
 				}
967 967
 			}
968 968
 		}
969 969
 		echo "\n";
970
-		echo $numreset . " service(s) reset to OK\n";
970
+		echo $numreset." service(s) reset to OK\n";
971 971
 		return 0;
972 972
 		
973 973
 	}
Please login to merge, or discard this patch.
Braces   +40 added lines, -39 removed lines patch added patch discarded remove patch
@@ -73,9 +73,9 @@  discard block
 block discarded – undo
73 73
 		{
74 74
 		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
75 75
 		    $this->logSetup=true;
76
+		} else {
77
+				    $this->logSetup=false;
76 78
 		}
77
-		else
78
-		    $this->logSetup=false;
79 79
 		$this->logging->log('Loggin started', INFO);
80 80
 
81 81
 		// Get options from ini files
@@ -93,7 +93,10 @@  discard block
 block discarded – undo
93 93
 		$this->setupDatabase($trapConfig); // Setup database class
94 94
 		
95 95
 		$this->getDatabaseOptions(); // Get options in database
96
-		if ($this->api_use === true) $this->getAPI(); // Setup API
96
+		if ($this->api_use === true) {
97
+			$this->getAPI();
98
+		}
99
+		// Setup API
97 100
 		
98 101
 		$this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
99 102
 		
@@ -129,8 +132,7 @@  discard block
 block discarded – undo
129 132
 	        }
130 133
 	        $this->logging->log($message,$log_level);
131 134
 	        return false;
132
-	    }
133
-	    else
135
+	    } else
134 136
 	    {
135 137
 	        $option_var=$option_array[$option_category][$option_name];
136 138
 	        return true;
@@ -194,7 +196,10 @@  discard block
 block discarded – undo
194 196
 	    
195 197
 	    $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->db_prefix);
196 198
 	    
197
-	    if ($this->api_use === true) return; // In case of API use, no IDO is necessary
199
+	    if ($this->api_use === true) {
200
+	    	return;
201
+	    }
202
+	    // In case of API use, no IDO is necessary
198 203
         
199 204
 	    // IDO Database
200 205
 	    if (!array_key_exists('IDOdatabase',$trapConfig['config']))
@@ -219,9 +224,11 @@  discard block
 block discarded – undo
219 224
 	protected function getDatabaseOptions()
220 225
 	{
221 226
 		// Database options
222
-		if ($this->logSetup === false) // Only if logging was no setup in constructor
227
+		if ($this->logSetup === false) {
228
+			// Only if logging was no setup in constructor
223 229
 		{
224 230
     		$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
231
+		}
225 232
     		$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
226 233
     		$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
227 234
 		}
@@ -230,7 +237,9 @@  discard block
 block discarded – undo
230 237
 	protected function getDBConfigIfSet($element,&$variable)
231 238
 	{
232 239
 		$value=$this->getDBConfig($element);
233
-		if ($value != 'null') $variable=$value;
240
+		if ($value != 'null') {
241
+			$variable=$value;
242
+		}
234 243
 	}
235 244
 	
236 245
 	/** 
@@ -318,8 +327,7 @@  discard block
 block discarded – undo
318 327
 		{
319 328
 		    $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
320 329
 			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
321
-		} 
322
-		else 
330
+		} else 
323 331
 		{		
324 332
 			$this->trap_data['source_ip']=$matches[1];
325 333
 			$this->trap_data['destination_ip']=$matches[3];
@@ -334,14 +342,12 @@  discard block
 block discarded – undo
334 342
 			if ($ret_code===0 || $ret_code===false)
335 343
 			{
336 344
 				$this->logging->log('No match on trap data : '.$vars,WARN,'');
337
-			}
338
-			else 
345
+			} else 
339 346
 			{
340 347
 			    if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
341 348
 				{
342 349
 					$this->trap_data['trap_oid']=$matches[2];
343
-				}
344
-				else
350
+				} else
345 351
 				{
346 352
 					$object= new stdClass;
347 353
 					$object->oid =$matches[1];
@@ -512,7 +518,9 @@  discard block
 block discarded – undo
512 518
 	            }
513 519
 	            
514 520
 	            $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
515
-	            if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
521
+	            if ($inserted_id==false) {
522
+	            	throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
523
+	            }
516 524
 	            $this->trap_id=$inserted_id;
517 525
 	            break;
518 526
 	        default:
@@ -528,7 +536,9 @@  discard block
 block discarded – undo
528 536
 	{
529 537
 		
530 538
 		// If action is ignore -> don't send t DB
531
-		if ($this->trap_to_db === false) return;
539
+		if ($this->trap_to_db === false) {
540
+			return;
541
+		}
532 542
 		
533 543
 		
534 544
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -585,7 +595,9 @@  discard block
 block discarded – undo
585 595
 				}
586 596
 
587 597
 				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
588
-				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
598
+				if ($inserted_id==false) {
599
+					throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
600
+				}
589 601
 				$this->trap_id=$inserted_id;
590 602
 			break;
591 603
 			default: 
@@ -714,8 +726,7 @@  discard block
 block discarded – undo
714 726
     		// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
715 727
     		exec('echo "'.$send.'" > ' .$this->icinga2cmd);
716 728
     		return true;
717
-	    }
718
-	    else
729
+	    } else
719 730
 	    {
720 731
 	        // Get perfdata if found
721 732
 	        $matches=array();
@@ -723,8 +734,7 @@  discard block
 block discarded – undo
723 734
 	        {
724 735
 	            $display=$matches[1];
725 736
 	            $perfdata=$matches[2];
726
-	        }
727
-	        else
737
+	        } else
728 738
 	        {
729 739
 	            $perfdata='';
730 740
 	        }
@@ -736,8 +746,7 @@  discard block
 block discarded – undo
736 746
 	        {
737 747
 	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
738 748
 	            return false;
739
-	        }
740
-	        else 
749
+	        } else 
741 750
 	        {
742 751
 	            $this->logging->log( "Sent result : " .$retmessage,INFO );
743 752
 	            return true;
@@ -833,20 +842,17 @@  discard block
 block discarded – undo
833 842
 						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
834 843
 						{
835 844
 						    $this->trap_action.='Error sending status : check cmd/API';
836
-						}
837
-						else
845
+						} else
838 846
 						{
839 847
 						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
840 848
 						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
841 849
 						}
842
-					}
843
-					else
850
+					} else
844 851
 					{
845 852
 						$this->add_rule_match($rule['id'],$rule['num_match']+1);
846 853
 					}
847 854
 					$this->trap_to_db=($action==-2)?false:true;
848
-				}
849
-				else
855
+				} else
850 856
 				{
851 857
 					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
852 858
 					
@@ -857,14 +863,12 @@  discard block
 block discarded – undo
857 863
 					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
858 864
 					    {
859 865
 					        $this->trap_action.='Error sending status : check cmd/API';
860
-					    }
861
-					    else
866
+					    } else
862 867
 					    {
863 868
     						$this->add_rule_match($rule['id'],$rule['num_match']+1);
864 869
     						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
865 870
 					    }
866
-					}
867
-					else
871
+					} else
868 872
 					{
869 873
 						$this->add_rule_match($rule['id'],$rule['num_match']+1);
870 874
 					}
@@ -874,16 +878,14 @@  discard block
 block discarded – undo
874 878
 				if (!isset($this->trap_data['source_name']))
875 879
 				{
876 880
 					$this->trap_data['source_name']=$rule['host_name'];
877
-				}
878
-				else
881
+				} else
879 882
 				{
880 883
 					if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
881 884
 					{ // only add if not present
882 885
 						$this->trap_data['source_name'].=','.$rule['host_name'];
883 886
 					}
884 887
 				}
885
-			}
886
-			catch (Exception $e) 
888
+			} catch (Exception $e) 
887 889
 			{ 
888 890
 			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
889 891
 			    $this->trap_action.=' ERR : '.$e->getMessage();
@@ -894,8 +896,7 @@  discard block
 block discarded – undo
894 896
 		if ($this->trap_data['status']=='error')
895 897
 		{
896 898
 		  $this->trap_to_db=true; // Always put errors in DB for the use can see
897
-		}
898
-		else
899
+		} else
899 900
 		{
900 901
 		  $this->trap_data['status']='done';
901 902
 		}
Please login to merge, or discard this patch.