Passed
Push — master ( 782f23...8a769b )
by Patrick
02:09
created
library/Trapdirector/TrapsProcess/Rule.php 1 patch
Indentation   +253 added lines, -253 removed lines patch added patch discarded remove patch
@@ -6,291 +6,291 @@
 block discarded – undo
6 6
 
7 7
 class Rule
8 8
 {
9
-    use \RuleUtils;
9
+	use \RuleUtils;
10 10
     
11
-    /** @var Logging $logging logging class*/
12
-    protected $logging;
11
+	/** @var Logging $logging logging class*/
12
+	protected $logging;
13 13
     
14
-    /** @var Trap $trapClass */
15
-    protected $trapClass;
14
+	/** @var Trap $trapClass */
15
+	protected $trapClass;
16 16
     
17 17
 
18
-    /**
19
-     * Setup Rule Class
20
-     * @param Trap $trapClass : To get logging class & plugin class
21
-     */
22
-    function __construct($trapClass)
23
-    {
24
-        $this->trapClass=$trapClass;
25
-        $this->logging=$trapClass->logging;
26
-    }
18
+	/**
19
+	 * Setup Rule Class
20
+	 * @param Trap $trapClass : To get logging class & plugin class
21
+	 */
22
+	function __construct($trapClass)
23
+	{
24
+		$this->trapClass=$trapClass;
25
+		$this->logging=$trapClass->logging;
26
+	}
27 27
     
28 28
     
29
-    protected function eval_getElement($rule,&$item)
30
-    {
31
-        if ($item >= strlen($rule))
32
-        {
33
-            throw new Exception("Early end of string ".$rule ." at " .$item );
34
-        }
35
-        while ($rule[$item]==' ') $item++;
36
-        if (preg_match('/[\-0-9\.]/',$rule[$item]))
37
-        { // number
38
-            return $this->get_number($rule, $item);
39
-        }
40
-        if ($rule[$item] == '"')
41
-        { // string
42
-            return $this->get_string($rule, $item);
43
-        }
29
+	protected function eval_getElement($rule,&$item)
30
+	{
31
+		if ($item >= strlen($rule))
32
+		{
33
+			throw new Exception("Early end of string ".$rule ." at " .$item );
34
+		}
35
+		while ($rule[$item]==' ') $item++;
36
+		if (preg_match('/[\-0-9\.]/',$rule[$item]))
37
+		{ // number
38
+			return $this->get_number($rule, $item);
39
+		}
40
+		if ($rule[$item] == '"')
41
+		{ // string
42
+			return $this->get_string($rule, $item);
43
+		}
44 44
         
45
-        if ($rule[$item] == '(')
46
-        { // grouping
47
-            return $this->get_group($rule, $item);
48
-        }
49
-        if ($rule[$item] == '_')
50
-        { // function
51
-            return $this->get_function($rule, $item);
52
-        }
53
-        throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
45
+		if ($rule[$item] == '(')
46
+		{ // grouping
47
+			return $this->get_group($rule, $item);
48
+		}
49
+		if ($rule[$item] == '_')
50
+		{ // function
51
+			return $this->get_function($rule, $item);
52
+		}
53
+		throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
54 54
         
55
-    }
55
+	}
56 56
     
57
-    protected function eval_getNext($rule,$item,$tok)
58
-    {
59
-        while (
60
-            ($rule[$item] != $tok ) 
61
-            && ($item < strlen($rule))) 
62
-        { 
63
-            $item++;
64
-        }
65
-        if ($item==strlen($rule)) {
66
-            throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
67
-        }
68
-        return $item+1;
69
-    }
57
+	protected function eval_getNext($rule,$item,$tok)
58
+	{
59
+		while (
60
+			($rule[$item] != $tok ) 
61
+			&& ($item < strlen($rule))) 
62
+		{ 
63
+			$item++;
64
+		}
65
+		if ($item==strlen($rule)) {
66
+			throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
67
+		}
68
+		return $item+1;
69
+	}
70 70
     
71
-    protected function eval_getOper($rule,&$item)
72
-    {
73
-        while ($rule[$item]==' ') $item++;
74
-        switch ($rule[$item])
75
-        {
76
-            case '<':
77
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
78
-                $item++; return array(0,"<");
79
-            case '>':
80
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
81
-                $item++; return array(0,">");
82
-            case '=':
83
-                $item++; return array(0,"=");
84
-            case '!':
85
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
86
-                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
87
-            case '~':
88
-                $item++; return array(0,"~");
89
-            case '|':
90
-                $item++; return array(1,"|");
91
-            case '&':
92
-                $item++; return array(1,"&");
93
-            default	:
94
-                throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
95
-        }
96
-    }
71
+	protected function eval_getOper($rule,&$item)
72
+	{
73
+		while ($rule[$item]==' ') $item++;
74
+		switch ($rule[$item])
75
+		{
76
+			case '<':
77
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
78
+				$item++; return array(0,"<");
79
+			case '>':
80
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
81
+				$item++; return array(0,">");
82
+			case '=':
83
+				$item++; return array(0,"=");
84
+			case '!':
85
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
86
+				throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
87
+			case '~':
88
+				$item++; return array(0,"~");
89
+			case '|':
90
+				$item++; return array(1,"|");
91
+			case '&':
92
+				$item++; return array(1,"&");
93
+			default	:
94
+				throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
95
+		}
96
+	}
97 97
     
98
-    private function check_negate_first($rule,&$item)
99
-    {
100
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
101
-        {
102
-            $item++;
103
-            return true;
104
-        }
105
-        else
106
-        {
107
-            return false;
108
-        }
109
-    }
98
+	private function check_negate_first($rule,&$item)
99
+	{
100
+		if ( $rule[$item] == '!') // If '!' found, negate next expression.
101
+		{
102
+			$item++;
103
+			return true;
104
+		}
105
+		else
106
+		{
107
+			return false;
108
+		}
109
+	}
110 110
 
111
-    private function do_compare($val1,$val2,$comp,$negate)
112
-    {
113
-        switch ($comp){
114
-            case '<':	$retVal= ($val1 < $val2); break;
115
-            case '<=':	$retVal= ($val1 <= $val2); break;
116
-            case '>':	$retVal= ($val1 > $val2); break;
117
-            case '>=':	$retVal= ($val1 >= $val2); break;
118
-            case '=':	$retVal= ($val1 == $val2); break;
119
-            case '!=':	$retVal= ($val1 != $val2); break;
120
-            case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
121
-            case '|':	$retVal= ($val1 || $val2); break;
122
-            case '&':	$retVal= ($val1 && $val2); break;
123
-            default:  throw new Exception("Error in expression - unknown comp : ".$comp);
124
-        }
125
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
111
+	private function do_compare($val1,$val2,$comp,$negate)
112
+	{
113
+		switch ($comp){
114
+			case '<':	$retVal= ($val1 < $val2); break;
115
+			case '<=':	$retVal= ($val1 <= $val2); break;
116
+			case '>':	$retVal= ($val1 > $val2); break;
117
+			case '>=':	$retVal= ($val1 >= $val2); break;
118
+			case '=':	$retVal= ($val1 == $val2); break;
119
+			case '!=':	$retVal= ($val1 != $val2); break;
120
+			case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
121
+			case '|':	$retVal= ($val1 || $val2); break;
122
+			case '&':	$retVal= ($val1 && $val2); break;
123
+			default:  throw new Exception("Error in expression - unknown comp : ".$comp);
124
+		}
125
+		if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
126 126
         
127
-        return $retVal;
128
-    }
127
+		return $retVal;
128
+	}
129 129
     
130
-    /** Evaluation : makes token and evaluate.
131
-     *	Public function for expressions testing
132
-     *	accepts : < > = <= >= !=  (typec = 0)
133
-     *	operators : & | (typec=1)
134
-     *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
135
-     *   comparison int vs strings will return null (error)
136
-     *	return : bool or null on error
137
-     */
138
-    public function evaluation($rule,&$item)
139
-    {
140
-        //echo "Evaluation of ".substr($rule,$item)."\n";
141
-        $negate=$this->check_negate_first($rule, $item);
142
-        // First element : number, string or ()
143
-        list($type1,$val1) = $this->eval_getElement($rule,$item);
144
-        //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
130
+	/** Evaluation : makes token and evaluate.
131
+	 *	Public function for expressions testing
132
+	 *	accepts : < > = <= >= !=  (typec = 0)
133
+	 *	operators : & | (typec=1)
134
+	 *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
135
+	 *   comparison int vs strings will return null (error)
136
+	 *	return : bool or null on error
137
+	 */
138
+	public function evaluation($rule,&$item)
139
+	{
140
+		//echo "Evaluation of ".substr($rule,$item)."\n";
141
+		$negate=$this->check_negate_first($rule, $item);
142
+		// First element : number, string or ()
143
+		list($type1,$val1) = $this->eval_getElement($rule,$item);
144
+		//echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
145 145
         
146
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
147
-        {
148
-            if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
149
-            if ($negate === true) $val1= ! $val1;
150
-            return $val1;
151
-        }
146
+		if ($item==strlen($rule)) // If only element, return value, but only boolean
147
+		{
148
+			if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
149
+			if ($negate === true) $val1= ! $val1;
150
+			return $val1;
151
+		}
152 152
         
153
-        // Second element : operator
154
-        list($typec,$comp) = $this->eval_getOper($rule,$item);
155
-        //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
153
+		// Second element : operator
154
+		list($typec,$comp) = $this->eval_getOper($rule,$item);
155
+		//echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
156 156
         
157
-        // Third element : number, string or ()
158
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
159
-        {
160
-            $item++;
161
-            if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
162
-            $val2= ! $this->evaluation($rule,$item);
163
-            $type2=2; // result is a boolean
164
-        }
165
-        else
166
-        {
167
-            list($type2,$val2) = $this->eval_getElement($rule,$item);
168
-        }
169
-        //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
157
+		// Third element : number, string or ()
158
+		if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
159
+		{
160
+			$item++;
161
+			if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
162
+			$val2= ! $this->evaluation($rule,$item);
163
+			$type2=2; // result is a boolean
164
+		}
165
+		else
166
+		{
167
+			list($type2,$val2) = $this->eval_getElement($rule,$item);
168
+		}
169
+		//echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
170 170
         
171
-        if ($type1!=$type2)  // cannot compare different types
172
-        {
173
-            throw new Exception("Cannot compare string & number : ".$rule);
174
-        }
175
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
176
-        {
177
-            throw new Exception("Cannot use boolean operators with string & number : ".$rule);
178
-        }
171
+		if ($type1!=$type2)  // cannot compare different types
172
+		{
173
+			throw new Exception("Cannot compare string & number : ".$rule);
174
+		}
175
+		if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
176
+		{
177
+			throw new Exception("Cannot use boolean operators with string & number : ".$rule);
178
+		}
179 179
         
180
-        $retVal = $this->do_compare($val1, $val2, $comp, $negate);
180
+		$retVal = $this->do_compare($val1, $val2, $comp, $negate);
181 181
         
182
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
183
-        // check for logical operator :
184
-        switch ($rule[$item])
185
-        {
186
-            case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
187
-            case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
182
+		if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
183
+		// check for logical operator :
184
+		switch ($rule[$item])
185
+		{
186
+			case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
187
+			case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
188 188
             
189
-            default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
190
-        }
191
-    }
189
+			default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
190
+		}
191
+	}
192 192
     
193
-    // Remove all whitespaces (when not quoted)
194
-    public function eval_cleanup($rule)
195
-    {
196
-        $item=0;
197
-        $rule2='';
198
-        while ($item < strlen($rule))
199
-        {
200
-            if ($rule[$item]==' ') { $item++; continue; }
201
-            if ($rule[$item]=='"')
202
-            {
203
-                $rule2.=$rule[$item];
204
-                $item++;
205
-                while (($item < strlen($rule)) && ($rule[$item]!='"') )
206
-                {
207
-                    $rule2.=$rule[$item];
208
-                    $item++;
209
-                }
210
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
211
-                $rule2.=$rule[$item];
212
-                $item++;
213
-                continue;
214
-            }
193
+	// Remove all whitespaces (when not quoted)
194
+	public function eval_cleanup($rule)
195
+	{
196
+		$item=0;
197
+		$rule2='';
198
+		while ($item < strlen($rule))
199
+		{
200
+			if ($rule[$item]==' ') { $item++; continue; }
201
+			if ($rule[$item]=='"')
202
+			{
203
+				$rule2.=$rule[$item];
204
+				$item++;
205
+				while (($item < strlen($rule)) && ($rule[$item]!='"') )
206
+				{
207
+					$rule2.=$rule[$item];
208
+					$item++;
209
+				}
210
+				if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
211
+				$rule2.=$rule[$item];
212
+				$item++;
213
+				continue;
214
+			}
215 215
             
216
-            $rule2.=$rule[$item];
217
-            $item++;
218
-        }
216
+			$rule2.=$rule[$item];
217
+			$item++;
218
+		}
219 219
         
220
-        return $rule2;
221
-    }
220
+		return $rule2;
221
+	}
222 222
 
223 223
 
224
-    /**
225
-     * Get '*' or '**' and transform in [0-9]+ or .* in return string
226
-     * @param string $oid OID in normal or regexp format. '*' will be escaped ('\*')
227
-     * @return string correct regexp format
228
-     */
229
-    public function regexp_eval(string &$oid)
230
-    {
231
-        // ** replaced by .*
232
-        $oidR=preg_replace('/\*\*/', '.*', $oid);
233
-        // * replaced by [0-9]+
234
-        $oidR=preg_replace('/\*/', '[0-9]+', $oidR);
224
+	/**
225
+	 * Get '*' or '**' and transform in [0-9]+ or .* in return string
226
+	 * @param string $oid OID in normal or regexp format. '*' will be escaped ('\*')
227
+	 * @return string correct regexp format
228
+	 */
229
+	public function regexp_eval(string &$oid)
230
+	{
231
+		// ** replaced by .*
232
+		$oidR=preg_replace('/\*\*/', '.*', $oid);
233
+		// * replaced by [0-9]+
234
+		$oidR=preg_replace('/\*/', '[0-9]+', $oidR);
235 235
         
236
-        // replace * with \* in oid for preg_replace
237
-        $oid=preg_replace('/\*/', '\*', $oid);
236
+		// replace * with \* in oid for preg_replace
237
+		$oid=preg_replace('/\*/', '\*', $oid);
238 238
         
239
-        $this->logging->log('Regexp eval : '.$oid.' / '.$oidR,DEBUG );
239
+		$this->logging->log('Regexp eval : '.$oid.' / '.$oidR,DEBUG );
240 240
         
241
-        return $oidR;
242
-    }
241
+		return $oidR;
242
+	}
243 243
     
244 244
     
245
-    /** Evaluation rule (uses eval_* functions recursively)
246
-     *	@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) )
247
-     *  @param array $oidList : OIDs values to sustitute.
248
-     *	@return bool : true : rule match, false : rule don't match , throw exception on error.
249
-     */   
250
-    public function eval_rule($rule,$oidList)
251
-    {
252
-        if ($rule==null || $rule == '') // Empty rule is always true
253
-        {
254
-            return true;
255
-        }
256
-        $matches=array();
257
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
258
-        {
259
-            $oid=$matches[1];
260
-            $found=0;
261
-            // Test and transform regexp
262
-            $oidR = $this->regexp_eval($oid);
245
+	/** Evaluation rule (uses eval_* functions recursively)
246
+	 *	@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) )
247
+	 *  @param array $oidList : OIDs values to sustitute.
248
+	 *	@return bool : true : rule match, false : rule don't match , throw exception on error.
249
+	 */   
250
+	public function eval_rule($rule,$oidList)
251
+	{
252
+		if ($rule==null || $rule == '') // Empty rule is always true
253
+		{
254
+			return true;
255
+		}
256
+		$matches=array();
257
+		while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
258
+		{
259
+			$oid=$matches[1];
260
+			$found=0;
261
+			// Test and transform regexp
262
+			$oidR = $this->regexp_eval($oid);
263 263
             
264
-            foreach($oidList as $val)
265
-            {
266
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
267
-                {
268
-                    if (!preg_match('/^-?[0-9]*\.?[0-9]+$/',$val->value))
269
-                    { // If not a number, change " to ' and put " around it
270
-                        $val->value=preg_replace('/"/',"'",$val->value);
271
-                        $val->value='"'.$val->value.'"';
272
-                    }
273
-                    $rep=0;
274
-                    $rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
275
-                    if ($rep==0)
276
-                    {
277
-                        $this->logging->log("Error in rule_eval",WARN,'');
278
-                        return false;
279
-                    }
280
-                    $found=1;
281
-                    break;
282
-                }
283
-            }
284
-            if ($found==0)
285
-            {	// OID not found : throw error
286
-                throw new Exception('OID '.$oid.' not found in trap');
287
-            }
288
-        }
289
-        $item=0;
290
-        $rule=$this->eval_cleanup($rule);
291
-        $this->logging->log('Rule after clenup: '.$rule,INFO );
264
+			foreach($oidList as $val)
265
+			{
266
+				if (preg_match("/^$oidR$/",$val->oid) == 1)
267
+				{
268
+					if (!preg_match('/^-?[0-9]*\.?[0-9]+$/',$val->value))
269
+					{ // If not a number, change " to ' and put " around it
270
+						$val->value=preg_replace('/"/',"'",$val->value);
271
+						$val->value='"'.$val->value.'"';
272
+					}
273
+					$rep=0;
274
+					$rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
275
+					if ($rep==0)
276
+					{
277
+						$this->logging->log("Error in rule_eval",WARN,'');
278
+						return false;
279
+					}
280
+					$found=1;
281
+					break;
282
+				}
283
+			}
284
+			if ($found==0)
285
+			{	// OID not found : throw error
286
+				throw new Exception('OID '.$oid.' not found in trap');
287
+			}
288
+		}
289
+		$item=0;
290
+		$rule=$this->eval_cleanup($rule);
291
+		$this->logging->log('Rule after clenup: '.$rule,INFO );
292 292
         
293
-        return  $this->evaluation($rule,$item);
294
-    }
293
+		return  $this->evaluation($rule,$item);
294
+	}
295 295
     
296 296
 }
297 297
\ No newline at end of file
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/RuleUtils.php 1 patch
Indentation   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -12,126 +12,126 @@
 block discarded – undo
12 12
 trait RuleUtils
13 13
 {
14 14
 
15
-    /**
16
-     * Get full number
17
-     * @param string $rule Rule as string
18
-     * @param int item current eval position
19
-     * @return array<int,string>
20
-     */
21
-    private function get_number(string $rule,int &$item)
22
-    {
23
-        $item2=$item+1;
24
-        while (
25
-            ($item2!=strlen($rule))
26
-            && (preg_match('/[\-0-9\.]/',$rule[$item2])))
27
-        {
28
-            $item2++ ;
29
-        }
30
-        $val=substr($rule,$item,$item2-$item);
31
-        $item=$item2;
32
-        //echo "number ".$val."\n";
15
+	/**
16
+	 * Get full number
17
+	 * @param string $rule Rule as string
18
+	 * @param int item current eval position
19
+	 * @return array<int,string>
20
+	 */
21
+	private function get_number(string $rule,int &$item)
22
+	{
23
+		$item2=$item+1;
24
+		while (
25
+			($item2!=strlen($rule))
26
+			&& (preg_match('/[\-0-9\.]/',$rule[$item2])))
27
+		{
28
+			$item2++ ;
29
+		}
30
+		$val=substr($rule,$item,$item2-$item);
31
+		$item=$item2;
32
+		//echo "number ".$val."\n";
33 33
         
34
-        return array(0,$val);
35
-    }
34
+		return array(0,$val);
35
+	}
36 36
 
37
-    /**
38
-     * Get a string (between ") 
39
-     * @param string $rule Rule as string
40
-     * @param int item current eval position
41
-     * @return array<int,string>
42
-     */
43
-    private function get_string(string $rule,int &$item)
44
-    {
45
-        $item++;
46
-        $item2=$this->eval_getNext($rule,$item,'"');
47
-        $val=substr($rule,$item,$item2-$item-1);
48
-        $item=$item2;
49
-        //echo "string : ".$val."\n";
50
-        return array(1,$val);
37
+	/**
38
+	 * Get a string (between ") 
39
+	 * @param string $rule Rule as string
40
+	 * @param int item current eval position
41
+	 * @return array<int,string>
42
+	 */
43
+	private function get_string(string $rule,int &$item)
44
+	{
45
+		$item++;
46
+		$item2=$this->eval_getNext($rule,$item,'"');
47
+		$val=substr($rule,$item,$item2-$item-1);
48
+		$item=$item2;
49
+		//echo "string : ".$val."\n";
50
+		return array(1,$val);
51 51
         
52
-    }
52
+	}
53 53
     
54
-    /**
55
-     * Parse elements inside () : jumps over "" and count parenthesis.
56
-     * Ex : ( "test" != ")test" & (1==2) ) will return "test" != ")test" & (1==2)
57
-     * @param string $rule : the current rule
58
-     * @param int $item : actual position in rule
59
-     * @throws Exception
60
-     * @return string : everything inside parenthesis
61
-     */
62
-    private function parse_parenthesis(string $rule,int &$item) : string
63
-    {
64
-        $item++;
65
-        $start=$item;
66
-        $parenthesis_count=0;
67
-        while (($item < strlen($rule)) // Not end of string AND
68
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
69
-        {
70
-            if ($rule[$item] == '"' )
71
-            { // pass through string
72
-                $item++;
73
-                $item=$this->eval_getNext($rule,$item,'"');
74
-            }
75
-            else{
76
-                if ($rule[$item] == '(')
77
-                {
78
-                    $parenthesis_count++;
79
-                }
80
-                if ($rule[$item] == ')')
81
-                {
82
-                    $parenthesis_count--;
83
-                }
84
-                $item++;
85
-            }
86
-        }
54
+	/**
55
+	 * Parse elements inside () : jumps over "" and count parenthesis.
56
+	 * Ex : ( "test" != ")test" & (1==2) ) will return "test" != ")test" & (1==2)
57
+	 * @param string $rule : the current rule
58
+	 * @param int $item : actual position in rule
59
+	 * @throws Exception
60
+	 * @return string : everything inside parenthesis
61
+	 */
62
+	private function parse_parenthesis(string $rule,int &$item) : string
63
+	{
64
+		$item++;
65
+		$start=$item;
66
+		$parenthesis_count=0;
67
+		while (($item < strlen($rule)) // Not end of string AND
68
+			&& ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
69
+		{
70
+			if ($rule[$item] == '"' )
71
+			{ // pass through string
72
+				$item++;
73
+				$item=$this->eval_getNext($rule,$item,'"');
74
+			}
75
+			else{
76
+				if ($rule[$item] == '(')
77
+				{
78
+					$parenthesis_count++;
79
+				}
80
+				if ($rule[$item] == ')')
81
+				{
82
+					$parenthesis_count--;
83
+				}
84
+				$item++;
85
+			}
86
+		}
87 87
         
88
-        if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
89
-        $val=substr($rule,$start,$item-$start);
90
-        $item++;
91
-        return $val;
92
-    }
88
+		if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
89
+		$val=substr($rule,$start,$item-$start);
90
+		$item++;
91
+		return $val;
92
+	}
93 93
 
94
-    /**
95
-     * Get and eval a grouped condition - ex : (1==1)
96
-     * @param string $rule
97
-     * @param int $item
98
-     * @return array<int,string>
99
-     */
100
-    private function get_group(string $rule,int &$item) : array
101
-    {
102
-        // gets eveything inside parenthesis
103
-        $val=$this->parse_parenthesis($rule, $item);
104
-        // Returns boolean with evaluation of all inside parenthesis
105
-        $start=0;
106
-        return array(2,$this->evaluation($val,$start));
107
-    }
94
+	/**
95
+	 * Get and eval a grouped condition - ex : (1==1)
96
+	 * @param string $rule
97
+	 * @param int $item
98
+	 * @return array<int,string>
99
+	 */
100
+	private function get_group(string $rule,int &$item) : array
101
+	{
102
+		// gets eveything inside parenthesis
103
+		$val=$this->parse_parenthesis($rule, $item);
104
+		// Returns boolean with evaluation of all inside parenthesis
105
+		$start=0;
106
+		return array(2,$this->evaluation($val,$start));
107
+	}
108 108
     
109
-    /**
110
-     * @param string $rule
111
-     * @param int $item
112
-     * @throws Exception
113
-     * @return array<int,string>
114
-     */
115
-    private function get_function(string $rule,int &$item) : array
116
-    {
117
-        // function is : __function(param1,param2...)
118
-        $start=$item;
119
-        while (($item < strlen($rule)) && ($rule[$item] != '(' )) // Not end of string AND not opening '('
120
-        {
121
-            $item++;
122
-        }
123
-        if ($item==strlen($rule)) {throw new Exception("no opening () for function in ".$rule ." at " .$item);}
109
+	/**
110
+	 * @param string $rule
111
+	 * @param int $item
112
+	 * @throws Exception
113
+	 * @return array<int,string>
114
+	 */
115
+	private function get_function(string $rule,int &$item) : array
116
+	{
117
+		// function is : __function(param1,param2...)
118
+		$start=$item;
119
+		while (($item < strlen($rule)) && ($rule[$item] != '(' )) // Not end of string AND not opening '('
120
+		{
121
+			$item++;
122
+		}
123
+		if ($item==strlen($rule)) {throw new Exception("no opening () for function in ".$rule ." at " .$item);}
124 124
         
125
-        // get parameters between parenthesis
125
+		// get parameters between parenthesis
126 126
         
127
-        $this->parse_parenthesis($rule, $item);
127
+		$this->parse_parenthesis($rule, $item);
128 128
         
129
-        $val=substr($rule,$start,$item-$start);
129
+		$val=substr($rule,$start,$item-$start);
130 130
         
131
-        $this->logging->log('got function ' . $val,DEBUG);
131
+		$this->logging->log('got function ' . $val,DEBUG);
132 132
         
133
-        return array(2,$this->trapClass->pluginClass->evaluateFunctionString($val));
133
+		return array(2,$this->trapClass->pluginClass->evaluateFunctionString($val));
134 134
         
135
-    }
135
+	}
136 136
     
137 137
 }
138 138
\ No newline at end of file
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/MibDatabase.php 1 patch
Indentation   +154 added lines, -154 removed lines patch added patch discarded remove patch
@@ -12,183 +12,183 @@
 block discarded – undo
12 12
  */
13 13
 trait MibDatabase
14 14
 {   
15
-    /** @var array $oidDesc MUST be overide by calling class */
16
-    //protected $oidDesc;
15
+	/** @var array $oidDesc MUST be overide by calling class */
16
+	//protected $oidDesc;
17 17
     
18
-    /** @var array $dbOidIndex MUST be overide by calling class */
19
-    //protected $dbOidIndex;
18
+	/** @var array $dbOidIndex MUST be overide by calling class */
19
+	//protected $dbOidIndex;
20 20
     
21
-    /** @return \Trapdirector\Logging */
22
-    abstract public function getLogging();
21
+	/** @return \Trapdirector\Logging */
22
+	abstract public function getLogging();
23 23
     
24
-    /** @return \Trapdirector\Database */
25
-    abstract public function getTrapsDB();
24
+	/** @return \Trapdirector\Database */
25
+	abstract public function getTrapsDB();
26 26
 
27 27
     
28
-    /**
29
-     * Update or add an OID to database uses $this->dbOidIndex for mem cache
30
-     * and $this->oidDesc doe data
31
-     * @return number : 0=unchanged, 1 = changed, 2=created
32
-     */
33
-    public function update_oid()
34
-    {
35
-        $db_conn=$this->getTrapsDB()->db_connect_trap();
36
-        // Quote description.
37
-        $this->oidDesc['description']=$db_conn->quote($this->oidDesc['description']);
28
+	/**
29
+	 * Update or add an OID to database uses $this->dbOidIndex for mem cache
30
+	 * and $this->oidDesc doe data
31
+	 * @return number : 0=unchanged, 1 = changed, 2=created
32
+	 */
33
+	public function update_oid()
34
+	{
35
+		$db_conn=$this->getTrapsDB()->db_connect_trap();
36
+		// Quote description.
37
+		$this->oidDesc['description']=$db_conn->quote($this->oidDesc['description']);
38 38
         
39
-        if (isset($this->dbOidIndex[$this->oidDesc['oid']]))
40
-        { // oid exists in db, so update
41
-            return $this->update_oid_update();
42
-        }
43
-        // create new OID.
44
-        return $this->update_oid_create();
39
+		if (isset($this->dbOidIndex[$this->oidDesc['oid']]))
40
+		{ // oid exists in db, so update
41
+			return $this->update_oid_update();
42
+		}
43
+		// create new OID.
44
+		return $this->update_oid_create();
45 45
         
46
-    }
46
+	}
47 47
     
48
-    /**
49
-     * Update object in DB with object in dbOidIndex if name/mib/type has changed.
50
-     * @return number : 0=unchanged, 1 = changed, 2=created
51
-     */
52
-    private function update_oid_update()
53
-    {
48
+	/**
49
+	 * Update object in DB with object in dbOidIndex if name/mib/type has changed.
50
+	 * @return number : 0=unchanged, 1 = changed, 2=created
51
+	 */
52
+	private function update_oid_update()
53
+	{
54 54
         
55
-        $db_conn=$this->getTrapsDB()->db_connect_trap();
55
+		$db_conn=$this->getTrapsDB()->db_connect_trap();
56 56
         
57
-        if ($this->dbOidIndex[$this->oidDesc['oid']]['key'] == -1)
58
-        { // newly created.
59
-            return 0;
60
-        }
61
-        $oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
62
-        $dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
63
-        if ( $this->oidDesc['name'] != $dbOid['name'] ||
64
-            $this->oidDesc['mib'] != $dbOid['mib'] ||
65
-            $this->oidDesc['type'] !=$dbOid['type']
66
-            )
67
-        { // Do update
68
-            $sql='UPDATE '.$this->getTrapsDB()->dbPrefix.'mib_cache SET '.
69
-                'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'.
70
-                ', syntax = :syntax, type_enum = :type_enum, description = :description '.
71
-                ' WHERE id= :id';
72
-            $sqlQuery=$db_conn->prepare($sql);
57
+		if ($this->dbOidIndex[$this->oidDesc['oid']]['key'] == -1)
58
+		{ // newly created.
59
+			return 0;
60
+		}
61
+		$oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
62
+		$dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
63
+		if ( $this->oidDesc['name'] != $dbOid['name'] ||
64
+			$this->oidDesc['mib'] != $dbOid['mib'] ||
65
+			$this->oidDesc['type'] !=$dbOid['type']
66
+			)
67
+		{ // Do update
68
+			$sql='UPDATE '.$this->getTrapsDB()->dbPrefix.'mib_cache SET '.
69
+				'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'.
70
+				', syntax = :syntax, type_enum = :type_enum, description = :description '.
71
+				' WHERE id= :id';
72
+			$sqlQuery=$db_conn->prepare($sql);
73 73
             
74
-            $sqlParam=array(
75
-                ':name' => $this->oidDesc['name'],
76
-                ':type' => $this->oidDesc['type'],
77
-                ':mib' => $this->oidDesc['mib'],
78
-                ':tc' =>  $this->oidDesc['textconv']??'null',
79
-                ':display_hint' => $this->oidDesc['dispHint']??'null' ,
80
-                ':syntax' => $this->oidDesc['syntax']==null??'null',
81
-                ':type_enum' => $this->oidDesc['type_enum']??'null',
82
-                ':description' => $this->oidDesc['description']??'null',
83
-                ':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
84
-            );
74
+			$sqlParam=array(
75
+				':name' => $this->oidDesc['name'],
76
+				':type' => $this->oidDesc['type'],
77
+				':mib' => $this->oidDesc['mib'],
78
+				':tc' =>  $this->oidDesc['textconv']??'null',
79
+				':display_hint' => $this->oidDesc['dispHint']??'null' ,
80
+				':syntax' => $this->oidDesc['syntax']==null??'null',
81
+				':type_enum' => $this->oidDesc['type_enum']??'null',
82
+				':description' => $this->oidDesc['description']??'null',
83
+				':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
84
+			);
85 85
             
86
-            if ($sqlQuery->execute($sqlParam) === false) {
87
-                $this->getLogging()->log('Error in query : ' . $sql,ERROR,'');
88
-            }
89
-            $this->getLogging()->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
90
-            return 1;
91
-        }
92
-        else
93
-        {
94
-            $this->getLogging()->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
95
-            return 0;
96
-        }
97
-    }
86
+			if ($sqlQuery->execute($sqlParam) === false) {
87
+				$this->getLogging()->log('Error in query : ' . $sql,ERROR,'');
88
+			}
89
+			$this->getLogging()->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
90
+			return 1;
91
+		}
92
+		else
93
+		{
94
+			$this->getLogging()->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
95
+			return 0;
96
+		}
97
+	}
98 98
 
99
-    /**
100
-     * Create object in DB with object in dbOidIndex
101
-     * @return number : 0=unchanged, 1 = changed, 2=created
102
-     */
103
-    private function update_oid_create()
104
-    {
105
-        // Insert data
99
+	/**
100
+	 * Create object in DB with object in dbOidIndex
101
+	 * @return number : 0=unchanged, 1 = changed, 2=created
102
+	 */
103
+	private function update_oid_create()
104
+	{
105
+		// Insert data
106 106
         
107
-        $db_conn=$this->getTrapsDB()->db_connect_trap();
108
-        $sql='INSERT INTO '.$this->getTrapsDB()->dbPrefix.'mib_cache '.
109
-            '(oid, name, type , mib, textual_convention, display_hint '.
110
-            ', syntax, type_enum , description ) ' .
111
-            'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
112
-            ', :syntax, :type_enum, :description )';
107
+		$db_conn=$this->getTrapsDB()->db_connect_trap();
108
+		$sql='INSERT INTO '.$this->getTrapsDB()->dbPrefix.'mib_cache '.
109
+			'(oid, name, type , mib, textual_convention, display_hint '.
110
+			', syntax, type_enum , description ) ' .
111
+			'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
112
+			', :syntax, :type_enum, :description )';
113 113
         
114
-        if ($this->getTrapsDB()->trapDBType == 'pgsql') $sql .= 'RETURNING id';
114
+		if ($this->getTrapsDB()->trapDBType == 'pgsql') $sql .= 'RETURNING id';
115 115
         
116
-        $sqlQuery=$db_conn->prepare($sql);
116
+		$sqlQuery=$db_conn->prepare($sql);
117 117
         
118
-        $sqlParam=array(
119
-            ':oid' => $this->oidDesc['oid'],
120
-            ':name' => $this->oidDesc['name'],
121
-            ':type' => $this->oidDesc['type'],
122
-            ':mib' => $this->oidDesc['mib'],
123
-            ':tc' =>  $this->oidDesc['textconv']??'null',
124
-            ':display_hint' => $this->oidDesc['dispHint']??'null',
125
-            ':syntax' => $this->oidDesc['syntax']??'null',
126
-            ':type_enum' => $this->oidDesc['type_enum']??'null',
127
-            ':description' => $this->oidDesc['description']??'null'
128
-        );
118
+		$sqlParam=array(
119
+			':oid' => $this->oidDesc['oid'],
120
+			':name' => $this->oidDesc['name'],
121
+			':type' => $this->oidDesc['type'],
122
+			':mib' => $this->oidDesc['mib'],
123
+			':tc' =>  $this->oidDesc['textconv']??'null',
124
+			':display_hint' => $this->oidDesc['dispHint']??'null',
125
+			':syntax' => $this->oidDesc['syntax']??'null',
126
+			':type_enum' => $this->oidDesc['type_enum']??'null',
127
+			':description' => $this->oidDesc['description']??'null'
128
+		);
129 129
         
130
-        if ($sqlQuery->execute($sqlParam) === false) {
131
-            $this->getLogging()->log('Error in query : ' . $sql,1,'');
132
-        }
130
+		if ($sqlQuery->execute($sqlParam) === false) {
131
+			$this->getLogging()->log('Error in query : ' . $sql,1,'');
132
+		}
133 133
         
134
-        switch ($this->getTrapsDB()->trapDBType)
135
-        {
136
-            case 'pgsql':
137
-                // Get last id to insert oid/values in secondary table
138
-                if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
139
-                    $this->getLogging()->log('Error getting id - pgsql - ',1,'');
140
-                }
141
-                if (! isset($inserted_id_ret['id'])) {
142
-                    $this->getLogging()->log('Error getting id - pgsql - empty.',ERROR);
143
-                    return 0;
144
-                }
145
-                $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
146
-                break;
147
-            case 'mysql':
148
-                // Get last id to insert oid/values in secondary table
149
-                $sql='SELECT LAST_INSERT_ID();';
150
-                if (($ret_code=$db_conn->query($sql)) === false) {
151
-                    $this->getLogging()->log('Erreur getting id - mysql - ',ERROR);
152
-                    return 0;
153
-                }
134
+		switch ($this->getTrapsDB()->trapDBType)
135
+		{
136
+			case 'pgsql':
137
+				// Get last id to insert oid/values in secondary table
138
+				if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
139
+					$this->getLogging()->log('Error getting id - pgsql - ',1,'');
140
+				}
141
+				if (! isset($inserted_id_ret['id'])) {
142
+					$this->getLogging()->log('Error getting id - pgsql - empty.',ERROR);
143
+					return 0;
144
+				}
145
+				$this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
146
+				break;
147
+			case 'mysql':
148
+				// Get last id to insert oid/values in secondary table
149
+				$sql='SELECT LAST_INSERT_ID();';
150
+				if (($ret_code=$db_conn->query($sql)) === false) {
151
+					$this->getLogging()->log('Erreur getting id - mysql - ',ERROR);
152
+					return 0;
153
+				}
154 154
                 
155
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
156
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
157
-                $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
158
-                break;
159
-            default:
160
-                $this->getLogging()->log('Error SQL type Unknown : '.$this->getTrapsDB()->trapDBType,ERROR);
161
-                return 0;
162
-        }
155
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
156
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
157
+				$this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
158
+				break;
159
+			default:
160
+				$this->getLogging()->log('Error SQL type Unknown : '.$this->getTrapsDB()->trapDBType,ERROR);
161
+				return 0;
162
+		}
163 163
         
164
-        // Set as newly created.
165
-        $this->dbOidIndex[$this->oidDesc['oid']]['key']=-1;
166
-        return 2;
167
-    }
164
+		// Set as newly created.
165
+		$this->dbOidIndex[$this->oidDesc['oid']]['key']=-1;
166
+		return 2;
167
+	}
168 168
 
169
-    /**
170
-     * get all objects for a trap.
171
-     * @param integer $trapId
172
-     * @return array : array of cached objects
173
-     */
174
-    private function cache_db_objects($trapId)
175
-    {
176
-        $dbObjects=array(); // cache of objects for trap in db
177
-        $db_conn=$this->getTrapsDB()->db_connect_trap();
178
-        // Get all objects
179
-        $sql='SELECT * FROM '.$this->getTrapsDB()->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
180
-        $this->getLogging()->log('SQL query get all traps: '.$sql,DEBUG );
181
-        if (($ret_code=$db_conn->query($sql)) === false) {
182
-            $this->getLogging()->log('No result in query : ' . $sql,1,'');
183
-        }
184
-        $dbObjectsRaw=$ret_code->fetchAll();
169
+	/**
170
+	 * get all objects for a trap.
171
+	 * @param integer $trapId
172
+	 * @return array : array of cached objects
173
+	 */
174
+	private function cache_db_objects($trapId)
175
+	{
176
+		$dbObjects=array(); // cache of objects for trap in db
177
+		$db_conn=$this->getTrapsDB()->db_connect_trap();
178
+		// Get all objects
179
+		$sql='SELECT * FROM '.$this->getTrapsDB()->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
180
+		$this->getLogging()->log('SQL query get all traps: '.$sql,DEBUG );
181
+		if (($ret_code=$db_conn->query($sql)) === false) {
182
+			$this->getLogging()->log('No result in query : ' . $sql,1,'');
183
+		}
184
+		$dbObjectsRaw=$ret_code->fetchAll();
185 185
         
186
-        foreach ($dbObjectsRaw as $val)
187
-        {
188
-            $dbObjects[$val['object_id']]=1;
189
-        }
190
-        return $dbObjects;
191
-    }
186
+		foreach ($dbObjectsRaw as $val)
187
+		{
188
+			$dbObjects[$val['object_id']]=1;
189
+		}
190
+		return $dbObjects;
191
+	}
192 192
     
193 193
 
194 194
 }
195 195
\ No newline at end of file
Please login to merge, or discard this patch.