Passed
Pull Request — master (#23)
by Patrick
02:12
created
application/controllers/HelperController.php 3 patches
Indentation   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -12,8 +12,8 @@  discard block
 block discarded – undo
12 12
 {
13 13
 	
14 14
 	/** Get host list with filter (IP or name) : host=<filter>
15
-	*	returns in JSON : status=>OK/NOK  hosts=>array of hosts
16
-	*/
15
+	 *	returns in JSON : status=>OK/NOK  hosts=>array of hosts
16
+	 */
17 17
 	public function gethostsAction()
18 18
 	{
19 19
 		$postData=$this->getRequest()->getPost();
@@ -40,8 +40,8 @@  discard block
 block discarded – undo
40 40
 
41 41
 	
42 42
 	/** Get hostgroup list with filter (name) : hostgroup=<hostFilter>
43
-	*	returns in JSON : status=>OK/NOK  hosts=>array of hosts
44
-	*/
43
+	 *	returns in JSON : status=>OK/NOK  hosts=>array of hosts
44
+	 */
45 45
 	public function gethostgroupsAction()
46 46
 	{
47 47
 		$postData=$this->getRequest()->getPost();
@@ -68,11 +68,11 @@  discard block
 block discarded – undo
68 68
 
69 69
 	
70 70
 	/** Get service list by host name ( host=<host> )
71
-	*	returns in JSON : 
72
-	*		status=>OK/No services found/More than one host matches
73
-	*		services=>array of services (name)
74
-	*		hostid = host object id or -1 if not found.
75
-	*/
71
+	 *	returns in JSON : 
72
+	 *		status=>OK/No services found/More than one host matches
73
+	 *		services=>array of services (name)
74
+	 *		hostid = host object id or -1 if not found.
75
+	 */
76 76
 	public function getservicesAction()
77 77
 	{
78 78
 		$postData=$this->getRequest()->getPost();
@@ -112,11 +112,11 @@  discard block
 block discarded – undo
112 112
 	}
113 113
 	
114 114
 	/** Get service list by host group ( name=<host> )
115
-	*	returns in JSON : 
116
-	*		status=>OK/No services found/More than one host matches
117
-	*		services=>array of services (name)
118
-	*		groupid = group object id or -1 if not found.
119
-	*/
115
+	 *	returns in JSON : 
116
+	 *		status=>OK/No services found/More than one host matches
117
+	 *		services=>array of services (name)
118
+	 *		groupid = group object id or -1 if not found.
119
+	 */
120 120
 	public function gethostgroupservicesAction()
121 121
 	{
122 122
 		$postData=$this->getRequest()->getPost();
@@ -153,10 +153,10 @@  discard block
 block discarded – undo
153 153
 	}
154 154
 
155 155
 	/** Get traps from mib  : entry : mib=<mib>
156
-	*	returns in JSON : 
157
-	*		status=>OK/No mib/Error getting mibs
158
-	*		traps=>array of array( oid -> name)
159
-	*/
156
+	 *	returns in JSON : 
157
+	 *		status=>OK/No mib/Error getting mibs
158
+	 *		traps=>array of array( oid -> name)
159
+	 */
160 160
 	public function gettrapsAction()
161 161
 	{
162 162
 		$postData=$this->getRequest()->getPost();
@@ -182,10 +182,10 @@  discard block
 block discarded – undo
182 182
 	}	
183 183
 
184 184
 	/** Get trap objects from mib  : entry : trap=<oid>
185
-	*	returns in JSON : 
186
-	*		status=>OK/no trap/not found
187
-	*		objects=>array of array( oid -> name, oid->mib)
188
-	*/
185
+	 *	returns in JSON : 
186
+	 *		status=>OK/no trap/not found
187
+	 *		objects=>array of array( oid -> name, oid->mib)
188
+	 */
189 189
 	public function gettrapobjectsAction()
190 190
 	{
191 191
 		$postData=$this->getRequest()->getPost();
@@ -211,8 +211,8 @@  discard block
 block discarded – undo
211 211
 	}	
212 212
 	
213 213
 	/** Get list of all loaded mibs : entry : none
214
-	*	return : array of strings.
215
-	*/
214
+	 *	return : array of strings.
215
+	 */
216 216
 	public function getmiblistAction()
217 217
 	{
218 218
 		try
@@ -227,10 +227,10 @@  discard block
 block discarded – undo
227 227
 	}
228 228
 	
229 229
 	/** Get MIB::Name from OID : entry : oid
230
-	*		status=>OK/No oid/not found
231
-	*		mib=>string
232
-	*		name=>string
233
-	*/	
230
+	 *		status=>OK/No oid/not found
231
+	 *		mib=>string
232
+	 *		name=>string
233
+	 */	
234 234
 	public function translateoidAction()
235 235
 	{
236 236
 		$postData=$this->getRequest()->getPost();
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 					'name' => $object['name'],
259 259
 					'type' => $object['type'],
260 260
 					'type_enum' => $object['type_enum'],
261
-				    'description' => $object['description']
261
+					'description' => $object['description']
262 262
 				)
263 263
 			);
264 264
 		}
@@ -267,10 +267,10 @@  discard block
 block discarded – undo
267 267
 
268 268
 	
269 269
 	/** Save or execute database purge of <n> days
270
-	*	days=>int 
271
-	*	action=>save/execute
272
-	*	return : status=>OK/Message error
273
-	*/
270
+	 *	days=>int 
271
+	 *	action=>save/execute
272
+	 *	return : status=>OK/Message error
273
+	 */
274 274
 	public function dbmaintenanceAction()
275 275
 	{
276 276
 		
@@ -339,11 +339,11 @@  discard block
 block discarded – undo
339 339
 	}	
340 340
 
341 341
 	/** Save log output to db
342
-	*	destination=>log destination 
343
-	*	file=>file name
344
-	*	level => int 
345
-	*	return : status=>OK/Message error
346
-	*/
342
+	 *	destination=>log destination 
343
+	 *	file=>file name
344
+	 *	level => int 
345
+	 *	return : status=>OK/Message error
346
+	 */
347 347
 	public function logdestinationAction()
348 348
 	{
349 349
 		$postData=$this->getRequest()->getPost();
@@ -367,8 +367,8 @@  discard block
 block discarded – undo
367 367
 			$fileHandler=@fopen($file,'w');
368 368
 			if ($fileHandler == false)
369 369
 			{   // File os note writabe / cannot create
370
-			    $this->_helper->json(array('status'=>'File not writable :  '.$file));
371
-			    return;
370
+				$this->_helper->json(array('status'=>'File not writable :  '.$file));
371
+				return;
372 372
 			}
373 373
 		}
374 374
 		else
@@ -418,50 +418,50 @@  discard block
 block discarded – undo
418 418
 	public function testruleAction()
419 419
 	{
420 420
 	    
421
-	    $postData=$this->getRequest()->getPost();
422
-	    if (isset($postData['rule']))
423
-	    {
424
-	        $rule=$postData['rule'];
425
-	    }
426
-	    else
427
-	    {
428
-	        $this->_helper->json(array('status'=>'No Rule'));
429
-	    }
430
-	    if (isset($postData['action']))
431
-	    {
432
-	        $action=$postData['action'];
433
-	        if ($action != 'evaluate')
434
-	        {
435
-	            $this->_helper->json(array('status'=>'unknown action '.$action));
436
-	            return;
437
-	        }
438
-	    }
439
-	    else
440
-	    {
441
-	        $this->_helper->json(array('status'=>'No action'));
442
-	        return;
443
-	    }
444
-	    if ($action == 'evaluate')
445
-	    {
446
-	        try
447
-	        {
448
-	            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
449
-	            $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
450
-	            $Trap = new Trap($icingaweb2_etc);
451
-	            // Cleanup spaces before eval
452
-	            $rule=$Trap->ruleClass->eval_cleanup($rule);
453
-	            // Eval
454
-	            $item=0;
455
-	            $rule=$Trap->ruleClass->evaluation($rule,$item);
456
-	        }
457
-	        catch (Exception $e)
458
-	        {
459
-	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
460
-	            return;
461
-	        }
462
-	        $return=($rule==true)?'true':'false';
463
-	        $this->_helper->json(array('status'=>'OK', 'message' => $return));
464
-	    }
421
+		$postData=$this->getRequest()->getPost();
422
+		if (isset($postData['rule']))
423
+		{
424
+			$rule=$postData['rule'];
425
+		}
426
+		else
427
+		{
428
+			$this->_helper->json(array('status'=>'No Rule'));
429
+		}
430
+		if (isset($postData['action']))
431
+		{
432
+			$action=$postData['action'];
433
+			if ($action != 'evaluate')
434
+			{
435
+				$this->_helper->json(array('status'=>'unknown action '.$action));
436
+				return;
437
+			}
438
+		}
439
+		else
440
+		{
441
+			$this->_helper->json(array('status'=>'No action'));
442
+			return;
443
+		}
444
+		if ($action == 'evaluate')
445
+		{
446
+			try
447
+			{
448
+				require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
449
+				$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
450
+				$Trap = new Trap($icingaweb2_etc);
451
+				// Cleanup spaces before eval
452
+				$rule=$Trap->ruleClass->eval_cleanup($rule);
453
+				// Eval
454
+				$item=0;
455
+				$rule=$Trap->ruleClass->evaluation($rule,$item);
456
+			}
457
+			catch (Exception $e)
458
+			{
459
+				$this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
460
+				return;
461
+			}
462
+			$return=($rule==true)?'true':'false';
463
+			$this->_helper->json(array('status'=>'OK', 'message' => $return));
464
+		}
465 465
 	    
466 466
 	}	
467 467
 	
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -27,12 +27,12 @@  discard block
 block discarded – undo
27 27
 			return;
28 28
 		}
29 29
 
30
-		$retHosts=array('status'=>'OK','hosts' => array());
30
+		$retHosts=array('status'=>'OK', 'hosts' => array());
31 31
 
32 32
 		$hosts=$this->getHostByIP($hostFilter);
33 33
 		foreach ($hosts as $val)
34 34
 		{
35
-			array_push($retHosts['hosts'],$val->name);
35
+			array_push($retHosts['hosts'], $val->name);
36 36
 		}
37 37
 		
38 38
 		$this->_helper->json($retHosts);
@@ -55,12 +55,12 @@  discard block
 block discarded – undo
55 55
 			return;
56 56
 		}
57 57
 
58
-		$retHosts=array('status'=>'OK','hosts' => array());
58
+		$retHosts=array('status'=>'OK', 'hosts' => array());
59 59
 
60 60
 		$hosts=$this->getHostGroupByName($hostFilter);
61 61
 		foreach ($hosts as $val)
62 62
 		{
63
-			array_push($retHosts['hosts'],$val->name);
63
+			array_push($retHosts['hosts'], $val->name);
64 64
 		}
65 65
 		
66 66
 		$this->_helper->json($retHosts);
@@ -82,31 +82,31 @@  discard block
 block discarded – undo
82 82
 		}
83 83
 		else
84 84
 		{
85
-			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
85
+			$this->_helper->json(array('status'=>'No Hosts', 'hostid' => -1));
86 86
 			return;
87 87
 		}
88 88
 		
89 89
 		$hostArray=$this->getHostByName($host);
90 90
 		if (count($hostArray) > 1)
91 91
 		{	
92
-			$this->_helper->json(array('status'=>'More than one host matches','hostid' => -1));
92
+			$this->_helper->json(array('status'=>'More than one host matches', 'hostid' => -1));
93 93
 			return;
94 94
 		}
95 95
 		else if (count($hostArray) == 0)
96 96
 		{
97
-			$this->_helper->json(array('status'=>'No host matches','hostid' => -1));
97
+			$this->_helper->json(array('status'=>'No host matches', 'hostid' => -1));
98 98
 			return;
99 99
 		}
100 100
 		$services=$this->getServicesByHostid($hostArray[0]->id);
101 101
 		if (count($services) < 1)
102 102
 		{
103
-			$this->_helper->json(array('status'=>'No services found for host','hostid' => $hostArray[0]->id));
103
+			$this->_helper->json(array('status'=>'No services found for host', 'hostid' => $hostArray[0]->id));
104 104
 			return;
105 105
 		}
106
-		$retServices=array('status'=>'OK','services' => array(),'hostid' => $hostArray[0]->id);
106
+		$retServices=array('status'=>'OK', 'services' => array(), 'hostid' => $hostArray[0]->id);
107 107
 		foreach ($services as $val)
108 108
 		{
109
-			array_push($retServices['services'],array($val->id , $val->name));
109
+			array_push($retServices['services'], array($val->id, $val->name));
110 110
 		}
111 111
 		$this->_helper->json($retServices);
112 112
 	}
@@ -126,28 +126,28 @@  discard block
 block discarded – undo
126 126
 		}
127 127
 		else
128 128
 		{
129
-			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
129
+			$this->_helper->json(array('status'=>'No Hosts', 'hostid' => -1));
130 130
 			return;
131 131
 		}
132 132
 		
133 133
 		$hostArray=$this->getHostGroupByName($host);
134 134
 		if (count($hostArray) > 1)
135 135
 		{	
136
-			$this->_helper->json(array('status'=>'More than one hostgroup matches','hostid' => -1));
136
+			$this->_helper->json(array('status'=>'More than one hostgroup matches', 'hostid' => -1));
137 137
 			return;
138 138
 		}
139 139
 		else if (count($hostArray) == 0)
140 140
 		{
141
-			$this->_helper->json(array('status'=>'No hostgroup matches','hostid' => -1));
141
+			$this->_helper->json(array('status'=>'No hostgroup matches', 'hostid' => -1));
142 142
 			return;
143 143
 		}
144 144
 		$services=$this->getServicesByHostGroupid($hostArray[0]->id);
145 145
 		if (count($services) < 1)
146 146
 		{
147
-			$this->_helper->json(array('status'=>'No services found for hostgroup','hostid' => $hostArray[0]->id));
147
+			$this->_helper->json(array('status'=>'No services found for hostgroup', 'hostid' => $hostArray[0]->id));
148 148
 			return;
149 149
 		}
150
-		$retServices=array('status'=>'OK','services' => $services,'hostid' => $hostArray[0]->id);
150
+		$retServices=array('status'=>'OK', 'services' => $services, 'hostid' => $hostArray[0]->id);
151 151
 		
152 152
 		$this->_helper->json($retServices);
153 153
 	}
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 		try
173 173
 		{
174 174
 			$traplist=$this->getMIB()->getTrapList($mib);
175
-			$retTraps=array('status'=>'OK','traps' => $traplist);
175
+			$retTraps=array('status'=>'OK', 'traps' => $traplist);
176 176
 		} 
177 177
 		catch (Exception $e) 
178 178
 		{ 
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
 		try
202 202
 		{
203 203
 			$objectlist=$this->getMIB()->getObjectList($trap);
204
-			$retObjects=array('status'=>'OK','objects' => $objectlist);
204
+			$retObjects=array('status'=>'OK', 'objects' => $objectlist);
205 205
 		} 
206 206
 		catch (Exception $e) 
207 207
 		{ 
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 		if (isset($postData['days']))
279 279
 		{
280 280
 			$days=$postData['days'];
281
-			if (!preg_match('/^[0-9]+$/',$days))
281
+			if (!preg_match('/^[0-9]+$/', $days))
282 282
 			{
283 283
 				$this->_helper->json(array('status'=>'invalid days : '.$days));
284 284
 				return;
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
 		if (isset($postData['action']))
293 293
 		{
294 294
 			$action=$postData['action'];
295
-			if ($action != 'save' && $action !='execute')
295
+			if ($action != 'save' && $action != 'execute')
296 296
 			{
297 297
 				$this->_helper->json(array('status'=>'unknown action '.$action));
298 298
 				return;
@@ -307,11 +307,11 @@  discard block
 block discarded – undo
307 307
 		{
308 308
 			try
309 309
 			{
310
-				$this->setDBConfigValue('db_remove_days',$days);
310
+				$this->setDBConfigValue('db_remove_days', $days);
311 311
 			}
312 312
 			catch (Exception $e)
313 313
 			{
314
-				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
314
+				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage()));
315 315
 				return;
316 316
 			}
317 317
 			$this->_helper->json(array('status'=>'OK'));
@@ -321,16 +321,16 @@  discard block
 block discarded – undo
321 321
 		{
322 322
 			try
323 323
 			{
324
-				require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
324
+				require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
325 325
 				$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
326 326
 				$debug_level=4;
327
-				$Trap = new Trap($icingaweb2_etc);
328
-				$Trap->setLogging($debug_level,'syslog');
327
+				$Trap=new Trap($icingaweb2_etc);
328
+				$Trap->setLogging($debug_level, 'syslog');
329 329
 				$Trap->eraseOldTraps($days);
330 330
 			}
331 331
 			catch (Exception $e)
332 332
 			{
333
-				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage() ));
333
+				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage()));
334 334
 				return;
335 335
 			}			
336 336
 			$this->_helper->json(array('status'=>'OK'));
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
 		if (isset($postData['file']))
365 365
 		{ 
366 366
 			$file=$postData['file'];
367
-			$fileHandler=@fopen($file,'w');
367
+			$fileHandler=@fopen($file, 'w');
368 368
 			if ($fileHandler == false)
369 369
 			{   // File os note writabe / cannot create
370 370
 			    $this->_helper->json(array('status'=>'File not writable :  '.$file));
@@ -396,13 +396,13 @@  discard block
 block discarded – undo
396 396
 		
397 397
 		try
398 398
 		{
399
-			$this->setDBConfigValue('log_destination',$destination);
400
-			$this->setDBConfigValue('log_file',$file);
401
-			$this->setDBConfigValue('log_level',$level);
399
+			$this->setDBConfigValue('log_destination', $destination);
400
+			$this->setDBConfigValue('log_file', $file);
401
+			$this->setDBConfigValue('log_level', $level);
402 402
 		}
403 403
 		catch (Exception $e)
404 404
 		{
405
-			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
405
+			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage()));
406 406
 			return;
407 407
 		}
408 408
 		$this->_helper->json(array('status'=>'OK'));
@@ -445,21 +445,21 @@  discard block
 block discarded – undo
445 445
 	    {
446 446
 	        try
447 447
 	        {
448
-	            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
448
+	            require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
449 449
 	            $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
450
-	            $Trap = new Trap($icingaweb2_etc);
450
+	            $Trap=new Trap($icingaweb2_etc);
451 451
 	            // Cleanup spaces before eval
452 452
 	            $rule=$Trap->ruleClass->eval_cleanup($rule);
453 453
 	            // Eval
454 454
 	            $item=0;
455
-	            $rule=$Trap->ruleClass->evaluation($rule,$item);
455
+	            $rule=$Trap->ruleClass->evaluation($rule, $item);
456 456
 	        }
457 457
 	        catch (Exception $e)
458 458
 	        {
459
-	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
459
+	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage()));
460 460
 	            return;
461 461
 	        }
462
-	        $return=($rule==true)?'true':'false';
462
+	        $return=($rule == true) ? 'true' : 'false';
463 463
 	        $this->_helper->json(array('status'=>'OK', 'message' => $return));
464 464
 	    }
465 465
 	    
Please login to merge, or discard this patch.
Braces   +25 added lines, -50 removed lines patch added patch discarded remove patch
@@ -20,8 +20,7 @@  discard block
 block discarded – undo
20 20
 		if (isset($postData['hostFilter']))
21 21
 		{
22 22
 			$hostFilter=$postData['hostFilter'];
23
-		}
24
-		else
23
+		} else
25 24
 		{
26 25
 			$this->_helper->json(array('status'=>'KO'));
27 26
 			return;
@@ -48,8 +47,7 @@  discard block
 block discarded – undo
48 47
 		if (isset($postData['hostFilter']))
49 48
 		{
50 49
 			$hostFilter=$postData['hostFilter'];
51
-		}
52
-		else
50
+		} else
53 51
 		{
54 52
 			$this->_helper->json(array('status'=>'Error : no filter'));
55 53
 			return;
@@ -79,8 +77,7 @@  discard block
 block discarded – undo
79 77
 		if (isset($postData['host']))
80 78
 		{
81 79
 			$host=$postData['host'];
82
-		}
83
-		else
80
+		} else
84 81
 		{
85 82
 			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
86 83
 			return;
@@ -91,8 +88,7 @@  discard block
 block discarded – undo
91 88
 		{	
92 89
 			$this->_helper->json(array('status'=>'More than one host matches','hostid' => -1));
93 90
 			return;
94
-		}
95
-		else if (count($hostArray) == 0)
91
+		} else if (count($hostArray) == 0)
96 92
 		{
97 93
 			$this->_helper->json(array('status'=>'No host matches','hostid' => -1));
98 94
 			return;
@@ -123,8 +119,7 @@  discard block
 block discarded – undo
123 119
 		if (isset($postData['host']))
124 120
 		{
125 121
 			$host=$postData['host'];
126
-		}
127
-		else
122
+		} else
128 123
 		{
129 124
 			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
130 125
 			return;
@@ -135,8 +130,7 @@  discard block
 block discarded – undo
135 130
 		{	
136 131
 			$this->_helper->json(array('status'=>'More than one hostgroup matches','hostid' => -1));
137 132
 			return;
138
-		}
139
-		else if (count($hostArray) == 0)
133
+		} else if (count($hostArray) == 0)
140 134
 		{
141 135
 			$this->_helper->json(array('status'=>'No hostgroup matches','hostid' => -1));
142 136
 			return;
@@ -163,8 +157,7 @@  discard block
 block discarded – undo
163 157
 		if (isset($postData['mib']))
164 158
 		{
165 159
 			$mib=$postData['mib'];
166
-		}
167
-		else
160
+		} else
168 161
 		{
169 162
 			$this->_helper->json(array('status'=>'No mib'));
170 163
 			return;
@@ -173,8 +166,7 @@  discard block
 block discarded – undo
173 166
 		{
174 167
 			$traplist=$this->getMIB()->getTrapList($mib);
175 168
 			$retTraps=array('status'=>'OK','traps' => $traplist);
176
-		} 
177
-		catch (Exception $e) 
169
+		} catch (Exception $e) 
178 170
 		{ 
179 171
 			$retTraps=array('status' => 'Error getting mibs');
180 172
 		}
@@ -192,8 +184,7 @@  discard block
 block discarded – undo
192 184
 		if (isset($postData['trap']))
193 185
 		{
194 186
 			$trap=$postData['trap'];
195
-		}
196
-		else
187
+		} else
197 188
 		{
198 189
 			$this->_helper->json(array('status'=>'No trap'));
199 190
 			return;
@@ -202,8 +193,7 @@  discard block
 block discarded – undo
202 193
 		{
203 194
 			$objectlist=$this->getMIB()->getObjectList($trap);
204 195
 			$retObjects=array('status'=>'OK','objects' => $objectlist);
205
-		} 
206
-		catch (Exception $e) 
196
+		} catch (Exception $e) 
207 197
 		{ 
208 198
 			$retObjects=array('status' => 'not found');
209 199
 		}
@@ -218,8 +208,7 @@  discard block
 block discarded – undo
218 208
 		try
219 209
 		{
220 210
 			$miblist=$this->getMIB()->getMIBList();
221
-		} 
222
-		catch (Exception $e) 
211
+		} catch (Exception $e) 
223 212
 		{ 
224 213
 			$miblist=array('Error getting mibs');
225 214
 		}
@@ -237,8 +226,7 @@  discard block
 block discarded – undo
237 226
 		if (isset($postData['oid']))
238 227
 		{
239 228
 			$oid=$postData['oid'];
240
-		}
241
-		else
229
+		} else
242 230
 		{
243 231
 			$this->_helper->json(array('status'=>'No oid'));
244 232
 			return;
@@ -249,8 +237,7 @@  discard block
 block discarded – undo
249 237
 		{
250 238
 			$this->_helper->json(array('status'=>'Not found'));
251 239
 			return;
252
-		}
253
-		else
240
+		} else
254 241
 		{
255 242
 			$this->_helper->json(
256 243
 				array('status'=>'OK',
@@ -283,8 +270,7 @@  discard block
 block discarded – undo
283 270
 				$this->_helper->json(array('status'=>'invalid days : '.$days));
284 271
 				return;
285 272
 			}
286
-		}
287
-		else
273
+		} else
288 274
 		{
289 275
 			$this->_helper->json(array('status'=>'No days'));
290 276
 			return;
@@ -297,8 +283,7 @@  discard block
 block discarded – undo
297 283
 				$this->_helper->json(array('status'=>'unknown action '.$action));
298 284
 				return;
299 285
 			}
300
-		}
301
-		else
286
+		} else
302 287
 		{
303 288
 			$this->_helper->json(array('status'=>'No action'));
304 289
 			return;
@@ -308,8 +293,7 @@  discard block
 block discarded – undo
308 293
 			try
309 294
 			{
310 295
 				$this->setDBConfigValue('db_remove_days',$days);
311
-			}
312
-			catch (Exception $e)
296
+			} catch (Exception $e)
313 297
 			{
314 298
 				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
315 299
 				return;
@@ -327,8 +311,7 @@  discard block
 block discarded – undo
327 311
 				$Trap = new Trap($icingaweb2_etc);
328 312
 				$Trap->setLogging($debug_level,'syslog');
329 313
 				$Trap->eraseOldTraps($days);
330
-			}
331
-			catch (Exception $e)
314
+			} catch (Exception $e)
332 315
 			{
333 316
 				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage() ));
334 317
 				return;
@@ -356,8 +339,7 @@  discard block
 block discarded – undo
356 339
 				$this->_helper->json(array('status'=>'invalid destination : '.$destination));
357 340
 				return;
358 341
 			}
359
-		}
360
-		else
342
+		} else
361 343
 		{
362 344
 			$this->_helper->json(array('status'=>'No destination'));
363 345
 		}
@@ -370,14 +352,12 @@  discard block
 block discarded – undo
370 352
 			    $this->_helper->json(array('status'=>'File not writable :  '.$file));
371 353
 			    return;
372 354
 			}
373
-		}
374
-		else
355
+		} else
375 356
 		{
376 357
 			if ($destination != 'file')
377 358
 			{
378 359
 				$file=null;
379
-			}
380
-			else
360
+			} else
381 361
 			{
382 362
 				$this->_helper->json(array('status'=>'No file'));
383 363
 				return;
@@ -387,8 +367,7 @@  discard block
 block discarded – undo
387 367
 		if (isset($postData['level']))
388 368
 		{ 
389 369
 			$level=$postData['level'];
390
-		}
391
-		else
370
+		} else
392 371
 		{
393 372
 			$this->_helper->json(array('status'=>'No level'));
394 373
 			return;
@@ -399,8 +378,7 @@  discard block
 block discarded – undo
399 378
 			$this->setDBConfigValue('log_destination',$destination);
400 379
 			$this->setDBConfigValue('log_file',$file);
401 380
 			$this->setDBConfigValue('log_level',$level);
402
-		}
403
-		catch (Exception $e)
381
+		} catch (Exception $e)
404 382
 		{
405 383
 			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
406 384
 			return;
@@ -422,8 +400,7 @@  discard block
 block discarded – undo
422 400
 	    if (isset($postData['rule']))
423 401
 	    {
424 402
 	        $rule=$postData['rule'];
425
-	    }
426
-	    else
403
+	    } else
427 404
 	    {
428 405
 	        $this->_helper->json(array('status'=>'No Rule'));
429 406
 	    }
@@ -435,8 +412,7 @@  discard block
 block discarded – undo
435 412
 	            $this->_helper->json(array('status'=>'unknown action '.$action));
436 413
 	            return;
437 414
 	        }
438
-	    }
439
-	    else
415
+	    } else
440 416
 	    {
441 417
 	        $this->_helper->json(array('status'=>'No action'));
442 418
 	        return;
@@ -453,8 +429,7 @@  discard block
 block discarded – undo
453 429
 	            // Eval
454 430
 	            $item=0;
455 431
 	            $rule=$Trap->ruleClass->evaluation($rule,$item);
456
-	        }
457
-	        catch (Exception $e)
432
+	        } catch (Exception $e)
458 433
 	        {
459 434
 	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
460 435
 	            return;
Please login to merge, or discard this patch.
application/controllers/SettingsController.php 3 patches
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -25,16 +25,16 @@  discard block
 block discarded – undo
25 25
    */
26 26
   private function get_param()
27 27
   {
28
-      $dberrorMsg=$this->params->get('dberror');
29
-      if ($dberrorMsg != '')
30
-      {
31
-          $this->view->errorDetected=$dberrorMsg;
32
-      }
33
-      $dberrorMsg=$this->params->get('idodberror');
34
-      if ($dberrorMsg != '')
35
-      {
36
-          $this->view->errorDetected=$dberrorMsg;
37
-      }
28
+	  $dberrorMsg=$this->params->get('dberror');
29
+	  if ($dberrorMsg != '')
30
+	  {
31
+		  $this->view->errorDetected=$dberrorMsg;
32
+	  }
33
+	  $dberrorMsg=$this->params->get('idodberror');
34
+	  if ($dberrorMsg != '')
35
+	  {
36
+		  $this->view->errorDetected=$dberrorMsg;
37
+	  }
38 38
   }
39 39
   
40 40
   /**
@@ -43,22 +43,22 @@  discard block
 block discarded – undo
43 43
    */
44 44
   private function check_empty_config()
45 45
   {
46
-      $this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
47
-      if ($this->Config()->isEmpty() == true)
48
-      {
49
-          $this->Config()->setSection('config'); // Set base config section.
50
-          try
51
-          {
52
-              $this->Config()->saveIni();
53
-              $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54
-              //$emptyConfig=1;
55
-          }
56
-          catch (Exception $e)
57
-          {
58
-              $this->view->configErrorDetected=$e->getMessage();
59
-          }
46
+	  $this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
47
+	  if ($this->Config()->isEmpty() == true)
48
+	  {
49
+		  $this->Config()->setSection('config'); // Set base config section.
50
+		  try
51
+		  {
52
+			  $this->Config()->saveIni();
53
+			  $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54
+			  //$emptyConfig=1;
55
+		  }
56
+		  catch (Exception $e)
57
+		  {
58
+			  $this->view->configErrorDetected=$e->getMessage();
59
+		  }
60 60
           
61
-      }
61
+	  }
62 62
   }
63 63
   
64 64
   /**
@@ -71,45 +71,45 @@  discard block
 block discarded – undo
71 71
    */
72 72
   private function check_db()
73 73
   {
74
-      $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
-          0	=>	array('Database configuration OK','',''),
76
-          1	=>	array('Database set in config.ini','No database in config.ini',''),
77
-          2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
78
-              Url::fromPath('config/resource')),
79
-          3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
80
-              Url::fromPath('trapdirector/settings/createschema')),
81
-          4	=>	array('Schema is set','Schema is not set for ',
82
-              Url::fromPath('trapdirector/settings/createschema')),
83
-          5	=>	array('Schema is up to date','Schema is outdated :',
84
-              Url::fromPath('trapdirector/settings/updateschema')),
85
-      );
74
+	  $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
+		  0	=>	array('Database configuration OK','',''),
76
+		  1	=>	array('Database set in config.ini','No database in config.ini',''),
77
+		  2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
78
+			  Url::fromPath('config/resource')),
79
+		  3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
80
+			  Url::fromPath('trapdirector/settings/createschema')),
81
+		  4	=>	array('Schema is set','Schema is not set for ',
82
+			  Url::fromPath('trapdirector/settings/createschema')),
83
+		  5	=>	array('Schema is up to date','Schema is outdated :',
84
+			  Url::fromPath('trapdirector/settings/updateschema')),
85
+	  );
86 86
       
87
-      $dberror=$this->getDb(true); // Get DB in test mode
87
+	  $dberror=$this->getDb(true); // Get DB in test mode
88 88
       
89
-      $this->view->db_error=$dberror[0];
90
-      switch ($dberror[0])
91
-      {
92
-          case 2:
93
-          case 4:
94
-              $db_message[$dberror[0]][1] .= $dberror[1];
95
-              break;
96
-          case 3:
97
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
98
-              break;
99
-          case 5:
100
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
101
-              break;
102
-          case 0:
103
-          case 1:
104
-              break;
105
-          default:
106
-              new ProgrammingError('Out of bond result from database test');
107
-      }
108
-      $this->view->message=$db_message;
89
+	  $this->view->db_error=$dberror[0];
90
+	  switch ($dberror[0])
91
+	  {
92
+		  case 2:
93
+		  case 4:
94
+			  $db_message[$dberror[0]][1] .= $dberror[1];
95
+			  break;
96
+		  case 3:
97
+			  $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
98
+			  break;
99
+		  case 5:
100
+			  $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
101
+			  break;
102
+		  case 0:
103
+		  case 1:
104
+			  break;
105
+		  default:
106
+			  new ProgrammingError('Out of bond result from database test');
107
+	  }
108
+	  $this->view->message=$db_message;
109 109
       
110
-      $dberror=$this->getIdoDb(true); // Get IDO DB in test mode
111
-      $this->view->ido_db_error=$dberror[0];
112
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
110
+	  $dberror=$this->getIdoDb(true); // Get IDO DB in test mode
111
+	  $this->view->ido_db_error=$dberror[0];
112
+	  $this->view->ido_message='IDO Database : ' . $dberror[1];
113 113
   }
114 114
   
115 115
   /**
@@ -119,23 +119,23 @@  discard block
 block discarded – undo
119 119
    */
120 120
   private function check_api()
121 121
   {
122
-      if ($this->Config()->get('config', 'icingaAPI_host') != '')
123
-      {
124
-          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
125
-          $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
126
-          try {
127
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
128
-              //$this->view->apimessageError=false;
129
-          } catch (RuntimeException $e) {
130
-              $this->view->apimessage='API config : ' . $e->getMessage();
131
-              $this->view->apimessageError=true;
132
-          }
133
-      }
134
-      else
135
-      {
136
-          $this->view->apimessage='API parameters not configured';
137
-          $this->view->apimessageError=true;
138
-      }
122
+	  if ($this->Config()->get('config', 'icingaAPI_host') != '')
123
+	  {
124
+		  $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
125
+		  $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
126
+		  try {
127
+			  list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
128
+			  //$this->view->apimessageError=false;
129
+		  } catch (RuntimeException $e) {
130
+			  $this->view->apimessage='API config : ' . $e->getMessage();
131
+			  $this->view->apimessageError=true;
132
+		  }
133
+	  }
134
+	  else
135
+	  {
136
+		  $this->view->apimessage='API parameters not configured';
137
+		  $this->view->apimessageError=true;
138
+	  }
139 139
   }
140 140
 
141 141
   /**
@@ -146,20 +146,20 @@  discard block
 block discarded – undo
146 146
    */
147 147
   private function check_icingaweb_path()
148 148
   {
149
-      $this->view->icingaEtcWarn=0;
150
-      $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
151
-      if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
152
-      {
153
-          $output=array();
149
+	  $this->view->icingaEtcWarn=0;
150
+	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
151
+	  if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
152
+	  {
153
+		  $output=array();
154 154
           
155
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2_etc=" ',$output);
155
+		  exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2_etc=" ',$output);
156 156
           
157
-          if (! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
158
-          {
159
-              $this->view->icingaEtcWarn=1;
160
-              $this->view->icingaweb2_etc=$icingaweb2_etc;
161
-          }
162
-      }
157
+		  if (! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
158
+		  {
159
+			  $this->view->icingaEtcWarn=1;
160
+			  $this->view->icingaweb2_etc=$icingaweb2_etc;
161
+		  }
162
+	  }
163 163
       
164 164
   }
165 165
   
@@ -170,15 +170,15 @@  discard block
 block discarded – undo
170 170
    */
171 171
   private function get_db_list($allowed)
172 172
   {
173
-      $resources = array();
174
-      foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
175
-      {
176
-          if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
177
-          {
178
-              $resources[$name] = $name;
179
-          }
180
-      }
181
-      return $resources;
173
+	  $resources = array();
174
+	  foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
175
+	  {
176
+		  if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
177
+		  {
178
+			  $resources[$name] = $name;
179
+		  }
180
+	  }
181
+	  return $resources;
182 182
   }
183 183
   
184 184
   /**
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
   public function indexAction()
198 198
   {
199 199
       
200
-    // CHeck permissions : display tests in any case, but no configuration.
200
+	// CHeck permissions : display tests in any case, but no configuration.
201 201
 	$this->view->configPermission=$this->checkModuleConfigPermission(1);
202 202
 	// But check read permission
203 203
 	$this->checkReadPermission();
@@ -205,16 +205,16 @@  discard block
 block discarded – undo
205 205
 	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');
206 206
 	
207 207
 	// Get message : sent on configuration problems detected by controllers
208
-    $this->get_param();
208
+	$this->get_param();
209 209
     
210
-    // Test if configuration exists, if not create for installer script
210
+	// Test if configuration exists, if not create for installer script
211 211
 	$this->check_empty_config();
212 212
 
213 213
 	// Test Database
214
-    $this->check_db();
214
+	$this->check_db();
215 215
 	
216 216
 	//********* Test API
217
-    $this->check_api();
217
+	$this->check_api();
218 218
 	
219 219
 	//*********** Test snmptrapd alive and options
220 220
 	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
@@ -229,11 +229,11 @@  discard block
 block discarded – undo
229 229
 	$this->view->traps_in_config= PHP_BINARY . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
230 230
 	
231 231
 	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
232
-	    . ' -c all ' 
233
-	    . ' -d ' . $this->Module()->getBaseDir()
234
-	    . ' -p ' . PHP_BINARY
235
-	    . ' -a ' . exec('whoami')
236
-	    . ' -w ' . Icinga::app()->getConfigDir();
232
+		. ' -c all ' 
233
+		. ' -d ' . $this->Module()->getBaseDir()
234
+		. ' -p ' . PHP_BINARY
235
+		. ' -a ' . exec('whoami')
236
+		. ' -w ' . Icinga::app()->getConfigDir();
237 237
 	        
238 238
 	// ******************* configuration form setup*******************
239 239
 	$this->view->form = $form = new TrapsConfigForm();
@@ -278,19 +278,19 @@  discard block
 block discarded – undo
278 278
 		  $dbResource = ResourceFactory::getResourceConfig($dbName);
279 279
 		  $dbType=$dbResource->get('db');
280 280
 		  switch ($dbType) {
281
-		      case 'mysql':
282
-		          $dbFileExt='sql';
283
-		          break;
284
-		      case 'pgsql':
285
-		          $dbFileExt='pgsql';
286
-		          break;
287
-		      default:
288
-		          throw new ConfigurationError('Unsuported database : '.$dbType);
281
+			  case 'mysql':
282
+				  $dbFileExt='sql';
283
+				  break;
284
+			  case 'pgsql':
285
+				  $dbFileExt='pgsql';
286
+				  break;
287
+			  default:
288
+				  throw new ConfigurationError('Unsuported database : '.$dbType);
289 289
 		  }
290 290
 		} catch (ConfigurationError $e )
291 291
 		{
292
-		    printf("Database configuration error : %s",$e->getMessage());
293
-		    return;
292
+			printf("Database configuration error : %s",$e->getMessage());
293
+			return;
294 294
 		}
295 295
 		printf('<pre>');
296 296
 		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
@@ -314,11 +314,11 @@  discard block
 block discarded – undo
314 314
   public function updateschemaAction()
315 315
   {
316 316
 	  $this->checkModuleConfigPermission();
317
-    	$this->getTabs()->add('get',array(
318
-    		'active'	=> true,
319
-    		'label'		=> $this->translate('Update Schema'),
320
-    		'url'		=> Url::fromRequest()
321
-    	));
317
+		$this->getTabs()->add('get',array(
318
+			'active'	=> true,
319
+			'label'		=> $this->translate('Update Schema'),
320
+			'url'		=> Url::fromRequest()
321
+		));
322 322
 	  // check if needed
323 323
 	  
324 324
 	  $dberror=$this->getDb(true); // Get DB in test mode
@@ -327,15 +327,15 @@  discard block
 block discarded – undo
327 327
 	  
328 328
 	  if ($dberror[0] == 0)
329 329
 	  {
330
-	      echo 'Schema already exists and is up to date<br>';
331
-	      return;
330
+		  echo 'Schema already exists and is up to date<br>';
331
+		  return;
332 332
 	  }
333 333
 	  if ($dberror[0] != 5)
334 334
 	  {
335
-	      echo 'Database does not exists or is not setup correctly<br>';
336
-	      return;
335
+		  echo 'Database does not exists or is not setup correctly<br>';
336
+		  return;
337 337
 	  }
338
-      // setup
338
+	  // setup
339 339
 	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
340 340
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
341 341
 	  $debug_level=4;
@@ -348,20 +348,20 @@  discard block
 block discarded – undo
348 348
 	  $target_version=$dberror[2];
349 349
 	  
350 350
 	  if ($this->params->get('msgok') == null) {
351
-	      // Check for messages and display if any
352
-              echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
353
-	      $Trap->setLogging(2,'syslog');
354
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
355
-	      if ($message != '')
356
-	      {
357
-	          echo 'Note :<br><pre>';
358
-	          echo $message;
359
-	          echo '</pre>';
360
-	          echo '<br>';
361
-	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
362
-	          echo '<br>';
363
-	          return;
364
-	      }
351
+		  // Check for messages and display if any
352
+			  echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
353
+		  $Trap->setLogging(2,'syslog');
354
+		  $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
355
+		  if ($message != '')
356
+		  {
357
+			  echo 'Note :<br><pre>';
358
+			  echo $message;
359
+			  echo '</pre>';
360
+			  echo '<br>';
361
+			  echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
362
+			  echo '<br>';
363
+			  return;
364
+		  }
365 365
 	  }
366 366
 	  
367 367
 	  $Trap->setLogging($debug_level,'display');
@@ -375,28 +375,28 @@  discard block
 block discarded – undo
375 375
 
376 376
   private function checkSnmpTrapd()
377 377
   {
378
-      $psOutput=array();
379
-      // First check is someone is listening to port 162. As not root, we can't have pid... 
380
-      exec('netstat -an |grep -E "udp.*:162"',$psOutput);
381
-      if (count($psOutput) == 0)
382
-      {
383
-          return array(1,'Port UDP/162 is not open : snmptrapd must not be started');
384
-      }
385
-      $psOutput=array();
386
-      exec('ps fax |grep snmptrapd |grep -v grep',$psOutput);
387
-      if (count($psOutput) == 0)
388
-      {
389
-          return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
390
-      }
391
-      // Assume there is only one line... TODO : see if there is a better way to do this
392
-      $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
393
-      if (!preg_match('/-n/',$line))
394
-          return array(1,'snmptrapd has no -n option : '.$line);
395
-      if (!preg_match('/-O[^ ]*n/',$line))
396
-          return array(1,'snmptrapd has no -On option : '.$line);
397
-      if (!preg_match('/-O[^ ]*e/',$line))
398
-          return array(1,'snmptrapd has no -Oe option : '.$line);
378
+	  $psOutput=array();
379
+	  // First check is someone is listening to port 162. As not root, we can't have pid... 
380
+	  exec('netstat -an |grep -E "udp.*:162"',$psOutput);
381
+	  if (count($psOutput) == 0)
382
+	  {
383
+		  return array(1,'Port UDP/162 is not open : snmptrapd must not be started');
384
+	  }
385
+	  $psOutput=array();
386
+	  exec('ps fax |grep snmptrapd |grep -v grep',$psOutput);
387
+	  if (count($psOutput) == 0)
388
+	  {
389
+		  return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
390
+	  }
391
+	  // Assume there is only one line... TODO : see if there is a better way to do this
392
+	  $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
393
+	  if (!preg_match('/-n/',$line))
394
+		  return array(1,'snmptrapd has no -n option : '.$line);
395
+	  if (!preg_match('/-O[^ ]*n/',$line))
396
+		  return array(1,'snmptrapd has no -On option : '.$line);
397
+	  if (!preg_match('/-O[^ ]*e/',$line))
398
+		  return array(1,'snmptrapd has no -Oe option : '.$line);
399 399
       
400
-      return array(0,'snmptrapd listening to UDP/162, options : '.$line);
400
+	  return array(0,'snmptrapd listening to UDP/162, options : '.$line);
401 401
   }
402 402
 }
Please login to merge, or discard this patch.
Spacing   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -72,15 +72,15 @@  discard block
 block discarded – undo
72 72
   private function check_db()
73 73
   {
74 74
       $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
-          0	=>	array('Database configuration OK','',''),
76
-          1	=>	array('Database set in config.ini','No database in config.ini',''),
77
-          2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
75
+          0	=>	array('Database configuration OK', '', ''),
76
+          1	=>	array('Database set in config.ini', 'No database in config.ini', ''),
77
+          2	=>	array('Database exists in Icingaweb2 config', 'Database does not exist in Icingaweb2 : ',
78 78
               Url::fromPath('config/resource')),
79
-          3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
79
+          3	=>	array('Database credentials OK', 'Database does not exist/invalid credentials/no schema : ',
80 80
               Url::fromPath('trapdirector/settings/createschema')),
81
-          4	=>	array('Schema is set','Schema is not set for ',
81
+          4	=>	array('Schema is set', 'Schema is not set for ',
82 82
               Url::fromPath('trapdirector/settings/createschema')),
83
-          5	=>	array('Schema is up to date','Schema is outdated :',
83
+          5	=>	array('Schema is up to date', 'Schema is outdated :',
84 84
               Url::fromPath('trapdirector/settings/updateschema')),
85 85
       );
86 86
       
@@ -91,13 +91,13 @@  discard block
 block discarded – undo
91 91
       {
92 92
           case 2:
93 93
           case 4:
94
-              $db_message[$dberror[0]][1] .= $dberror[1];
94
+              $db_message[$dberror[0]][1].=$dberror[1];
95 95
               break;
96 96
           case 3:
97
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
97
+              $db_message[$dberror[0]][1].=$dberror[1].', Message : '.$dberror[2];
98 98
               break;
99 99
           case 5:
100
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
100
+              $db_message[$dberror[0]][1].=' version '.$dberror[1].', version needed : '.$dberror[2];
101 101
               break;
102 102
           case 0:
103 103
           case 1:
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
       
110 110
       $dberror=$this->getIdoDb(true); // Get IDO DB in test mode
111 111
       $this->view->ido_db_error=$dberror[0];
112
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
112
+      $this->view->ido_message='IDO Database : '.$dberror[1];
113 113
   }
114 114
   
115 115
   /**
@@ -121,13 +121,13 @@  discard block
 block discarded – undo
121 121
   {
122 122
       if ($this->Config()->get('config', 'icingaAPI_host') != '')
123 123
       {
124
-          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
124
+          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'), $this->Config()->get('config', 'icingaAPI_port'));
125 125
           $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
126 126
           try {
127
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
127
+              list($this->view->apimessageError, $this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
128 128
               //$this->view->apimessageError=false;
129 129
           } catch (RuntimeException $e) {
130
-              $this->view->apimessage='API config : ' . $e->getMessage();
130
+              $this->view->apimessage='API config : '.$e->getMessage();
131 131
               $this->view->apimessageError=true;
132 132
           }
133 133
       }
@@ -152,9 +152,9 @@  discard block
 block discarded – undo
152 152
       {
153 153
           $output=array();
154 154
           
155
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2_etc=" ',$output);
155
+          exec('cat '.$this->module->getBaseDir().'/bin/trap_in.php | grep "\$icingaweb2_etc=" ', $output);
156 156
           
157
-          if (! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
157
+          if (!preg_match('#"'.$icingaweb2_etc.'"#', $output[0]))
158 158
           {
159 159
               $this->view->icingaEtcWarn=1;
160 160
               $this->view->icingaweb2_etc=$icingaweb2_etc;
@@ -170,12 +170,12 @@  discard block
 block discarded – undo
170 170
    */
171 171
   private function get_db_list($allowed)
172 172
   {
173
-      $resources = array();
173
+      $resources=array();
174 174
       foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
175 175
       {
176 176
           if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
177 177
           {
178
-              $resources[$name] = $name;
178
+              $resources[$name]=$name;
179 179
           }
180 180
       }
181 181
       return $resources;
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 	// But check read permission
203 203
 	$this->checkReadPermission();
204 204
 	
205
-	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');
205
+	$this->view->tabs=$this->Module()->getConfigTabs()->activate('config');
206 206
 	
207 207
 	// Get message : sent on configuration problems detected by controllers
208 208
     $this->get_param();
@@ -217,32 +217,32 @@  discard block
 block discarded – undo
217 217
     $this->check_api();
218 218
 	
219 219
 	//*********** Test snmptrapd alive and options
220
-	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
220
+	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage)=$this->checkSnmpTrapd();
221 221
 
222 222
 	// List DB in $ressources
223
-	$resources = $this->get_db_list(array('mysql', 'pgsql')); 
223
+	$resources=$this->get_db_list(array('mysql', 'pgsql')); 
224 224
 
225 225
 	// Check standard Icingaweb2 path
226 226
 	$this->check_icingaweb_path();
227 227
 	
228 228
 	// Setup path for mini documentation
229
-	$this->view->traps_in_config= PHP_BINARY . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
229
+	$this->view->traps_in_config=PHP_BINARY.' '.$this->Module()->getBaseDir().'/bin/trap_in.php';
230 230
 	
231
-	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
231
+	$this->view->installer=$this->Module()->getBaseDir().'/bin/installer.sh '
232 232
 	    . ' -c all ' 
233
-	    . ' -d ' . $this->Module()->getBaseDir()
234
-	    . ' -p ' . PHP_BINARY
235
-	    . ' -a ' . exec('whoami')
236
-	    . ' -w ' . Icinga::app()->getConfigDir();
233
+	    . ' -d '.$this->Module()->getBaseDir()
234
+	    . ' -p '.PHP_BINARY
235
+	    . ' -a '.exec('whoami')
236
+	    . ' -w '.Icinga::app()->getConfigDir();
237 237
 	        
238 238
 	// ******************* configuration form setup*******************
239
-	$this->view->form = $form = new TrapsConfigForm();
239
+	$this->view->form=$form=new TrapsConfigForm();
240 240
 	
241 241
 	// set default paths;
242
-	$this->view->form->setPaths($this->Module()->getBaseDir(),Icinga::app()->getConfigDir());
242
+	$this->view->form->setPaths($this->Module()->getBaseDir(), Icinga::app()->getConfigDir());
243 243
 	
244 244
 	// set default ido database
245
-	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring','backends')->get('icinga','resource'));
245
+	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring', 'backends')->get('icinga', 'resource'));
246 246
 	
247 247
 	// Make form handle request.
248 248
 	$form->setIniConfig($this->Config())
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
   public function createschemaAction()
255 255
   {
256 256
 	$this->checkModuleConfigPermission();
257
-	$this->getTabs()->add('create_schema',array(
257
+	$this->getTabs()->add('create_schema', array(
258 258
 		'active'	=> true,
259 259
 		'label'		=> $this->translate('Create Schema'),
260 260
 		'url'		=> Url::fromRequest()
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 		$dbName=$this->Config()->get('config', 'database');
276 276
 
277 277
 		try {
278
-		  $dbResource = ResourceFactory::getResourceConfig($dbName);
278
+		  $dbResource=ResourceFactory::getResourceConfig($dbName);
279 279
 		  $dbType=$dbResource->get('db');
280 280
 		  switch ($dbType) {
281 281
 		      case 'mysql':
@@ -287,34 +287,34 @@  discard block
 block discarded – undo
287 287
 		      default:
288 288
 		          throw new ConfigurationError('Unsuported database : '.$dbType);
289 289
 		  }
290
-		} catch (ConfigurationError $e )
290
+		} catch (ConfigurationError $e)
291 291
 		{
292
-		    printf("Database configuration error : %s",$e->getMessage());
292
+		    printf("Database configuration error : %s", $e->getMessage());
293 293
 		    return;
294 294
 		}
295 295
 		printf('<pre>');
296
-		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
296
+		require_once $this->Module()->getBaseDir().'/bin/trap_class.php';
297 297
 		
298 298
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
299 299
 		$debug_level=4;
300
-		$Trap = new Trap($icingaweb2_etc);
301
-		$Trap->setLogging($debug_level,'display');
300
+		$Trap=new Trap($icingaweb2_etc);
301
+		$Trap->setLogging($debug_level, 'display');
302 302
 		
303 303
 		$prefix=$this->Config()->get('config', 'database_prefix');
304 304
 		// schema file : <path>/SQL/schema_v<verion>.<dbtype>
305
-		$schema=$this->Module()->getBaseDir() . 
306
-		'/SQL/schema_v'. $this->getModuleConfig()->getDbCurVersion() . '.' . $dbFileExt;
305
+		$schema=$this->Module()->getBaseDir(). 
306
+		'/SQL/schema_v'.$this->getModuleConfig()->getDbCurVersion().'.'.$dbFileExt;
307 307
 		
308
-		$Trap->trapsDB->create_schema($schema,$prefix);
308
+		$Trap->trapsDB->create_schema($schema, $prefix);
309 309
 		echo '</pre>';
310 310
 	}
311
-	echo '<br><br>Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a>';
311
+	echo '<br><br>Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a>';
312 312
   }
313 313
 
314 314
   public function updateschemaAction()
315 315
   {
316 316
 	  $this->checkModuleConfigPermission();
317
-    	$this->getTabs()->add('get',array(
317
+    	$this->getTabs()->add('get', array(
318 318
     		'active'	=> true,
319 319
     		'label'		=> $this->translate('Update Schema'),
320 320
     		'url'		=> Url::fromRequest()
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
 	  
324 324
 	  $dberror=$this->getDb(true); // Get DB in test mode
325 325
 	  
326
-	  echo 'Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a><br><br>';
326
+	  echo 'Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a><br><br>';
327 327
 	  
328 328
 	  if ($dberror[0] == 0)
329 329
 	  {
@@ -336,40 +336,40 @@  discard block
 block discarded – undo
336 336
 	      return;
337 337
 	  }
338 338
       // setup
339
-	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
339
+	  require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
340 340
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
341 341
 	  $debug_level=4;
342
-	  $Trap = new Trap($icingaweb2_etc);
342
+	  $Trap=new Trap($icingaweb2_etc);
343 343
 	  
344 344
 	  
345 345
 	  $prefix=$this->Config()->get('config', 'database_prefix');
346
-	  $updateSchema=$this->Module()->getBaseDir() . '/SQL/';
346
+	  $updateSchema=$this->Module()->getBaseDir().'/SQL/';
347 347
 	  
348 348
 	  $target_version=$dberror[2];
349 349
 	  
350 350
 	  if ($this->params->get('msgok') == null) {
351 351
 	      // Check for messages and display if any
352 352
               echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
353
-	      $Trap->setLogging(2,'syslog');
354
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
353
+	      $Trap->setLogging(2, 'syslog');
354
+	      $message=$Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix, true);
355 355
 	      if ($message != '')
356 356
 	      {
357 357
 	          echo 'Note :<br><pre>';
358 358
 	          echo $message;
359 359
 	          echo '</pre>';
360 360
 	          echo '<br>';
361
-	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
361
+	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="'.Url::fromPath('trapdirector/settings/updateschema').'?msgok=1">Click here to update</a>';
362 362
 	          echo '<br>';
363 363
 	          return;
364 364
 	      }
365 365
 	  }
366 366
 	  
367
-	  $Trap->setLogging($debug_level,'display');
367
+	  $Trap->setLogging($debug_level, 'display');
368 368
 	  
369
-	  echo 'Updating schema to '. $target_version . ': <br>';
369
+	  echo 'Updating schema to '.$target_version.': <br>';
370 370
 	  echo '<pre>';
371 371
 	  	  
372
-	  $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix);
372
+	  $Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix);
373 373
 	  echo '</pre>';
374 374
   }  
375 375
 
@@ -377,26 +377,26 @@  discard block
 block discarded – undo
377 377
   {
378 378
       $psOutput=array();
379 379
       // First check is someone is listening to port 162. As not root, we can't have pid... 
380
-      exec('netstat -an |grep -E "udp.*:162"',$psOutput);
380
+      exec('netstat -an |grep -E "udp.*:162"', $psOutput);
381 381
       if (count($psOutput) == 0)
382 382
       {
383
-          return array(1,'Port UDP/162 is not open : snmptrapd must not be started');
383
+          return array(1, 'Port UDP/162 is not open : snmptrapd must not be started');
384 384
       }
385 385
       $psOutput=array();
386
-      exec('ps fax |grep snmptrapd |grep -v grep',$psOutput);
386
+      exec('ps fax |grep snmptrapd |grep -v grep', $psOutput);
387 387
       if (count($psOutput) == 0)
388 388
       {
389
-          return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
389
+          return array(1, "UDP/162 : OK, but no snmptrapd process (?)");
390 390
       }
391 391
       // Assume there is only one line... TODO : see if there is a better way to do this
392
-      $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
393
-      if (!preg_match('/-n/',$line))
394
-          return array(1,'snmptrapd has no -n option : '.$line);
395
-      if (!preg_match('/-O[^ ]*n/',$line))
396
-          return array(1,'snmptrapd has no -On option : '.$line);
397
-      if (!preg_match('/-O[^ ]*e/',$line))
398
-          return array(1,'snmptrapd has no -Oe option : '.$line);
392
+      $line=preg_replace('/^.*snmptrapd /', '', $psOutput[0]);
393
+      if (!preg_match('/-n/', $line))
394
+          return array(1, 'snmptrapd has no -n option : '.$line);
395
+      if (!preg_match('/-O[^ ]*n/', $line))
396
+          return array(1, 'snmptrapd has no -On option : '.$line);
397
+      if (!preg_match('/-O[^ ]*e/', $line))
398
+          return array(1, 'snmptrapd has no -Oe option : '.$line);
399 399
       
400
-      return array(0,'snmptrapd listening to UDP/162, options : '.$line);
400
+      return array(0, 'snmptrapd listening to UDP/162, options : '.$line);
401 401
   }
402 402
 }
Please login to merge, or discard this patch.
Braces   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -52,8 +52,7 @@  discard block
 block discarded – undo
52 52
               $this->Config()->saveIni();
53 53
               $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54 54
               //$emptyConfig=1;
55
-          }
56
-          catch (Exception $e)
55
+          } catch (Exception $e)
57 56
           {
58 57
               $this->view->configErrorDetected=$e->getMessage();
59 58
           }
@@ -130,8 +129,7 @@  discard block
 block discarded – undo
130 129
               $this->view->apimessage='API config : ' . $e->getMessage();
131 130
               $this->view->apimessageError=true;
132 131
           }
133
-      }
134
-      else
132
+      } else
135 133
       {
136 134
           $this->view->apimessage='API parameters not configured';
137 135
           $this->view->apimessageError=true;
@@ -266,8 +264,7 @@  discard block
 block discarded – undo
266 264
 	if ($dberror[0] == 0)
267 265
 	{
268 266
 		printf('Schema already exists');
269
-	}
270
-	else
267
+	} else
271 268
 	{
272 269
 		printf('Creating schema : <br>');
273 270
 
@@ -390,12 +387,15 @@  discard block
 block discarded – undo
390 387
       }
391 388
       // Assume there is only one line... TODO : see if there is a better way to do this
392 389
       $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
393
-      if (!preg_match('/-n/',$line))
394
-          return array(1,'snmptrapd has no -n option : '.$line);
395
-      if (!preg_match('/-O[^ ]*n/',$line))
396
-          return array(1,'snmptrapd has no -On option : '.$line);
397
-      if (!preg_match('/-O[^ ]*e/',$line))
398
-          return array(1,'snmptrapd has no -Oe option : '.$line);
390
+      if (!preg_match('/-n/',$line)) {
391
+                return array(1,'snmptrapd has no -n option : '.$line);
392
+      }
393
+      if (!preg_match('/-O[^ ]*n/',$line)) {
394
+                return array(1,'snmptrapd has no -On option : '.$line);
395
+      }
396
+      if (!preg_match('/-O[^ ]*e/',$line)) {
397
+                return array(1,'snmptrapd has no -Oe option : '.$line);
398
+      }
399 399
       
400 400
       return array(0,'snmptrapd listening to UDP/162, options : '.$line);
401 401
   }
Please login to merge, or discard this patch.
library/Trapdirector/Icinga2Api.php 3 patches
Braces   +5 added lines, -10 removed lines patch added patch discarded remove patch
@@ -74,8 +74,7 @@  discard block
 block discarded – undo
74 74
        try
75 75
         {
76 76
             $result=$this->request('GET', "", NULL, NULL);
77
-        } 
78
-        catch (Exception $e)
77
+        } catch (Exception $e)
79 78
         {
80 79
             return array(true, 'Error with API : '.$e->getMessage());
81 80
         }
@@ -165,8 +164,7 @@  discard block
 block discarded – undo
165 164
             if (property_exists($result,'status'))
166 165
             {
167 166
                 $message=$result->status;
168
-            }
169
-            else 
167
+            } else 
170 168
             {
171 169
                 $message="Unkown status";
172 170
             }
@@ -177,8 +175,7 @@  discard block
 block discarded – undo
177 175
             if (isset($result->results[0]))
178 176
             {
179 177
                 return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
180
-            }
181
-            else
178
+            } else
182 179
             {
183 180
                 return array(false,'Service not found');
184 181
             }
@@ -220,8 +217,7 @@  discard block
 block discarded – undo
220 217
             if (property_exists($result,'status'))
221 218
             {
222 219
                 throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
223
-            }
224
-            else
220
+            } else
225 221
             {
226 222
                 throw new Exception('Ret code ' .$result->error.' : Unkown status');
227 223
             }
@@ -266,8 +262,7 @@  discard block
 block discarded – undo
266 262
             if (property_exists($result,'status'))
267 263
             {
268 264
                 throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
269
-            }
270
-            else
265
+            } else
271 266
             {
272 267
                 throw new Exception('Ret code ' .$result->error.' : Unkown status');
273 268
             }
Please login to merge, or discard this patch.
Indentation   +332 added lines, -332 removed lines patch added patch discarded remove patch
@@ -8,363 +8,363 @@
 block discarded – undo
8 8
 
9 9
 class Icinga2API 
10 10
 {
11
-    protected $version = 'v1';      //< icinga2 api version
11
+	protected $version = 'v1';      //< icinga2 api version
12 12
     
13
-    protected $host;                //< icinga2 host name or IP
14
-    protected $port;                //< icinga2 api port
13
+	protected $host;                //< icinga2 host name or IP
14
+	protected $port;                //< icinga2 api port
15 15
     
16
-    protected $user;                //< user name
17
-    protected $pass;                //< user password
18
-    protected $usercert;            //< user key for certificate auth (NOT IMPLEMENTED)
19
-    protected $authmethod='pass';   //< Authentication : 'pass' or 'cert'
16
+	protected $user;                //< user name
17
+	protected $pass;                //< user password
18
+	protected $usercert;            //< user key for certificate auth (NOT IMPLEMENTED)
19
+	protected $authmethod='pass';   //< Authentication : 'pass' or 'cert'
20 20
 
21
-    protected $curl;
22
-    // http://php.net/manual/de/function.json-last-error.php#119985
23
-    protected $errorReference = [
24
-        JSON_ERROR_NONE => 'No error has occurred.',
25
-        JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
26
-        JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
27
-        JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded.',
28
-        JSON_ERROR_SYNTAX => 'Syntax error.',
29
-        JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded.',
30
-        JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded.',
31
-        JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
32
-        JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
33
-    ];
34
-    const JSON_UNKNOWN_ERROR = 'Unknown error.';
21
+	protected $curl;
22
+	// http://php.net/manual/de/function.json-last-error.php#119985
23
+	protected $errorReference = [
24
+		JSON_ERROR_NONE => 'No error has occurred.',
25
+		JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
26
+		JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
27
+		JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded.',
28
+		JSON_ERROR_SYNTAX => 'Syntax error.',
29
+		JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded.',
30
+		JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded.',
31
+		JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
32
+		JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
33
+	];
34
+	const JSON_UNKNOWN_ERROR = 'Unknown error.';
35 35
     
36
-    /**
37
-     * Creates Icinga2API object
38
-     * 
39
-     * @param string $host host name or IP
40
-     * @param number $port API port
41
-     */
42
-    public function __construct($host, $port = 5665)
43
-    {
44
-        $this->host=$host;
45
-        $this->port=$port;
46
-    }
47
-    /**
48
-     * Set user & pass
49
-     * @param string $user
50
-     * @param string $pass
51
-     */
52
-    public function setCredentials($user,$pass)
53
-    {
54
-        $this->user=$user;
55
-        $this->pass=$pass;
56
-        $this->authmethod='pass';
57
-    }
36
+	/**
37
+	 * Creates Icinga2API object
38
+	 * 
39
+	 * @param string $host host name or IP
40
+	 * @param number $port API port
41
+	 */
42
+	public function __construct($host, $port = 5665)
43
+	{
44
+		$this->host=$host;
45
+		$this->port=$port;
46
+	}
47
+	/**
48
+	 * Set user & pass
49
+	 * @param string $user
50
+	 * @param string $pass
51
+	 */
52
+	public function setCredentials($user,$pass)
53
+	{
54
+		$this->user=$user;
55
+		$this->pass=$pass;
56
+		$this->authmethod='pass';
57
+	}
58 58
     
59
-    /**
60
-     * Set user & certificate (NOT IMPLEMENTED @throws RuntimeException)
61
-     * @param string $user
62
-     * @param string $usercert
63
-     */
64
-    public function setCredentialskey($user,$usercert)
65
-    {
66
-        $this->user=$user;
67
-        $this->usercert=$usercert;
68
-        $this->authmethod='cert';
69
-        throw new RuntimeException('Certificate auth not implemented');
70
-    }
59
+	/**
60
+	 * Set user & certificate (NOT IMPLEMENTED @throws RuntimeException)
61
+	 * @param string $user
62
+	 * @param string $usercert
63
+	 */
64
+	public function setCredentialskey($user,$usercert)
65
+	{
66
+		$this->user=$user;
67
+		$this->usercert=$usercert;
68
+		$this->authmethod='cert';
69
+		throw new RuntimeException('Certificate auth not implemented');
70
+	}
71 71
 
72
-    public function test(array $permissions)
73
-    {
74
-       try
75
-        {
76
-            $result=$this->request('GET', "", NULL, NULL);
77
-        } 
78
-        catch (Exception $e)
79
-        {
80
-            return array(true, 'Error with API : '.$e->getMessage());
81
-        }
82
-        //var_dump($result);
83
-        $permOk=1;
84
-        $permMissing='';
85
-        if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
86
-        {
72
+	public function test(array $permissions)
73
+	{
74
+	   try
75
+		{
76
+			$result=$this->request('GET', "", NULL, NULL);
77
+		} 
78
+		catch (Exception $e)
79
+		{
80
+			return array(true, 'Error with API : '.$e->getMessage());
81
+		}
82
+		//var_dump($result);
83
+		$permOk=1;
84
+		$permMissing='';
85
+		if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
86
+		{
87 87
             
88
-            foreach ( $permissions as $mustPermission)
89
-            {
90
-                $curPermOK=0;
91
-                foreach ( $result->results[0]->permissions as $curPermission)
92
-                {
93
-                    $curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
94
-                    if (preg_match('#'.$curPermission.'#',$mustPermission))
95
-                    {
96
-                        $curPermOK=1;
97
-                        break;
98
-                    }
99
-                }
100
-                if ($curPermOK == 0)
101
-                {
102
-                    $permOk=0;
103
-                    $permMissing=$mustPermission;
104
-                    break;
105
-                }
106
-            }
107
-            if ($permOk == 0)
108
-            {
109
-                return array(true,'API connection OK, but missing permission : '.$permMissing);
110
-            }
111
-            return array(false,'API connection OK');
88
+			foreach ( $permissions as $mustPermission)
89
+			{
90
+				$curPermOK=0;
91
+				foreach ( $result->results[0]->permissions as $curPermission)
92
+				{
93
+					$curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
94
+					if (preg_match('#'.$curPermission.'#',$mustPermission))
95
+					{
96
+						$curPermOK=1;
97
+						break;
98
+					}
99
+				}
100
+				if ($curPermOK == 0)
101
+				{
102
+					$permOk=0;
103
+					$permMissing=$mustPermission;
104
+					break;
105
+				}
106
+			}
107
+			if ($permOk == 0)
108
+			{
109
+				return array(true,'API connection OK, but missing permission : '.$permMissing);
110
+			}
111
+			return array(false,'API connection OK');
112 112
             
113
-        }
114
-        return array(true,'API connection OK, but cannot get permissions');
115
-    }
113
+		}
114
+		return array(true,'API connection OK, but cannot get permissions');
115
+	}
116 116
     
117 117
     
118
-    protected function url($url) {
119
-        return sprintf('https://%s:%d/%s/%s', $this->host, $this->port, $this->version, $url);
120
-    }
118
+	protected function url($url) {
119
+		return sprintf('https://%s:%d/%s/%s', $this->host, $this->port, $this->version, $url);
120
+	}
121 121
     
122
-    /**
123
-     * Create or return curl ressource
124
-     * @throws Exception
125
-     * @return resource
126
-     */
127
-    protected function curl() {
128
-        if ($this->curl === null) {
129
-            $this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
130
-            if (!$this->curl) {
131
-                throw new Exception('CURL INIT ERROR: ' . curl_error($this->curl));
132
-            }
133
-        }
134
-        return $this->curl;
135
-    }
122
+	/**
123
+	 * Create or return curl ressource
124
+	 * @throws Exception
125
+	 * @return resource
126
+	 */
127
+	protected function curl() {
128
+		if ($this->curl === null) {
129
+			$this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
130
+			if (!$this->curl) {
131
+				throw new Exception('CURL INIT ERROR: ' . curl_error($this->curl));
132
+			}
133
+		}
134
+		return $this->curl;
135
+	}
136 136
 
137
-    /**
138
-     * Send a passive service check
139
-     * @param string $host : host name 
140
-     * @param string $service : service name
141
-     * @param int $state : state of service
142
-     * @param string $display : service passive check output
143
-     * @param string $perfdata : performance data as string
144
-     * @return array (status = true (oK) or false (nok), string message)
145
-     */
146
-    public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
147
-    {
148
-        //Send a POST request to the URL endpoint /v1/actions/process-check-result
149
-        //actions/process-check-result?service=example.localdomain!passive-ping6
150
-        $url='actions/process-check-result';
151
-        $body=array(
152
-            "filter"        => 'service.name=="'.$service.'" && service.host_name=="'.$host.'"',
153
-            'type'          => 'Service',
154
-            "exit_status"   => $state,
155
-            "plugin_output" => $display,
156
-            "performance_data" => $perfdata
157
-        );
158
-        try 
159
-        {
160
-            $result=$this->request('POST', $url, null, $body);
161
-        } catch (Exception $e) 
162
-        {
163
-            return array(false, $e->getMessage());
164
-        }
165
-        if (property_exists($result,'error') )
166
-        {
167
-            if (property_exists($result,'status'))
168
-            {
169
-                $message=$result->status;
170
-            }
171
-            else 
172
-            {
173
-                $message="Unkown status";
174
-            }
175
-            return array(false , 'Ret code ' .$result->error.' : '.$message);
176
-        }
177
-        if (property_exists($result, 'results'))
178
-        {
179
-            if (isset($result->results[0]))
180
-            {
181
-                return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
182
-            }
183
-            else
184
-            {
185
-                return array(false,'Service not found');
186
-            }
137
+	/**
138
+	 * Send a passive service check
139
+	 * @param string $host : host name 
140
+	 * @param string $service : service name
141
+	 * @param int $state : state of service
142
+	 * @param string $display : service passive check output
143
+	 * @param string $perfdata : performance data as string
144
+	 * @return array (status = true (oK) or false (nok), string message)
145
+	 */
146
+	public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
147
+	{
148
+		//Send a POST request to the URL endpoint /v1/actions/process-check-result
149
+		//actions/process-check-result?service=example.localdomain!passive-ping6
150
+		$url='actions/process-check-result';
151
+		$body=array(
152
+			"filter"        => 'service.name=="'.$service.'" && service.host_name=="'.$host.'"',
153
+			'type'          => 'Service',
154
+			"exit_status"   => $state,
155
+			"plugin_output" => $display,
156
+			"performance_data" => $perfdata
157
+		);
158
+		try 
159
+		{
160
+			$result=$this->request('POST', $url, null, $body);
161
+		} catch (Exception $e) 
162
+		{
163
+			return array(false, $e->getMessage());
164
+		}
165
+		if (property_exists($result,'error') )
166
+		{
167
+			if (property_exists($result,'status'))
168
+			{
169
+				$message=$result->status;
170
+			}
171
+			else 
172
+			{
173
+				$message="Unkown status";
174
+			}
175
+			return array(false , 'Ret code ' .$result->error.' : '.$message);
176
+		}
177
+		if (property_exists($result, 'results'))
178
+		{
179
+			if (isset($result->results[0]))
180
+			{
181
+				return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
182
+			}
183
+			else
184
+			{
185
+				return array(false,'Service not found');
186
+			}
187 187
             
188
-        }
189
-        return array(false,'Unkown result, open issue with this : '.print_r($result,true));
190
-    }
188
+		}
189
+		return array(false,'Unkown result, open issue with this : '.print_r($result,true));
190
+	}
191 191
  
192
-    /**
193
-     * return array of host by IP (4 or 6)
194
-     * @param string $ip
195
-     * @throws Exception
196
-     * @return array objects : array('__name','name','display_name')
197
-     */
198
-    public function getHostByIP($ip) 
199
-    {
200
-        /*
192
+	/**
193
+	 * return array of host by IP (4 or 6)
194
+	 * @param string $ip
195
+	 * @throws Exception
196
+	 * @return array objects : array('__name','name','display_name')
197
+	 */
198
+	public function getHostByIP($ip) 
199
+	{
200
+		/*
201 201
          *  curl -k -s -u  trapdirector:trapdirector -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts' 
202 202
          *  -d '{"filter":"host.group==\"test_trap\"","attrs": ["address" ,"address6"]}'
203 203
             
204 204
             {"results":[{"attrs":{"__name":"Icinga host","address":"127.0.0.1","display_name":"Icinga host","name":"Icinga host"},"joins":{},"meta":{},"name":"Icinga host","type":"Host"}]}
205 205
          */
206 206
         
207
-        $url='objects/hosts';
208
-        $body=array(
209
-            "filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
210
-            "attrs"         => array('__name','name','display_name')
211
-        );
212
-        try
213
-        {
214
-            $result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
215
-        } catch (Exception $e)
216
-        {
217
-            throw new Exception($e->getMessage());
218
-        }
207
+		$url='objects/hosts';
208
+		$body=array(
209
+			"filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
210
+			"attrs"         => array('__name','name','display_name')
211
+		);
212
+		try
213
+		{
214
+			$result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
215
+		} catch (Exception $e)
216
+		{
217
+			throw new Exception($e->getMessage());
218
+		}
219 219
         
220
-        if (property_exists($result,'error') )
221
-        {
222
-            if (property_exists($result,'status'))
223
-            {
224
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
225
-            }
226
-            else
227
-            {
228
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
229
-            }
230
-        }
231
-        if (property_exists($result, 'results'))
232
-        {
233
-            $numHost=0;
234
-            $hostArray=array();
235
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
236
-            {
237
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
238
-                $numHost++;
239
-            }
240
-            return $hostArray;            
241
-        }
242
-        throw new Exception('Unkown result');
243
-    }
220
+		if (property_exists($result,'error') )
221
+		{
222
+			if (property_exists($result,'status'))
223
+			{
224
+				throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
225
+			}
226
+			else
227
+			{
228
+				throw new Exception('Ret code ' .$result->error.' : Unkown status');
229
+			}
230
+		}
231
+		if (property_exists($result, 'results'))
232
+		{
233
+			$numHost=0;
234
+			$hostArray=array();
235
+			while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
236
+			{
237
+				$hostArray[$numHost] = $result->results[$numHost]->attrs;
238
+				$numHost++;
239
+			}
240
+			return $hostArray;            
241
+		}
242
+		throw new Exception('Unkown result');
243
+	}
244 244
 
245
-    /**
246
-     * Get all host and IP from hostgroup
247
-     * @param string $hostGroup
248
-     * @throws Exception
249
-     * @return array : attributes : address, address6, name
250
-     */
251
-    public function getHostsIPByHostGroup($hostGroup)
252
-    {        
253
-        $url='objects/hosts';
254
-        $body=array(
255
-            "filter"        => '\"'.$hostGroup.'\" in host.groups',
256
-            "attrs"         => array('address','address','name')
257
-        );
258
-        try
259
-        {
260
-            $result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
261
-        } catch (Exception $e)
262
-        {
263
-            throw new Exception($e->getMessage());
264
-        }
245
+	/**
246
+	 * Get all host and IP from hostgroup
247
+	 * @param string $hostGroup
248
+	 * @throws Exception
249
+	 * @return array : attributes : address, address6, name
250
+	 */
251
+	public function getHostsIPByHostGroup($hostGroup)
252
+	{        
253
+		$url='objects/hosts';
254
+		$body=array(
255
+			"filter"        => '\"'.$hostGroup.'\" in host.groups',
256
+			"attrs"         => array('address','address','name')
257
+		);
258
+		try
259
+		{
260
+			$result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
261
+		} catch (Exception $e)
262
+		{
263
+			throw new Exception($e->getMessage());
264
+		}
265 265
         
266
-        if (property_exists($result,'error') )
267
-        {
268
-            if (property_exists($result,'status'))
269
-            {
270
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
271
-            }
272
-            else
273
-            {
274
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
275
-            }
276
-        }
277
-        if (property_exists($result, 'results'))
278
-        {
279
-            $numHost=0;
280
-            $hostArray=array();
281
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
282
-            {
283
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
284
-                $hostArray[$numHost]->name = $result->results[$numHost]->name;
285
-                $numHost++;
286
-            }
287
-            return $hostArray;
288
-        }
289
-        throw new Exception('Unkown result');
290
-    }
266
+		if (property_exists($result,'error') )
267
+		{
268
+			if (property_exists($result,'status'))
269
+			{
270
+				throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
271
+			}
272
+			else
273
+			{
274
+				throw new Exception('Ret code ' .$result->error.' : Unkown status');
275
+			}
276
+		}
277
+		if (property_exists($result, 'results'))
278
+		{
279
+			$numHost=0;
280
+			$hostArray=array();
281
+			while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
282
+			{
283
+				$hostArray[$numHost] = $result->results[$numHost]->attrs;
284
+				$hostArray[$numHost]->name = $result->results[$numHost]->name;
285
+				$numHost++;
286
+			}
287
+			return $hostArray;
288
+		}
289
+		throw new Exception('Unkown result');
290
+	}
291 291
     
292
-    /**
293
-     * Send request to API
294
-     * @param string $method get/post/...
295
-     * @param string $url (after /v1/ )
296
-     * @param array $headers
297
-     * @param array $body 
298
-     * @throws Exception
299
-     * @return array
300
-     */
301
-    public function request($method, $url, $headers, $body) {
302
-        $auth = sprintf('%s:%s', $this->user, $this->pass);
303
-        $curlHeaders = array("Accept: application/json");
304
-        if ($body !== null) {
305
-            $body = json_encode($body);
306
-            array_push($curlHeaders, 'Content-Type: application/json');
307
-            //array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
308
-        }
309
-        //var_dump($body);
310
-        //var_dump($this->url($url));
311
-        if ($headers !== null) {
312
-            $curlFinalHeaders = array_merge($curlHeaders, $headers);
313
-        } else 
314
-        {
315
-            $curlFinalHeaders=$curlHeaders;
316
-        }
317
-        $curl = $this->curl();
318
-        $opts = array(
319
-            CURLOPT_URL		=> $this->url($url),
320
-            CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
321
-            CURLOPT_USERPWD		=> $auth,
322
-            CURLOPT_CUSTOMREQUEST	=> strtoupper($method),
323
-            CURLOPT_RETURNTRANSFER 	=> true,
324
-            CURLOPT_CONNECTTIMEOUT 	=> 10,
325
-            CURLOPT_SSL_VERIFYHOST 	=> false,
326
-            CURLOPT_SSL_VERIFYPEER 	=> false,
327
-        );
328
-        if ($body !== null) {
329
-            $opts[CURLOPT_POSTFIELDS] = $body;
330
-        }
331
-        curl_setopt_array($curl, $opts);
332
-        $res = curl_exec($curl);
333
-        if ($res === false) {
334
-            throw new Exception('CURL ERROR: ' . curl_error($curl));
335
-        }
336
-        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
337
-        if ($statusCode === 401) {
338
-            throw new Exception('Unable to authenticate, please check your API credentials');
339
-        }
340
-        return $this->fromJsonResult($res);
341
-    }
292
+	/**
293
+	 * Send request to API
294
+	 * @param string $method get/post/...
295
+	 * @param string $url (after /v1/ )
296
+	 * @param array $headers
297
+	 * @param array $body 
298
+	 * @throws Exception
299
+	 * @return array
300
+	 */
301
+	public function request($method, $url, $headers, $body) {
302
+		$auth = sprintf('%s:%s', $this->user, $this->pass);
303
+		$curlHeaders = array("Accept: application/json");
304
+		if ($body !== null) {
305
+			$body = json_encode($body);
306
+			array_push($curlHeaders, 'Content-Type: application/json');
307
+			//array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
308
+		}
309
+		//var_dump($body);
310
+		//var_dump($this->url($url));
311
+		if ($headers !== null) {
312
+			$curlFinalHeaders = array_merge($curlHeaders, $headers);
313
+		} else 
314
+		{
315
+			$curlFinalHeaders=$curlHeaders;
316
+		}
317
+		$curl = $this->curl();
318
+		$opts = array(
319
+			CURLOPT_URL		=> $this->url($url),
320
+			CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
321
+			CURLOPT_USERPWD		=> $auth,
322
+			CURLOPT_CUSTOMREQUEST	=> strtoupper($method),
323
+			CURLOPT_RETURNTRANSFER 	=> true,
324
+			CURLOPT_CONNECTTIMEOUT 	=> 10,
325
+			CURLOPT_SSL_VERIFYHOST 	=> false,
326
+			CURLOPT_SSL_VERIFYPEER 	=> false,
327
+		);
328
+		if ($body !== null) {
329
+			$opts[CURLOPT_POSTFIELDS] = $body;
330
+		}
331
+		curl_setopt_array($curl, $opts);
332
+		$res = curl_exec($curl);
333
+		if ($res === false) {
334
+			throw new Exception('CURL ERROR: ' . curl_error($curl));
335
+		}
336
+		$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
337
+		if ($statusCode === 401) {
338
+			throw new Exception('Unable to authenticate, please check your API credentials');
339
+		}
340
+		return $this->fromJsonResult($res);
341
+	}
342 342
     
343
-    /**
344
-     * 
345
-     * @param string $json json encoded 
346
-     * @throws Exception
347
-     * @return array json decoded
348
-     */
349
-    protected function fromJsonResult($json) {
350
-        $result = @json_decode($json);
351
-        //var_dump($json);
352
-        if ($result === null) {
353
-            throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
354
-        }
355
-        return $result;
356
-    }
343
+	/**
344
+	 * 
345
+	 * @param string $json json encoded 
346
+	 * @throws Exception
347
+	 * @return array json decoded
348
+	 */
349
+	protected function fromJsonResult($json) {
350
+		$result = @json_decode($json);
351
+		//var_dump($json);
352
+		if ($result === null) {
353
+			throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
354
+		}
355
+		return $result;
356
+	}
357 357
     
358
-    /**
359
-     * Return text error no json error
360
-     * @param string $errorCode
361
-     * @return string
362
-     */
363
-    protected function getLastJsonErrorMessage($errorCode) {
364
-        if (!array_key_exists($errorCode, $this->errorReference)) {
365
-            return self::JSON_UNKNOWN_ERROR;
366
-        }
367
-        return $this->errorReference[$errorCode];
368
-    }
358
+	/**
359
+	 * Return text error no json error
360
+	 * @param string $errorCode
361
+	 * @return string
362
+	 */
363
+	protected function getLastJsonErrorMessage($errorCode) {
364
+		if (!array_key_exists($errorCode, $this->errorReference)) {
365
+			return self::JSON_UNKNOWN_ERROR;
366
+		}
367
+		return $this->errorReference[$errorCode];
368
+	}
369 369
 }
370 370
 
Please login to merge, or discard this patch.
Spacing   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -8,19 +8,19 @@  discard block
 block discarded – undo
8 8
 
9 9
 class Icinga2API 
10 10
 {
11
-    protected $version = 'v1';      //< icinga2 api version
11
+    protected $version='v1'; //< icinga2 api version
12 12
     
13
-    protected $host;                //< icinga2 host name or IP
14
-    protected $port;                //< icinga2 api port
13
+    protected $host; //< icinga2 host name or IP
14
+    protected $port; //< icinga2 api port
15 15
     
16
-    protected $user;                //< user name
17
-    protected $pass;                //< user password
18
-    protected $usercert;            //< user key for certificate auth (NOT IMPLEMENTED)
19
-    protected $authmethod='pass';   //< Authentication : 'pass' or 'cert'
16
+    protected $user; //< user name
17
+    protected $pass; //< user password
18
+    protected $usercert; //< user key for certificate auth (NOT IMPLEMENTED)
19
+    protected $authmethod='pass'; //< Authentication : 'pass' or 'cert'
20 20
 
21 21
     protected $curl;
22 22
     // http://php.net/manual/de/function.json-last-error.php#119985
23
-    protected $errorReference = [
23
+    protected $errorReference=[
24 24
         JSON_ERROR_NONE => 'No error has occurred.',
25 25
         JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
26 26
         JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
         JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
32 32
         JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
33 33
     ];
34
-    const JSON_UNKNOWN_ERROR = 'Unknown error.';
34
+    const JSON_UNKNOWN_ERROR='Unknown error.';
35 35
     
36 36
     /**
37 37
      * Creates Icinga2API object
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
      * @param string $host host name or IP
40 40
      * @param number $port API port
41 41
      */
42
-    public function __construct($host, $port = 5665)
42
+    public function __construct($host, $port=5665)
43 43
     {
44 44
         $this->host=$host;
45 45
         $this->port=$port;
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
      * @param string $user
50 50
      * @param string $pass
51 51
      */
52
-    public function setCredentials($user,$pass)
52
+    public function setCredentials($user, $pass)
53 53
     {
54 54
         $this->user=$user;
55 55
         $this->pass=$pass;
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
      * @param string $user
62 62
      * @param string $usercert
63 63
      */
64
-    public function setCredentialskey($user,$usercert)
64
+    public function setCredentialskey($user, $usercert)
65 65
     {
66 66
         $this->user=$user;
67 67
         $this->usercert=$usercert;
@@ -85,13 +85,13 @@  discard block
 block discarded – undo
85 85
         if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
86 86
         {
87 87
             
88
-            foreach ( $permissions as $mustPermission)
88
+            foreach ($permissions as $mustPermission)
89 89
             {
90 90
                 $curPermOK=0;
91
-                foreach ( $result->results[0]->permissions as $curPermission)
91
+                foreach ($result->results[0]->permissions as $curPermission)
92 92
                 {
93
-                    $curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
94
-                    if (preg_match('#'.$curPermission.'#',$mustPermission))
93
+                    $curPermission=preg_replace('/\*/', '.*', $curPermission); // put * as .* to created a regexp
94
+                    if (preg_match('#'.$curPermission.'#', $mustPermission))
95 95
                     {
96 96
                         $curPermOK=1;
97 97
                         break;
@@ -106,12 +106,12 @@  discard block
 block discarded – undo
106 106
             }
107 107
             if ($permOk == 0)
108 108
             {
109
-                return array(true,'API connection OK, but missing permission : '.$permMissing);
109
+                return array(true, 'API connection OK, but missing permission : '.$permMissing);
110 110
             }
111
-            return array(false,'API connection OK');
111
+            return array(false, 'API connection OK');
112 112
             
113 113
         }
114
-        return array(true,'API connection OK, but cannot get permissions');
114
+        return array(true, 'API connection OK, but cannot get permissions');
115 115
     }
116 116
     
117 117
     
@@ -126,9 +126,9 @@  discard block
 block discarded – undo
126 126
      */
127 127
     protected function curl() {
128 128
         if ($this->curl === null) {
129
-            $this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
129
+            $this->curl=curl_init(sprintf('https://%s:%d', $this->host, $this->port));
130 130
             if (!$this->curl) {
131
-                throw new Exception('CURL INIT ERROR: ' . curl_error($this->curl));
131
+                throw new Exception('CURL INIT ERROR: '.curl_error($this->curl));
132 132
             }
133 133
         }
134 134
         return $this->curl;
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
      * @param string $perfdata : performance data as string
144 144
      * @return array (status = true (oK) or false (nok), string message)
145 145
      */
146
-    public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
146
+    public function serviceCheckResult($host, $service, $state, $display, $perfdata='')
147 147
     {
148 148
         //Send a POST request to the URL endpoint /v1/actions/process-check-result
149 149
         //actions/process-check-result?service=example.localdomain!passive-ping6
@@ -162,9 +162,9 @@  discard block
 block discarded – undo
162 162
         {
163 163
             return array(false, $e->getMessage());
164 164
         }
165
-        if (property_exists($result,'error') )
165
+        if (property_exists($result, 'error'))
166 166
         {
167
-            if (property_exists($result,'status'))
167
+            if (property_exists($result, 'status'))
168 168
             {
169 169
                 $message=$result->status;
170 170
             }
@@ -172,21 +172,21 @@  discard block
 block discarded – undo
172 172
             {
173 173
                 $message="Unkown status";
174 174
             }
175
-            return array(false , 'Ret code ' .$result->error.' : '.$message);
175
+            return array(false, 'Ret code '.$result->error.' : '.$message);
176 176
         }
177 177
         if (property_exists($result, 'results'))
178 178
         {
179 179
             if (isset($result->results[0]))
180 180
             {
181
-                return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
181
+                return array(true, 'code '.$result->results[0]->code.' : '.$result->results[0]->status);
182 182
             }
183 183
             else
184 184
             {
185
-                return array(false,'Service not found');
185
+                return array(false, 'Service not found');
186 186
             }
187 187
             
188 188
         }
189
-        return array(false,'Unkown result, open issue with this : '.print_r($result,true));
189
+        return array(false, 'Unkown result, open issue with this : '.print_r($result, true));
190 190
     }
191 191
  
192 192
     /**
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
         $url='objects/hosts';
208 208
         $body=array(
209 209
             "filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
210
-            "attrs"         => array('__name','name','display_name')
210
+            "attrs"         => array('__name', 'name', 'display_name')
211 211
         );
212 212
         try
213 213
         {
@@ -217,24 +217,24 @@  discard block
 block discarded – undo
217 217
             throw new Exception($e->getMessage());
218 218
         }
219 219
         
220
-        if (property_exists($result,'error') )
220
+        if (property_exists($result, 'error'))
221 221
         {
222
-            if (property_exists($result,'status'))
222
+            if (property_exists($result, 'status'))
223 223
             {
224
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
224
+                throw new Exception('Ret code '.$result->error.' : '.$result->status);
225 225
             }
226 226
             else
227 227
             {
228
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
228
+                throw new Exception('Ret code '.$result->error.' : Unkown status');
229 229
             }
230 230
         }
231 231
         if (property_exists($result, 'results'))
232 232
         {
233 233
             $numHost=0;
234 234
             $hostArray=array();
235
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
235
+            while (isset($result->results[$numHost]) && property_exists($result->results[$numHost], 'attrs'))
236 236
             {
237
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
237
+                $hostArray[$numHost]=$result->results[$numHost]->attrs;
238 238
                 $numHost++;
239 239
             }
240 240
             return $hostArray;            
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
         $url='objects/hosts';
254 254
         $body=array(
255 255
             "filter"        => '\"'.$hostGroup.'\" in host.groups',
256
-            "attrs"         => array('address','address','name')
256
+            "attrs"         => array('address', 'address', 'name')
257 257
         );
258 258
         try
259 259
         {
@@ -263,25 +263,25 @@  discard block
 block discarded – undo
263 263
             throw new Exception($e->getMessage());
264 264
         }
265 265
         
266
-        if (property_exists($result,'error') )
266
+        if (property_exists($result, 'error'))
267 267
         {
268
-            if (property_exists($result,'status'))
268
+            if (property_exists($result, 'status'))
269 269
             {
270
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
270
+                throw new Exception('Ret code '.$result->error.' : '.$result->status);
271 271
             }
272 272
             else
273 273
             {
274
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
274
+                throw new Exception('Ret code '.$result->error.' : Unkown status');
275 275
             }
276 276
         }
277 277
         if (property_exists($result, 'results'))
278 278
         {
279 279
             $numHost=0;
280 280
             $hostArray=array();
281
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
281
+            while (isset($result->results[$numHost]) && property_exists($result->results[$numHost], 'attrs'))
282 282
             {
283
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
284
-                $hostArray[$numHost]->name = $result->results[$numHost]->name;
283
+                $hostArray[$numHost]=$result->results[$numHost]->attrs;
284
+                $hostArray[$numHost]->name=$result->results[$numHost]->name;
285 285
                 $numHost++;
286 286
             }
287 287
             return $hostArray;
@@ -299,23 +299,23 @@  discard block
 block discarded – undo
299 299
      * @return array
300 300
      */
301 301
     public function request($method, $url, $headers, $body) {
302
-        $auth = sprintf('%s:%s', $this->user, $this->pass);
303
-        $curlHeaders = array("Accept: application/json");
302
+        $auth=sprintf('%s:%s', $this->user, $this->pass);
303
+        $curlHeaders=array("Accept: application/json");
304 304
         if ($body !== null) {
305
-            $body = json_encode($body);
305
+            $body=json_encode($body);
306 306
             array_push($curlHeaders, 'Content-Type: application/json');
307 307
             //array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
308 308
         }
309 309
         //var_dump($body);
310 310
         //var_dump($this->url($url));
311 311
         if ($headers !== null) {
312
-            $curlFinalHeaders = array_merge($curlHeaders, $headers);
312
+            $curlFinalHeaders=array_merge($curlHeaders, $headers);
313 313
         } else 
314 314
         {
315 315
             $curlFinalHeaders=$curlHeaders;
316 316
         }
317
-        $curl = $this->curl();
318
-        $opts = array(
317
+        $curl=$this->curl();
318
+        $opts=array(
319 319
             CURLOPT_URL		=> $this->url($url),
320 320
             CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
321 321
             CURLOPT_USERPWD		=> $auth,
@@ -326,14 +326,14 @@  discard block
 block discarded – undo
326 326
             CURLOPT_SSL_VERIFYPEER 	=> false,
327 327
         );
328 328
         if ($body !== null) {
329
-            $opts[CURLOPT_POSTFIELDS] = $body;
329
+            $opts[CURLOPT_POSTFIELDS]=$body;
330 330
         }
331 331
         curl_setopt_array($curl, $opts);
332
-        $res = curl_exec($curl);
332
+        $res=curl_exec($curl);
333 333
         if ($res === false) {
334
-            throw new Exception('CURL ERROR: ' . curl_error($curl));
334
+            throw new Exception('CURL ERROR: '.curl_error($curl));
335 335
         }
336
-        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
336
+        $statusCode=curl_getinfo($curl, CURLINFO_HTTP_CODE);
337 337
         if ($statusCode === 401) {
338 338
             throw new Exception('Unable to authenticate, please check your API credentials');
339 339
         }
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
      * @return array json decoded
348 348
      */
349 349
     protected function fromJsonResult($json) {
350
-        $result = @json_decode($json);
350
+        $result=@json_decode($json);
351 351
         //var_dump($json);
352 352
         if ($result === null) {
353 353
             throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
Please login to merge, or discard this patch.
application/controllers/HandlerController.php 3 patches
Indentation   +235 added lines, -236 removed lines patch added patch discarded remove patch
@@ -11,13 +11,12 @@  discard block
 block discarded – undo
11 11
 
12 12
 //use Icinga\Web\Form as Form;
13 13
 /** Rules management
14
-
15
-*/
14
+ */
16 15
 class HandlerController extends TrapsController
17 16
 {
18 17
 
19 18
 	/** index : list existing rules 
20
-	*/
19
+	 */
21 20
 	public function indexAction()
22 21
 	{	
23 22
 		$this->checkReadPermission();
@@ -39,23 +38,23 @@  discard block
 block discarded – undo
39 38
 	 */
40 39
 	public function testruleAction()
41 40
 	{
42
-	    $this->checkReadPermission();
43
-	    $this->getTabs()->add('get',array(
44
-	        'active'	=> true,
45
-	        'label'		=> $this->translate('Test Rule'),
46
-	        'url'		=> Url::fromRequest()
47
-	    ));
41
+		$this->checkReadPermission();
42
+		$this->getTabs()->add('get',array(
43
+			'active'	=> true,
44
+			'label'		=> $this->translate('Test Rule'),
45
+			'url'		=> Url::fromRequest()
46
+		));
48 47
 	    
49
-	    //$db = $this->getDb();
48
+		//$db = $this->getDb();
50 49
 
51
-	    if ($this->params->get('rule') !== null) 
52
-	    {
53
-	        $this->view->rule= $this->params->get('rule');
54
-	    }
55
-	    else
56
-	    {
57
-	        $this->view->rule='';
58
-	    }
50
+		if ($this->params->get('rule') !== null) 
51
+		{
52
+			$this->view->rule= $this->params->get('rule');
53
+		}
54
+		else
55
+		{
56
+			$this->view->rule='';
57
+		}
59 58
 	}
60 59
 	
61 60
 	/**
@@ -63,31 +62,31 @@  discard block
 block discarded – undo
63 62
 	 */
64 63
 	private function add_setup_vars()
65 64
 	{
66
-	    // variables to send to view
67
-	    $this->view->hostlist=array(); // host list to input datalist
68
-	    $this->view->hostname=''; // Host name in input text
69
-	    $this->view->serviceGet=false; // Set to true to get list of service if only one host set
70
-	    $this->view->serviceSet=null; // Select service in services select (must have serviceGet=true).
71
-	    $this->view->mainoid=''; // Trap OID
72
-	    $this->view->mib=''; // Trap mib
73
-	    $this->view->name=''; // Trap name
74
-	    $this->view->trapListForMIB=array(); // Trap list if mib exists for trap
75
-	    $this->view->objectList=array(); // objects sent with trap
76
-	    $this->view->display=''; // Initial display
77
-	    $this->view->rule=''; // rule display
78
-	    $this->view->revertOK=''; // revert OK in seconds
79
-	    $this->view->hostid=-1; // normally set by javascript serviceGet()
80
-	    $this->view->ruleid=-1; // Rule id in DB for update & delete
81
-	    $this->view->setToUpdate=false; // set form as update form
82
-	    $this->view->setRuleMatch=-1; // set action on rule match (default nothing)
83
-	    $this->view->setRuleNoMatch=-1; // set action on rule no match (default nothing)
65
+		// variables to send to view
66
+		$this->view->hostlist=array(); // host list to input datalist
67
+		$this->view->hostname=''; // Host name in input text
68
+		$this->view->serviceGet=false; // Set to true to get list of service if only one host set
69
+		$this->view->serviceSet=null; // Select service in services select (must have serviceGet=true).
70
+		$this->view->mainoid=''; // Trap OID
71
+		$this->view->mib=''; // Trap mib
72
+		$this->view->name=''; // Trap name
73
+		$this->view->trapListForMIB=array(); // Trap list if mib exists for trap
74
+		$this->view->objectList=array(); // objects sent with trap
75
+		$this->view->display=''; // Initial display
76
+		$this->view->rule=''; // rule display
77
+		$this->view->revertOK=''; // revert OK in seconds
78
+		$this->view->hostid=-1; // normally set by javascript serviceGet()
79
+		$this->view->ruleid=-1; // Rule id in DB for update & delete
80
+		$this->view->setToUpdate=false; // set form as update form
81
+		$this->view->setRuleMatch=-1; // set action on rule match (default nothing)
82
+		$this->view->setRuleNoMatch=-1; // set action on rule no match (default nothing)
84 83
 	    
85
-	    $this->view->selectGroup=false; // Select by group if true
86
-	    $this->view->hostgroupid=-1; // host group id
87
-	    $this->view->serviceGroupGet=false; // Get list of service for group (set serviceSet to select one)
84
+		$this->view->selectGroup=false; // Select by group if true
85
+		$this->view->hostgroupid=-1; // host group id
86
+		$this->view->serviceGroupGet=false; // Get list of service for group (set serviceSet to select one)
88 87
 	    
89
-	    $this->view->modifier=null;
90
-	    $this->view->modified=null;
88
+		$this->view->modifier=null;
89
+		$this->view->modified=null;
91 90
 	}
92 91
 	
93 92
 	/**
@@ -96,102 +95,102 @@  discard block
 block discarded – undo
96 95
 	 */
97 96
 	private function add_from_existing($trapid)
98 97
 	{
99
-	    /********** Setup from existing trap ***************/
100
-	    // Get the full trap info
101
-	    $trapDetail=$this->getTrapDetail($trapid);
98
+		/********** Setup from existing trap ***************/
99
+		// Get the full trap info
100
+		$trapDetail=$this->getTrapDetail($trapid);
102 101
 	    
103
-	    $hostfilter=$trapDetail->source_ip;
102
+		$hostfilter=$trapDetail->source_ip;
104 103
 	    
105
-	    // Get host
106
-	    try
107
-	    {
108
-	        $hosts=$this->getHostByIP($hostfilter);
109
-	    }
110
-	    catch (Exception $e)
111
-	    {
112
-	        $this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
113
-	    }
104
+		// Get host
105
+		try
106
+		{
107
+			$hosts=$this->getHostByIP($hostfilter);
108
+		}
109
+		catch (Exception $e)
110
+		{
111
+			$this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
112
+		}
114 113
 	    
115 114
 	    
116
-	    // if one unique host found -> put id text input
117
-	    if (count($hosts)==1) {
118
-	        $this->view->hostname=$hosts[0]->name;
119
-	        //$hostid=$hosts[0]->id;
120
-	        // Tell JS to get services when page is loaded
121
-	        $this->view->serviceGet=true;
115
+		// if one unique host found -> put id text input
116
+		if (count($hosts)==1) {
117
+			$this->view->hostname=$hosts[0]->name;
118
+			//$hostid=$hosts[0]->id;
119
+			// Tell JS to get services when page is loaded
120
+			$this->view->serviceGet=true;
122 121
 	        
123
-	    }
124
-	    else
125
-	    {
126
-	        foreach($hosts as $key=>$val)
127
-	        {
128
-	            array_push($this->view->hostlist,$hosts[$key]->name);
129
-	        }
130
-	    }
122
+		}
123
+		else
124
+		{
125
+			foreach($hosts as $key=>$val)
126
+			{
127
+				array_push($this->view->hostlist,$hosts[$key]->name);
128
+			}
129
+		}
131 130
 	    
132
-	    // set up trap oid and objects received by the trap
131
+		// set up trap oid and objects received by the trap
133 132
 	    
134
-	    $this->view->mainoid=$trapDetail->trap_oid;
135
-	    if ($trapDetail->trap_name_mib != null)
136
-	    {
137
-	        $this->view->mib=$trapDetail->trap_name_mib;
138
-	        $this->view->name=$trapDetail->trap_name;
139
-	        $this->view->trapListForMIB=$this->getMIB()
140
-	        ->getTrapList($trapDetail->trap_name_mib);
141
-	    }
133
+		$this->view->mainoid=$trapDetail->trap_oid;
134
+		if ($trapDetail->trap_name_mib != null)
135
+		{
136
+			$this->view->mib=$trapDetail->trap_name_mib;
137
+			$this->view->name=$trapDetail->trap_name;
138
+			$this->view->trapListForMIB=$this->getMIB()
139
+			->getTrapList($trapDetail->trap_name_mib);
140
+		}
142 141
 	    
143
-	    // Get all objects that can be in trap from MIB
144
-	    $allObjects=$this->getMIB()->getObjectList($trapDetail->trap_oid);
145
-	    // Get all objects in current Trap
146
-	    $currentTrapObjects=$this->getTrapobjects($trapid);
147
-	    $oid_index=1;
148
-	    foreach ($currentTrapObjects as $key => $val)
149
-	    {
150
-	        $currentObjectType='Unknown';
151
-	        $currentObjectTypeEnum='Unknown';
152
-	        if (isset($allObjects[$val->oid]['type']))
153
-	        {
154
-	            $currentObjectType=$allObjects[$val->oid]['type'];
155
-	            $currentObjectTypeEnum=$allObjects[$val->oid]['type_enum'];
156
-	        }
157
-	        $currentObject=array(
158
-	            $oid_index,
159
-	            $val->oid,
160
-	            $val->oid_name_mib,
161
-	            $val->oid_name,
162
-	            $val->value,
163
-	            $currentObjectType,
164
-	            $currentObjectTypeEnum
165
-	        );
166
-	        $oid_index++;
167
-	        array_push($this->view->objectList,$currentObject);
168
-	        // set currrent object to null in allObjects
169
-	        if (isset($allObjects[$val->oid]))
170
-	        {
171
-	            $allObjects[$val->oid]=null;
172
-	        }
173
-	    }
174
-	    if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
175
-	    {
176
-	        foreach ($allObjects as $key => $val)
177
-	        {
178
-	            if ($val==null) { continue; }
179
-	            array_push($this->view->objectList, array(
180
-	                $oid_index,
181
-	                $key,
182
-	                $allObjects[$key]['mib'],
183
-	                $allObjects[$key]['name'],
184
-	                '',
185
-	                $allObjects[$key]['type'],
186
-	                $allObjects[$key]['type_enum']
187
-	            ));
188
-	            $oid_index++;
189
-	        }
190
-	    }
142
+		// Get all objects that can be in trap from MIB
143
+		$allObjects=$this->getMIB()->getObjectList($trapDetail->trap_oid);
144
+		// Get all objects in current Trap
145
+		$currentTrapObjects=$this->getTrapobjects($trapid);
146
+		$oid_index=1;
147
+		foreach ($currentTrapObjects as $key => $val)
148
+		{
149
+			$currentObjectType='Unknown';
150
+			$currentObjectTypeEnum='Unknown';
151
+			if (isset($allObjects[$val->oid]['type']))
152
+			{
153
+				$currentObjectType=$allObjects[$val->oid]['type'];
154
+				$currentObjectTypeEnum=$allObjects[$val->oid]['type_enum'];
155
+			}
156
+			$currentObject=array(
157
+				$oid_index,
158
+				$val->oid,
159
+				$val->oid_name_mib,
160
+				$val->oid_name,
161
+				$val->value,
162
+				$currentObjectType,
163
+				$currentObjectTypeEnum
164
+			);
165
+			$oid_index++;
166
+			array_push($this->view->objectList,$currentObject);
167
+			// set currrent object to null in allObjects
168
+			if (isset($allObjects[$val->oid]))
169
+			{
170
+				$allObjects[$val->oid]=null;
171
+			}
172
+		}
173
+		if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
174
+		{
175
+			foreach ($allObjects as $key => $val)
176
+			{
177
+				if ($val==null) { continue; }
178
+				array_push($this->view->objectList, array(
179
+					$oid_index,
180
+					$key,
181
+					$allObjects[$key]['mib'],
182
+					$allObjects[$key]['name'],
183
+					'',
184
+					$allObjects[$key]['type'],
185
+					$allObjects[$key]['type_enum']
186
+				));
187
+				$oid_index++;
188
+			}
189
+		}
191 190
 	    
192
-	    // Add a simple display
193
-	    $this->view->display='Trap '.$trapDetail->trap_name.' received';
194
-	    $this->view->create_basic_rule=true;
191
+		// Add a simple display
192
+		$this->view->display='Trap '.$trapDetail->trap_name.' received';
193
+		$this->view->create_basic_rule=true;
195 194
 	}
196 195
 
197 196
 	/**
@@ -200,29 +199,29 @@  discard block
 block discarded – undo
200 199
 	 */
201 200
 	private function add_check_host_exists($ruleDetail)
202 201
 	{
203
-	    // Check if hostname still exists
204
-	    $host_get=$this->getHostByName($this->view->hostname);
202
+		// Check if hostname still exists
203
+		$host_get=$this->getHostByName($this->view->hostname);
205 204
 	    
206
-	    if (count($host_get)==0)
207
-	    {
208
-	        $this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
209
-	        $this->view->serviceGet=false;
210
-	    }
211
-	    else
212
-	    {
213
-	        // Tell JS to get services when page is loaded
214
-	        $this->view->serviceGet=true;
215
-	        // get service id for form to set :
216
-	        $serviceID=$this->getServiceIDByName($this->view->hostname,$ruleDetail->service_name);
217
-	        if (count($serviceID) ==0)
218
-	        {
219
-	            $this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
220
-	        }
221
-	        else
222
-	        {
223
-	            $this->view->serviceSet=$serviceID[0]->id;
224
-	        }
225
-	    }
205
+		if (count($host_get)==0)
206
+		{
207
+			$this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
208
+			$this->view->serviceGet=false;
209
+		}
210
+		else
211
+		{
212
+			// Tell JS to get services when page is loaded
213
+			$this->view->serviceGet=true;
214
+			// get service id for form to set :
215
+			$serviceID=$this->getServiceIDByName($this->view->hostname,$ruleDetail->service_name);
216
+			if (count($serviceID) ==0)
217
+			{
218
+				$this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
219
+			}
220
+			else
221
+			{
222
+				$this->view->serviceSet=$serviceID[0]->id;
223
+			}
224
+		}
226 225
 	}
227 226
 
228 227
 	/**
@@ -231,33 +230,33 @@  discard block
 block discarded – undo
231 230
 	 */
232 231
 	private function add_check_hostgroup_exists($ruleDetail)
233 232
 	{
234
-	    // Check if groupe exists
235
-	    $group_get=$this->getHostGroupByName($this->view->hostgroupname);
236
-	    if (count($group_get)==0)
237
-	    {
238
-	        $this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
239
-	        $this->view->serviceGroupGet=false;
240
-	    }
241
-	    else
242
-	    {
243
-	        $grpServices=$this->getServicesByHostGroupid($group_get[0]->id);
244
-	        $foundGrpService=0;
245
-	        foreach ($grpServices as $grpService)
246
-	        {
247
-	            if ($grpService[0] == $ruleDetail->service_name)
248
-	            {
249
-	                $foundGrpService=1;
250
-	                $this->view->serviceSet=$ruleDetail->service_name;
251
-	            }
252
-	        }
233
+		// Check if groupe exists
234
+		$group_get=$this->getHostGroupByName($this->view->hostgroupname);
235
+		if (count($group_get)==0)
236
+		{
237
+			$this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
238
+			$this->view->serviceGroupGet=false;
239
+		}
240
+		else
241
+		{
242
+			$grpServices=$this->getServicesByHostGroupid($group_get[0]->id);
243
+			$foundGrpService=0;
244
+			foreach ($grpServices as $grpService)
245
+			{
246
+				if ($grpService[0] == $ruleDetail->service_name)
247
+				{
248
+					$foundGrpService=1;
249
+					$this->view->serviceSet=$ruleDetail->service_name;
250
+				}
251
+			}
253 252
 	        
254
-	        // Tell JS to get services when page is loaded
255
-	        $this->view->serviceGroupGet=true;
256
-	        if ($foundGrpService==0)
257
-	        {
258
-	            $this->view->warning_message.=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
259
-	        }
260
-	    }
253
+			// Tell JS to get services when page is loaded
254
+			$this->view->serviceGroupGet=true;
255
+			if ($foundGrpService==0)
256
+			{
257
+				$this->view->warning_message.=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
258
+			}
259
+		}
261 260
 	}
262 261
 	
263 262
 	/**
@@ -269,48 +268,48 @@  discard block
 block discarded – undo
269 268
 	 */
270 269
 	private function add_create_trap_object_list(&$display, &$rule)
271 270
 	{
272
-	    $curObjectList=array();
273
-	    $index=1;
274
-	    // check in display & rule for : OID(<oid>)
275
-	    $matches=array();
276
-	    while ( preg_match('/_OID\(([\.0-9]+)\)/',$display,$matches) ||
277
-	        preg_match('/_OID\(([\.0-9]+)\)/',$rule,$matches))
278
-	    {
279
-	        $curOid=$matches[1];
280
-	        if (($object=$this->getMIB()->translateOID($curOid)) != null)
281
-	        {
282
-	            array_push($curObjectList, array(
283
-	                $index,
284
-	                $curOid,
285
-	                $object['mib'],
286
-	                $object['name'],
287
-	                '',
288
-	                $object['type'],
289
-	                $object['type_enum']
290
-	            ));
291
-	        }
292
-	        else
293
-	        {
294
-	            array_push($curObjectList, array(
295
-	                $index,
296
-	                $curOid,
297
-	                'not found',
298
-	                'not found',
299
-	                '',
300
-	                'not found'
301
-	            ));
302
-	        }
303
-	        $display=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$display);
304
-	        $rule=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$rule);
305
-	        $index++;
306
-	    }
307
-	    return $curObjectList;
271
+		$curObjectList=array();
272
+		$index=1;
273
+		// check in display & rule for : OID(<oid>)
274
+		$matches=array();
275
+		while ( preg_match('/_OID\(([\.0-9]+)\)/',$display,$matches) ||
276
+			preg_match('/_OID\(([\.0-9]+)\)/',$rule,$matches))
277
+		{
278
+			$curOid=$matches[1];
279
+			if (($object=$this->getMIB()->translateOID($curOid)) != null)
280
+			{
281
+				array_push($curObjectList, array(
282
+					$index,
283
+					$curOid,
284
+					$object['mib'],
285
+					$object['name'],
286
+					'',
287
+					$object['type'],
288
+					$object['type_enum']
289
+				));
290
+			}
291
+			else
292
+			{
293
+				array_push($curObjectList, array(
294
+					$index,
295
+					$curOid,
296
+					'not found',
297
+					'not found',
298
+					'',
299
+					'not found'
300
+				));
301
+			}
302
+			$display=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$display);
303
+			$rule=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$rule);
304
+			$index++;
305
+		}
306
+		return $curObjectList;
308 307
 	}
309 308
 	
310 309
 	/** Add a handler  
311
-	*	Get params fromid : setup from existing trap (id of trap table)
312
-	*	Get param ruleid : edit from existing handler (id of rule table)
313
-	*/
310
+	 *	Get params fromid : setup from existing trap (id of trap table)
311
+	 *	Get param ruleid : edit from existing handler (id of rule table)
312
+	 */
314 313
 	public function addAction()
315 314
 	{
316 315
 		$this->checkConfigPermission();
@@ -329,8 +328,8 @@  discard block
 block discarded – undo
329 328
 		//$this->view->trapvalues=false; // Set to true to display 'value' colum in objects
330 329
 		
331 330
 		if (($trapid = $this->params->get('fromid')) !== null) {
332
-		    /********** Setup from existing trap ***************/
333
-            $this->add_from_existing($trapid);
331
+			/********** Setup from existing trap ***************/
332
+			$this->add_from_existing($trapid);
334 333
 			return;
335 334
 		}
336 335
 		
@@ -355,14 +354,14 @@  discard block
 block discarded – undo
355 354
 			$this->view->warning_message='';
356 355
 			if ($this->view->hostname != null)
357 356
 			{
358
-			    $this->view->selectGroup=false;
359
-			    // Check if hostname still exists
360
-			    $this->add_check_host_exists($ruleDetail);
357
+				$this->view->selectGroup=false;
358
+				// Check if hostname still exists
359
+				$this->add_check_host_exists($ruleDetail);
361 360
 			}
362 361
 			else
363 362
 			{
364
-			    $this->view->selectGroup=true;
365
-			    $this->add_check_hostgroup_exists($ruleDetail); //  Check if groupe exists				
363
+				$this->view->selectGroup=true;
364
+				$this->add_check_hostgroup_exists($ruleDetail); //  Check if groupe exists				
366 365
 			}
367 366
 			
368 367
 			$this->view->mainoid=$ruleDetail->trap_oid;
@@ -390,9 +389,9 @@  discard block
 block discarded – undo
390 389
 	}
391 390
 	
392 391
 	/** Validate form and output message to user  
393
-	*	@param in postdata 
394
-	* 	@return string status : OK / <Message>
395
-	**/
392
+	 *	@param in postdata 
393
+	 * 	@return string status : OK / <Message>
394
+	 **/
396 395
 	protected function handlerformAction()
397 396
 	{
398 397
 		$postData=$this->getRequest()->getPost();
@@ -433,7 +432,7 @@  discard block
 block discarded – undo
433 432
 			//$this->Module()->
434 433
 			$this->_helper->json(array(
435 434
 				'status'=>'OK',
436
-			    'redirect'=>'trapdirector/handler'
435
+				'redirect'=>'trapdirector/handler'
437 436
 			      
438 437
 			));
439 438
 		}		
@@ -517,9 +516,9 @@  discard block
 block discarded – undo
517 516
 	}
518 517
 
519 518
 	/** Get trap detail by trapid. 
520
-	*	@param integer $trapid : id of trap in received table
521
-	*	@return array (objects)
522
-	*/
519
+	 *	@param integer $trapid : id of trap in received table
520
+	 *	@return array (objects)
521
+	 */
523 522
 	protected function getTrapDetail($trapid) 
524 523
 	{
525 524
 		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
@@ -551,9 +550,9 @@  discard block
 block discarded – undo
551 550
 	}
552 551
 
553 552
 	/** Get trap objects
554
-	*	@param integer $trapid : trap id
555
-	* 	@return array : full column in db of trap id
556
-	*/
553
+	 *	@param integer $trapid : trap id
554
+	 * 	@return array : full column in db of trap id
555
+	 */
557 556
 	protected function getTrapobjects($trapid)
558 557
 	{	
559 558
 		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
@@ -584,9 +583,9 @@  discard block
 block discarded – undo
584 583
 	}
585 584
 
586 585
 	/** Get rule detail by ruleid.
587
-	*	@param integer $ruleid int id of rule in rule table
588
-	*	@return array : column objects in db
589
-	*/
586
+	 *	@param integer $ruleid int id of rule in rule table
587
+	 *	@return array : column objects in db
588
+	 */
590 589
 	protected function getRuleDetail($ruleid) 
591 590
 	{
592 591
 		if (!preg_match('/^[0-9]+$/',$ruleid)) { throw new Exception('Invalid id');  }
@@ -613,7 +612,7 @@  discard block
 block discarded – undo
613 612
 	}
614 613
 
615 614
 	/** Setup tabs for rules 
616
-	*/
615
+	 */
617 616
 	protected function prepareTabs()
618 617
 	{
619 618
 		return $this->getTabs()->add('status', array(
Please login to merge, or discard this patch.
Spacing   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -23,14 +23,14 @@  discard block
 block discarded – undo
23 23
 		$this->checkReadPermission();
24 24
 		$this->prepareTabs()->activate('status');
25 25
 
26
-		$db = $this->getDb();
26
+		$db=$this->getDb();
27 27
 		$this->getHandlerListTable()->setConnection($db);
28 28
 		$this->getHandlerListTable()->setMibloader($this->getMIB());
29 29
 		// Apply pagination limits 
30
-		$this->view->table=$this->applyPaginationLimits($this->getHandlerListTable(),$this->getModuleConfig()->itemListDisplay());		
30
+		$this->view->table=$this->applyPaginationLimits($this->getHandlerListTable(), $this->getModuleConfig()->itemListDisplay());		
31 31
 		
32 32
 		// Set Filter
33
-		$this->view->filterEditor = $this->getHandlerListTable()->getFilterEditor($this->getRequest());		
33
+		$this->view->filterEditor=$this->getHandlerListTable()->getFilterEditor($this->getRequest());		
34 34
 	
35 35
 		//$this->displayExitError('Handler/indexAction','Not implemented');
36 36
 	}
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
 	public function testruleAction()
41 41
 	{
42 42
 	    $this->checkReadPermission();
43
-	    $this->getTabs()->add('get',array(
43
+	    $this->getTabs()->add('get', array(
44 44
 	        'active'	=> true,
45 45
 	        'label'		=> $this->translate('Test Rule'),
46 46
 	        'url'		=> Url::fromRequest()
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
 
51 51
 	    if ($this->params->get('rule') !== null) 
52 52
 	    {
53
-	        $this->view->rule= $this->params->get('rule');
53
+	        $this->view->rule=$this->params->get('rule');
54 54
 	    }
55 55
 	    else
56 56
 	    {
@@ -109,12 +109,12 @@  discard block
 block discarded – undo
109 109
 	    }
110 110
 	    catch (Exception $e)
111 111
 	    {
112
-	        $this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
112
+	        $this->displayExitError('Add handler : get host by IP/Name ', $e->getMessage());
113 113
 	    }
114 114
 	    
115 115
 	    
116 116
 	    // if one unique host found -> put id text input
117
-	    if (count($hosts)==1) {
117
+	    if (count($hosts) == 1) {
118 118
 	        $this->view->hostname=$hosts[0]->name;
119 119
 	        //$hostid=$hosts[0]->id;
120 120
 	        // Tell JS to get services when page is loaded
@@ -123,9 +123,9 @@  discard block
 block discarded – undo
123 123
 	    }
124 124
 	    else
125 125
 	    {
126
-	        foreach($hosts as $key=>$val)
126
+	        foreach ($hosts as $key=>$val)
127 127
 	        {
128
-	            array_push($this->view->hostlist,$hosts[$key]->name);
128
+	            array_push($this->view->hostlist, $hosts[$key]->name);
129 129
 	        }
130 130
 	    }
131 131
 	    
@@ -164,18 +164,18 @@  discard block
 block discarded – undo
164 164
 	            $currentObjectTypeEnum
165 165
 	        );
166 166
 	        $oid_index++;
167
-	        array_push($this->view->objectList,$currentObject);
167
+	        array_push($this->view->objectList, $currentObject);
168 168
 	        // set currrent object to null in allObjects
169 169
 	        if (isset($allObjects[$val->oid]))
170 170
 	        {
171 171
 	            $allObjects[$val->oid]=null;
172 172
 	        }
173 173
 	    }
174
-	    if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
174
+	    if ($allObjects != null) // in case trap doesn't have objects or is not resolved
175 175
 	    {
176 176
 	        foreach ($allObjects as $key => $val)
177 177
 	        {
178
-	            if ($val==null) { continue; }
178
+	            if ($val == null) { continue; }
179 179
 	            array_push($this->view->objectList, array(
180 180
 	                $oid_index,
181 181
 	                $key,
@@ -203,9 +203,9 @@  discard block
 block discarded – undo
203 203
 	    // Check if hostname still exists
204 204
 	    $host_get=$this->getHostByName($this->view->hostname);
205 205
 	    
206
-	    if (count($host_get)==0)
206
+	    if (count($host_get) == 0)
207 207
 	    {
208
-	        $this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
208
+	        $this->view->warning_message='Host '.$this->view->hostname.' doesn\'t exists anymore';
209 209
 	        $this->view->serviceGet=false;
210 210
 	    }
211 211
 	    else
@@ -213,10 +213,10 @@  discard block
 block discarded – undo
213 213
 	        // Tell JS to get services when page is loaded
214 214
 	        $this->view->serviceGet=true;
215 215
 	        // get service id for form to set :
216
-	        $serviceID=$this->getServiceIDByName($this->view->hostname,$ruleDetail->service_name);
217
-	        if (count($serviceID) ==0)
216
+	        $serviceID=$this->getServiceIDByName($this->view->hostname, $ruleDetail->service_name);
217
+	        if (count($serviceID) == 0)
218 218
 	        {
219
-	            $this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
219
+	            $this->view->warning_message=' Service '.$ruleDetail->service_name.' doesn\'t exists anymore';
220 220
 	        }
221 221
 	        else
222 222
 	        {
@@ -233,9 +233,9 @@  discard block
 block discarded – undo
233 233
 	{
234 234
 	    // Check if groupe exists
235 235
 	    $group_get=$this->getHostGroupByName($this->view->hostgroupname);
236
-	    if (count($group_get)==0)
236
+	    if (count($group_get) == 0)
237 237
 	    {
238
-	        $this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
238
+	        $this->view->warning_message='HostGroup '.$this->view->hostgroupname.' doesn\'t exists anymore';
239 239
 	        $this->view->serviceGroupGet=false;
240 240
 	    }
241 241
 	    else
@@ -253,9 +253,9 @@  discard block
 block discarded – undo
253 253
 	        
254 254
 	        // Tell JS to get services when page is loaded
255 255
 	        $this->view->serviceGroupGet=true;
256
-	        if ($foundGrpService==0)
256
+	        if ($foundGrpService == 0)
257 257
 	        {
258
-	            $this->view->warning_message.=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
258
+	            $this->view->warning_message.=' Service '.$ruleDetail->service_name.' doesn\'t exists anymore';
259 259
 	        }
260 260
 	    }
261 261
 	}
@@ -273,8 +273,8 @@  discard block
 block discarded – undo
273 273
 	    $index=1;
274 274
 	    // check in display & rule for : OID(<oid>)
275 275
 	    $matches=array();
276
-	    while ( preg_match('/_OID\(([\.0-9]+)\)/',$display,$matches) ||
277
-	        preg_match('/_OID\(([\.0-9]+)\)/',$rule,$matches))
276
+	    while (preg_match('/_OID\(([\.0-9]+)\)/', $display, $matches) ||
277
+	        preg_match('/_OID\(([\.0-9]+)\)/', $rule, $matches))
278 278
 	    {
279 279
 	        $curOid=$matches[1];
280 280
 	        if (($object=$this->getMIB()->translateOID($curOid)) != null)
@@ -300,8 +300,8 @@  discard block
 block discarded – undo
300 300
 	                'not found'
301 301
 	            ));
302 302
 	        }
303
-	        $display=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$display);
304
-	        $rule=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$rule);
303
+	        $display=preg_replace('/_OID\('.$curOid.'\)/', '\$'.$index.'\$', $display);
304
+	        $rule=preg_replace('/_OID\('.$curOid.'\)/', '\$'.$index.'\$', $rule);
305 305
 	        $index++;
306 306
 	    }
307 307
 	    return $curObjectList;
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
 	{
316 316
 		$this->checkConfigPermission();
317 317
 		// set up tab
318
-		$this->getTabs()->add('get',array(
318
+		$this->getTabs()->add('get', array(
319 319
 			'active'	=> true,
320 320
 			'label'		=> $this->translate('Add handler'),
321 321
 			'url'		=> Url::fromRequest()
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
 		
329 329
 		//$this->view->trapvalues=false; // Set to true to display 'value' colum in objects
330 330
 		
331
-		if (($trapid = $this->params->get('fromid')) !== null) {
331
+		if (($trapid=$this->params->get('fromid')) !== null) {
332 332
 		    /********** Setup from existing trap ***************/
333 333
             $this->add_from_existing($trapid);
334 334
 			return;
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
 			$this->view->setRuleMatch=$ruleDetail->action_match;
349 349
 			$this->view->setRuleNoMatch=$ruleDetail->action_nomatch;
350 350
 			$this->view->hostgroupname=$ruleDetail->host_group_name;
351
-			$this->view->modified=gmdate("Y-m-d\TH:i:s\Z",$ruleDetail->modified);
351
+			$this->view->modified=gmdate("Y-m-d\TH:i:s\Z", $ruleDetail->modified);
352 352
 			$this->view->modifier=$ruleDetail->modifier;
353 353
 			
354 354
 			// Warning message if host/service don't exists anymore
@@ -400,26 +400,26 @@  discard block
 block discarded – undo
400 400
 	
401 401
 		$params=array(
402 402
 			// id (also db) => 	array('post' => post id, 'val' => default val, 'db' => send to table)
403
-			'hostgroup'		=>	array('post' => 'hostgroup','db'=>false),
404
-			'db_rule'		=>	array('post' => 'db_rule','db'=>false),
405
-			'hostid'		=>	array('post' => 'hostid','db'=>false),
406
-			'host_name'		=>	array('post' => 'hostname','val' => null,'db'=>true),
407
-			'host_group_name'=>	array('post' => null,'val' => null,'db'=>true),
408
-			'serviceid'		=>	array('post' => 'serviceid','db'=>false),
409
-			'service_name'	=>	array('post' => 'serviceName','db'=>true),
410
-			'trap_oid'		=>	array('post' => 'oid','db'=>true),
411
-			'revert_ok'		=>	array('post' => 'revertOK','val' => 0,'db'=>true),
412
-			'display'		=>	array('post' => 'display','val' => '','db'=>true),
413
-			'rule'			=>	array('post' => 'rule','val' => '','db'=>true),			
414
-			'action_match'	=>	array('post' => 'ruleMatch','val' => -1,'db'=>true),
415
-			'action_nomatch'=>	array('post' => 'ruleNoMatch','val' => -1,'db'=>true),					
416
-			'ip4'			=>	array('post' => null,'val' => null,'db'=>true),
417
-			'ip6'			=>	array('post' => null,'val' => null,'db'=>true),
418
-			'action_form'	=>	array('post' => 'action_form','db'=>false)
403
+			'hostgroup'		=>	array('post' => 'hostgroup', 'db'=>false),
404
+			'db_rule'		=>	array('post' => 'db_rule', 'db'=>false),
405
+			'hostid'		=>	array('post' => 'hostid', 'db'=>false),
406
+			'host_name'		=>	array('post' => 'hostname', 'val' => null, 'db'=>true),
407
+			'host_group_name'=>	array('post' => null, 'val' => null, 'db'=>true),
408
+			'serviceid'		=>	array('post' => 'serviceid', 'db'=>false),
409
+			'service_name'	=>	array('post' => 'serviceName', 'db'=>true),
410
+			'trap_oid'		=>	array('post' => 'oid', 'db'=>true),
411
+			'revert_ok'		=>	array('post' => 'revertOK', 'val' => 0, 'db'=>true),
412
+			'display'		=>	array('post' => 'display', 'val' => '', 'db'=>true),
413
+			'rule'			=>	array('post' => 'rule', 'val' => '', 'db'=>true),			
414
+			'action_match'	=>	array('post' => 'ruleMatch', 'val' => -1, 'db'=>true),
415
+			'action_nomatch'=>	array('post' => 'ruleNoMatch', 'val' => -1, 'db'=>true),					
416
+			'ip4'			=>	array('post' => null, 'val' => null, 'db'=>true),
417
+			'ip6'			=>	array('post' => null, 'val' => null, 'db'=>true),
418
+			'action_form'	=>	array('post' => 'action_form', 'db'=>false)
419 419
 		);
420 420
 		
421 421
 		if (isset($postData[$params['action_form']['post']]) 
422
-			&& $postData[$params['action_form']['post']] == 'delete' )
422
+			&& $postData[$params['action_form']['post']] == 'delete')
423 423
 		{
424 424
 			try
425 425
 			{
@@ -439,16 +439,16 @@  discard block
 block discarded – undo
439 439
 		}		
440 440
 		foreach (array_keys($params) as $key)
441 441
 		{
442
-			if ($params[$key]['post']==null) continue; // data not sent in post vars
443
-			if (! isset($postData[$params[$key]['post']]))
442
+			if ($params[$key]['post'] == null) continue; // data not sent in post vars
443
+			if (!isset($postData[$params[$key]['post']]))
444 444
 			{
445 445
 				// should not happen as the js checks data
446
-				$this->_helper->json(array('status'=>'No ' . $key));
446
+				$this->_helper->json(array('status'=>'No '.$key));
447 447
 			}
448 448
 			else
449 449
 			{
450 450
 				$data=$postData[$params[$key]['post']];
451
-				if ($data!=null && $data !="")
451
+				if ($data != null && $data != "")
452 452
 				{
453 453
 					$params[$key]['val']=$postData[$params[$key]['post']];
454 454
 				}
@@ -457,8 +457,8 @@  discard block
 block discarded – undo
457 457
 
458 458
 		try 
459 459
 		{
460
-			$isHostGroup=($params['hostgroup']['val'] == 1)?true:false;
461
-			if (! $isHostGroup ) 
460
+			$isHostGroup=($params['hostgroup']['val'] == 1) ?true:false;
461
+			if (!$isHostGroup) 
462 462
 			{  // checks if selection by host 
463 463
 				$hostAddr=$this->getHostInfoByID($params['hostid']['val']);
464 464
 				$params['ip4']['val']=$hostAddr->ip4;
@@ -485,25 +485,25 @@  discard block
 block discarded – undo
485 485
 					return;					
486 486
 				}
487 487
 				// Put param in correct column (group_name)
488
-				$params['host_group_name']['val'] = $params['host_name']['val'];
488
+				$params['host_group_name']['val']=$params['host_name']['val'];
489 489
 				$params['host_name']['val']=null;
490 490
 			}
491 491
 			$dbparams=array();
492 492
 			foreach ($params as $key=>$val)
493 493
 			{
494
-				if ($val['db']==true )
494
+				if ($val['db'] == true)
495 495
 				{
496
-					$dbparams[$key] = $val['val'];
496
+					$dbparams[$key]=$val['val'];
497 497
 				}
498 498
 			}
499 499
 			// echo '<br>';	print_r($dbparams);echo '<br>';
500
-			if ($params['db_rule']['val'] == -1 ) 
500
+			if ($params['db_rule']['val'] == -1) 
501 501
 			{
502 502
 				$ruleID=$this->addHandlerRule($dbparams);
503 503
 			}
504 504
 			else
505 505
 			{
506
-				$this->updateHandlerRule($dbparams,$params['db_rule']['val']);
506
+				$this->updateHandlerRule($dbparams, $params['db_rule']['val']);
507 507
 				$ruleID=$params['db_rule']['val'];
508 508
 			}
509 509
 		}
@@ -522,10 +522,10 @@  discard block
 block discarded – undo
522 522
 	*/
523 523
 	protected function getTrapDetail($trapid) 
524 524
 	{
525
-		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
525
+		if (!preg_match('/^[0-9]+$/', $trapid)) { throw new Exception('Invalid id'); }
526 526
 		$queryArray=$this->getModuleConfig()->trapDetailQuery();
527 527
 		
528
-		$db = $this->getDb()->getConnection();
528
+		$db=$this->getDb()->getConnection();
529 529
 		// ***************  Get main data
530 530
 		// extract columns and titles;
531 531
 		$elmts=NULL;
@@ -534,15 +534,15 @@  discard block
 block discarded – undo
534 534
 		}
535 535
 		try
536 536
 		{		
537
-			$query = $db->select()
538
-				->from($this->getModuleConfig()->getTrapTableName(),$elmts)
539
-				->where('id=?',$trapid);
537
+			$query=$db->select()
538
+				->from($this->getModuleConfig()->getTrapTableName(), $elmts)
539
+				->where('id=?', $trapid);
540 540
 			$trapDetail=$db->fetchRow($query);
541
-			if ( $trapDetail == null ) throw new Exception('No traps was found with id = '.$trapid);
541
+			if ($trapDetail == null) throw new Exception('No traps was found with id = '.$trapid);
542 542
 		}
543 543
 		catch (Exception $e)
544 544
 		{
545
-			$this->displayExitError('Add handler : get trap detail returning : '.print_r($trapDetail,true),$e->getMessage());
545
+			$this->displayExitError('Add handler : get trap detail returning : '.print_r($trapDetail, true), $e->getMessage());
546 546
 			return;
547 547
 		}
548 548
 
@@ -556,10 +556,10 @@  discard block
 block discarded – undo
556 556
 	*/
557 557
 	protected function getTrapobjects($trapid)
558 558
 	{	
559
-		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
559
+		if (!preg_match('/^[0-9]+$/', $trapid)) { throw new Exception('Invalid id'); }
560 560
 		$queryArrayData=$this->getModuleConfig()->trapDataDetailQuery();
561 561
 		
562
-		$db = $this->getDb()->getConnection();
562
+		$db=$this->getDb()->getConnection();
563 563
 		// ***************  Get object data
564 564
 		// extract columns and titles;
565 565
 		$data_elmts=NULL;
@@ -568,15 +568,15 @@  discard block
 block discarded – undo
568 568
 		}
569 569
 		try
570 570
 		{		
571
-			$query = $db->select()
572
-				->from($this->moduleConfig->getTrapDataTableName(),$data_elmts)
573
-				->where('trap_id=?',$trapid);
571
+			$query=$db->select()
572
+				->from($this->moduleConfig->getTrapDataTableName(), $data_elmts)
573
+				->where('trap_id=?', $trapid);
574 574
 			$trapDetail=$db->fetchAll($query);
575 575
 			// if ( $trapDetail == null ) throw new Exception('No traps was found with id = '.$trapid);
576 576
 		}
577 577
 		catch (Exception $e)
578 578
 		{
579
-			$this->displayExitError('Add handler : get trap data detail : ',$e->getMessage());
579
+			$this->displayExitError('Add handler : get trap data detail : ', $e->getMessage());
580 580
 			return array();
581 581
 		}
582 582
 
@@ -589,22 +589,22 @@  discard block
 block discarded – undo
589 589
 	*/
590 590
 	protected function getRuleDetail($ruleid) 
591 591
 	{
592
-		if (!preg_match('/^[0-9]+$/',$ruleid)) { throw new Exception('Invalid id');  }
592
+		if (!preg_match('/^[0-9]+$/', $ruleid)) { throw new Exception('Invalid id'); }
593 593
 		$queryArray=$this->getModuleConfig()->ruleDetailQuery();
594 594
 		
595
-		$db = $this->getDb()->getConnection();
595
+		$db=$this->getDb()->getConnection();
596 596
 		// ***************  Get main data
597 597
 		try
598 598
 		{		
599
-			$query = $db->select()
600
-				->from($this->getModuleConfig()->getTrapRuleName(),$queryArray)
601
-				->where('id=?',$ruleid);
599
+			$query=$db->select()
600
+				->from($this->getModuleConfig()->getTrapRuleName(), $queryArray)
601
+				->where('id=?', $ruleid);
602 602
 			$ruleDetail=$db->fetchRow($query);
603
-			if ( $ruleDetail == null ) throw new Exception('No rule was found with id = '.$ruleid);
603
+			if ($ruleDetail == null) throw new Exception('No rule was found with id = '.$ruleid);
604 604
 		}
605 605
 		catch (Exception $e)
606 606
 		{
607
-			$this->displayExitError('Update handler : get rule detail',$e->getMessage());
607
+			$this->displayExitError('Update handler : get rule detail', $e->getMessage());
608 608
 			return array();
609 609
 		}
610 610
 
@@ -618,7 +618,7 @@  discard block
 block discarded – undo
618 618
 	{
619 619
 		return $this->getTabs()->add('status', array(
620 620
 			'label' => $this->translate('Traps'),
621
-			'url'   => $this->getModuleConfig()->urlPath() . '/handler')
621
+			'url'   => $this->getModuleConfig()->urlPath().'/handler')
622 622
 		);
623 623
 	} 
624 624
 	
Please login to merge, or discard this patch.
Braces   +35 added lines, -39 removed lines patch added patch discarded remove patch
@@ -51,8 +51,7 @@  discard block
 block discarded – undo
51 51
 	    if ($this->params->get('rule') !== null) 
52 52
 	    {
53 53
 	        $this->view->rule= $this->params->get('rule');
54
-	    }
55
-	    else
54
+	    } else
56 55
 	    {
57 56
 	        $this->view->rule='';
58 57
 	    }
@@ -106,8 +105,7 @@  discard block
 block discarded – undo
106 105
 	    try
107 106
 	    {
108 107
 	        $hosts=$this->getHostByIP($hostfilter);
109
-	    }
110
-	    catch (Exception $e)
108
+	    } catch (Exception $e)
111 109
 	    {
112 110
 	        $this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
113 111
 	    }
@@ -120,8 +118,7 @@  discard block
 block discarded – undo
120 118
 	        // Tell JS to get services when page is loaded
121 119
 	        $this->view->serviceGet=true;
122 120
 	        
123
-	    }
124
-	    else
121
+	    } else
125 122
 	    {
126 123
 	        foreach($hosts as $key=>$val)
127 124
 	        {
@@ -171,11 +168,14 @@  discard block
 block discarded – undo
171 168
 	            $allObjects[$val->oid]=null;
172 169
 	        }
173 170
 	    }
174
-	    if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
171
+	    if ($allObjects!=null) {
172
+	    	// in case trap doesn't have objects or is not resolved
175 173
 	    {
176 174
 	        foreach ($allObjects as $key => $val)
177 175
 	        {
178
-	            if ($val==null) { continue; }
176
+	            if ($val==null) { continue;
177
+	    }
178
+	    }
179 179
 	            array_push($this->view->objectList, array(
180 180
 	                $oid_index,
181 181
 	                $key,
@@ -207,8 +207,7 @@  discard block
 block discarded – undo
207 207
 	    {
208 208
 	        $this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
209 209
 	        $this->view->serviceGet=false;
210
-	    }
211
-	    else
210
+	    } else
212 211
 	    {
213 212
 	        // Tell JS to get services when page is loaded
214 213
 	        $this->view->serviceGet=true;
@@ -217,8 +216,7 @@  discard block
 block discarded – undo
217 216
 	        if (count($serviceID) ==0)
218 217
 	        {
219 218
 	            $this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
220
-	        }
221
-	        else
219
+	        } else
222 220
 	        {
223 221
 	            $this->view->serviceSet=$serviceID[0]->id;
224 222
 	        }
@@ -237,8 +235,7 @@  discard block
 block discarded – undo
237 235
 	    {
238 236
 	        $this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
239 237
 	        $this->view->serviceGroupGet=false;
240
-	    }
241
-	    else
238
+	    } else
242 239
 	    {
243 240
 	        $grpServices=$this->getServicesByHostGroupid($group_get[0]->id);
244 241
 	        $foundGrpService=0;
@@ -288,8 +285,7 @@  discard block
 block discarded – undo
288 285
 	                $object['type'],
289 286
 	                $object['type_enum']
290 287
 	            ));
291
-	        }
292
-	        else
288
+	        } else
293 289
 	        {
294 290
 	            array_push($curObjectList, array(
295 291
 	                $index,
@@ -358,8 +354,7 @@  discard block
 block discarded – undo
358 354
 			    $this->view->selectGroup=false;
359 355
 			    // Check if hostname still exists
360 356
 			    $this->add_check_host_exists($ruleDetail);
361
-			}
362
-			else
357
+			} else
363 358
 			{
364 359
 			    $this->view->selectGroup=true;
365 360
 			    $this->add_check_hostgroup_exists($ruleDetail); //  Check if groupe exists				
@@ -367,9 +362,11 @@  discard block
 block discarded – undo
367 362
 			
368 363
 			$this->view->mainoid=$ruleDetail->trap_oid;
369 364
 			$oidName=$this->getMIB()->translateOID($ruleDetail->trap_oid);
370
-			if ($oidName != null)  // oid is found in mibs
365
+			if ($oidName != null) {
366
+				// oid is found in mibs
371 367
 			{
372
-				$this->view->mib=$oidName['mib']; 
368
+				$this->view->mib=$oidName['mib'];
369
+			}
373 370
 				$this->view->name=$oidName['name'];
374 371
 				$this->view->trapListForMIB=$this->getMIB()
375 372
 					->getTrapList($oidName['mib']);				
@@ -424,8 +421,7 @@  discard block
 block discarded – undo
424 421
 			try
425 422
 			{
426 423
 				$this->deleteRule($postData[$params['db_rule']['post']]);
427
-			}
428
-			catch (Exception $e)
424
+			} catch (Exception $e)
429 425
 			{
430 426
 				$this->_helper->json(array('status'=>$e->getMessage()));
431 427
 				return;
@@ -439,13 +435,15 @@  discard block
 block discarded – undo
439 435
 		}		
440 436
 		foreach (array_keys($params) as $key)
441 437
 		{
442
-			if ($params[$key]['post']==null) continue; // data not sent in post vars
438
+			if ($params[$key]['post']==null) {
439
+				continue;
440
+			}
441
+			// data not sent in post vars
443 442
 			if (! isset($postData[$params[$key]['post']]))
444 443
 			{
445 444
 				// should not happen as the js checks data
446 445
 				$this->_helper->json(array('status'=>'No ' . $key));
447
-			}
448
-			else
446
+			} else
449 447
 			{
450 448
 				$data=$postData[$params[$key]['post']];
451 449
 				if ($data!=null && $data !="")
@@ -475,8 +473,7 @@  discard block
 block discarded – undo
475 473
 					$this->_helper->json(array('status'=>"Invalid service id : Please re enter service"));
476 474
 					return;
477 475
 				}
478
-			}
479
-			else
476
+			} else
480 477
 			{
481 478
 				$object=$this->getObjectNameByid($params['hostid']['val']);
482 479
 				if ($params['host_name']['val'] != $object->name1)
@@ -500,14 +497,12 @@  discard block
 block discarded – undo
500 497
 			if ($params['db_rule']['val'] == -1 ) 
501 498
 			{
502 499
 				$ruleID=$this->addHandlerRule($dbparams);
503
-			}
504
-			else
500
+			} else
505 501
 			{
506 502
 				$this->updateHandlerRule($dbparams,$params['db_rule']['val']);
507 503
 				$ruleID=$params['db_rule']['val'];
508 504
 			}
509
-		}
510
-		catch (Exception $e)
505
+		} catch (Exception $e)
511 506
 		{
512 507
 			$this->_helper->json(array('status'=>$e->getMessage()));
513 508
 			return;
@@ -538,9 +533,10 @@  discard block
 block discarded – undo
538 533
 				->from($this->getModuleConfig()->getTrapTableName(),$elmts)
539 534
 				->where('id=?',$trapid);
540 535
 			$trapDetail=$db->fetchRow($query);
541
-			if ( $trapDetail == null ) throw new Exception('No traps was found with id = '.$trapid);
542
-		}
543
-		catch (Exception $e)
536
+			if ( $trapDetail == null ) {
537
+				throw new Exception('No traps was found with id = '.$trapid);
538
+			}
539
+		} catch (Exception $e)
544 540
 		{
545 541
 			$this->displayExitError('Add handler : get trap detail returning : '.print_r($trapDetail,true),$e->getMessage());
546 542
 			return;
@@ -573,8 +569,7 @@  discard block
 block discarded – undo
573 569
 				->where('trap_id=?',$trapid);
574 570
 			$trapDetail=$db->fetchAll($query);
575 571
 			// if ( $trapDetail == null ) throw new Exception('No traps was found with id = '.$trapid);
576
-		}
577
-		catch (Exception $e)
572
+		} catch (Exception $e)
578 573
 		{
579 574
 			$this->displayExitError('Add handler : get trap data detail : ',$e->getMessage());
580 575
 			return array();
@@ -600,9 +595,10 @@  discard block
 block discarded – undo
600 595
 				->from($this->getModuleConfig()->getTrapRuleName(),$queryArray)
601 596
 				->where('id=?',$ruleid);
602 597
 			$ruleDetail=$db->fetchRow($query);
603
-			if ( $ruleDetail == null ) throw new Exception('No rule was found with id = '.$ruleid);
604
-		}
605
-		catch (Exception $e)
598
+			if ( $ruleDetail == null ) {
599
+				throw new Exception('No rule was found with id = '.$ruleid);
600
+			}
601
+		} catch (Exception $e)
606 602
 		{
607 603
 			$this->displayExitError('Update handler : get rule detail',$e->getMessage());
608 604
 			return array();
Please login to merge, or discard this patch.
application/controllers/StatusController.php 3 patches
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -65,10 +65,10 @@  discard block
 block discarded – undo
65 65
 	} 
66 66
   
67 67
 	/** Mib management
68
-	*	Post param : action=update_mib_db : update mib database
69
-	*	Post param : ation=check_update : check if mib update is finished
70
-	*	File post : mibfile -> save mib file
71
-	*/
68
+	 *	Post param : action=update_mib_db : update mib database
69
+	 *	Post param : ation=check_update : check if mib update is finished
70
+	 *	File post : mibfile -> save mib file
71
+	 */
72 72
 	public function mibAction()
73 73
 	{
74 74
 		$this->prepareTabs()->activate('mib');
@@ -87,22 +87,22 @@  discard block
 block discarded – undo
87 87
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
88 88
 					if (preg_match('/OK/',$return))
89 89
 					{
90
-					    $this->_helper->json(array('status'=>'OK'));
90
+						$this->_helper->json(array('status'=>'OK'));
91 91
 					}
92 92
 					// Error
93 93
 					$this->_helper->json(array('status'=>$return));
94 94
 				}
95 95
 				if ($action == 'check_update')
96 96
 				{
97
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
98
-				    if ($file == false)
99
-				    {   // process is dead
100
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
101
-				        return;
102
-				    }
103
-				    $pid=fgets($file);
104
-				    $output=array();
105
-				    $retVal=0;
97
+					$file=@fopen('/tmp/trapdirector_update.pid','r');
98
+					if ($file == false)
99
+					{   // process is dead
100
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
101
+						return;
102
+					}
103
+					$pid=fgets($file);
104
+					$output=array();
105
+					$retVal=0;
106 106
 					exec('ps '.$pid,$output,$retVal);
107 107
 					if ($retVal == 0)
108 108
 					{ // process is alive
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 					}
111 111
 					else
112 112
 					{ // process is dead
113
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
113
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
114 114
 					}
115 115
 				}
116 116
 				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
@@ -123,26 +123,26 @@  discard block
 block discarded – undo
123 123
 				$destDir=array_shift($DirConf);
124 124
 				if (!is_dir($destDir))
125 125
 				{
126
-				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
126
+					$this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
127 127
 				}
128 128
 				else
129 129
 				{
130
-				    if (!is_writable($destDir))
131
-				    {
132
-				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
133
-				    }
134
-				    else
135
-				    {
136
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
137
-    				    if (move_uploaded_file($_FILES['mibfile']['tmp_name'],$destination)===false)
138
-    				    {
139
-    				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
140
-    				    }
141
-    				    else
142
-    				    {
143
-    				        $this->view->uploadStatus="File $name uploaded in $destDir";
144
-    				    }
145
-				    }
130
+					if (!is_writable($destDir))
131
+					{
132
+						$this->view->uploadStatus="ERROR : $destDir directory is not writable";
133
+					}
134
+					else
135
+					{
136
+						$destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
137
+						if (move_uploaded_file($_FILES['mibfile']['tmp_name'],$destination)===false)
138
+						{
139
+							$this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
140
+						}
141
+						else
142
+						{
143
+							$this->view->uploadStatus="File $name uploaded in $destDir";
144
+						}
145
+					}
146 146
 				}
147 147
 
148 148
 			}
@@ -275,20 +275,20 @@  discard block
 block discarded – undo
275 275
 // TODO : see if useless 
276 276
 class UploadForm extends Form
277 277
 { 
278
-    public function __construct($options = null) 
279
-    {
280
-        parent::__construct($options);
281
-        $this->addElements2();
282
-    }
278
+	public function __construct($options = null) 
279
+	{
280
+		parent::__construct($options);
281
+		$this->addElements2();
282
+	}
283 283
 
284
-    public function addElements2()
285
-    {
286
-        // File Input
287
-        $file = new File('mib-file');
288
-        $file->setLabel('Mib upload');
289
-             //->setAttrib('multiple', null);
290
-        $this->addElement($file);
284
+	public function addElements2()
285
+	{
286
+		// File Input
287
+		$file = new File('mib-file');
288
+		$file->setLabel('Mib upload');
289
+			 //->setAttrib('multiple', null);
290
+		$this->addElement($file);
291 291
 		$button = new Submit("upload",array('ignore'=>false));
292 292
 		$this->addElement($button);//->setIgnore(false);
293
-    }
293
+	}
294 294
 }
Please login to merge, or discard this patch.
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -22,18 +22,18 @@  discard block
 block discarded – undo
22 22
 		/************  Trapdb ***********/
23 23
 		try
24 24
 		{
25
-			$db = $this->getDb()->getConnection();
26
-			$query = $db->select()->from(
25
+			$db=$this->getDb()->getConnection();
26
+			$query=$db->select()->from(
27 27
 				$this->getModuleConfig()->getTrapTableName(),
28 28
 				array('COUNT(*)')
29 29
 			);			
30 30
 			$this->view->trap_count=$db->fetchOne($query);
31
-			$query = $db->select()->from(
31
+			$query=$db->select()->from(
32 32
 				$this->getModuleConfig()->getTrapDataTableName(),
33 33
 				array('COUNT(*)')
34 34
 			);			
35 35
 			$this->view->trap_object_count=$db->fetchOne($query);
36
-			$query = $db->select()->from(
36
+			$query=$db->select()->from(
37 37
 				$this->getModuleConfig()->getTrapRuleName(),
38 38
 				array('COUNT(*)')
39 39
 			);			
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 		}
45 45
 		catch (Exception $e)
46 46
 		{
47
-			$this->displayExitError('status',$e->getMessage());
47
+			$this->displayExitError('status', $e->getMessage());
48 48
 		}
49 49
 		
50 50
 		/*************** Log destination *******************/
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
 		}
60 60
 		catch (Exception $e)
61 61
 		{
62
-			$this->displayExitError('status',$e->getMessage());
62
+			$this->displayExitError('status', $e->getMessage());
63 63
 		}		
64 64
 		
65 65
 	} 
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 				if ($action == 'update_mib_db')
86 86
 				{ // Do the update in background
87 87
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
88
-					if (preg_match('/OK/',$return))
88
+					if (preg_match('/OK/', $return))
89 89
 					{
90 90
 					    $this->_helper->json(array('status'=>'OK'));
91 91
 					}
@@ -94,32 +94,32 @@  discard block
 block discarded – undo
94 94
 				}
95 95
 				if ($action == 'check_update')
96 96
 				{
97
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
97
+				    $file=@fopen('/tmp/trapdirector_update.pid', 'r');
98 98
 				    if ($file == false)
99 99
 				    {   // process is dead
100
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
100
+				        $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'Cannot open file'));
101 101
 				        return;
102 102
 				    }
103 103
 				    $pid=fgets($file);
104 104
 				    $output=array();
105 105
 				    $retVal=0;
106
-					exec('ps '.$pid,$output,$retVal);
106
+					exec('ps '.$pid, $output, $retVal);
107 107
 					if ($retVal == 0)
108 108
 					{ // process is alive
109 109
 						$this->_helper->json(array('status'=>'Alive and kicking'));
110 110
 					}
111 111
 					else
112 112
 					{ // process is dead
113
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
113
+					    $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'no proc'.$pid));
114 114
 					}
115 115
 				}
116
-				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
116
+				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible'));
117 117
 			}
118 118
 			/** Check for mib file UPLOAD */
119 119
 			if (isset($_FILES['mibfile']))
120 120
 			{
121 121
 				$name=$_FILES['mibfile']['name'];
122
-				$DirConf=explode(':',$this->Config()->get('config', 'snmptranslate_dirs'));
122
+				$DirConf=explode(':', $this->Config()->get('config', 'snmptranslate_dirs'));
123 123
 				$destDir=array_shift($DirConf);
124 124
 				if (!is_dir($destDir))
125 125
 				{
@@ -133,8 +133,8 @@  discard block
 block discarded – undo
133 133
 				    }
134 134
 				    else
135 135
 				    {
136
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
137
-    				    if (move_uploaded_file($_FILES['mibfile']['tmp_name'],$destination)===false)
136
+				        $destination=$destDir.'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
137
+    				    if (move_uploaded_file($_FILES['mibfile']['tmp_name'], $destination) === false)
138 138
     				    {
139 139
     				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
140 140
     				    }
@@ -150,13 +150,13 @@  discard block
 block discarded – undo
150 150
 		}
151 151
 		
152 152
 		// snmptranslate tests
153
-		$snmptranslate = $this->Config()->get('config', 'snmptranslate');
153
+		$snmptranslate=$this->Config()->get('config', 'snmptranslate');
154 154
 		$this->view->snmptranslate_bin=$snmptranslate;
155 155
 		$this->view->snmptranslate_state='warn';
156
-		if (is_executable ( $snmptranslate ))
156
+		if (is_executable($snmptranslate))
157 157
 		{
158
-			$translate=exec($snmptranslate . ' 1');
159
-			if (preg_match('/iso/',$translate))
158
+			$translate=exec($snmptranslate.' 1');
159
+			if (preg_match('/iso/', $translate))
160 160
 			{
161 161
 				$this->view->snmptranslate='works fine';
162 162
 				$this->view->snmptranslate_state='ok';
@@ -174,46 +174,46 @@  discard block
 block discarded – undo
174 174
 		// mib database
175 175
 		
176 176
 		$this->view->mibDbCount=$this->getMIB()->countObjects();
177
-		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null,21);
177
+		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null, 21);
178 178
 		
179 179
 		// mib dirs
180 180
 		$DirConf=$this->Config()->get('config', 'snmptranslate_dirs');
181
-		$dirArray=explode(':',$DirConf);
181
+		$dirArray=explode(':', $DirConf);
182 182
 
183 183
 		// Get base directories from net-snmp-config
184 184
 		$output=$matches=array();
185 185
 		$retVal=0;
186
-		$sysDirs=exec('net-snmp-config --default-mibdirs',$output,$retVal);
187
-		if ($retVal==0)
186
+		$sysDirs=exec('net-snmp-config --default-mibdirs', $output, $retVal);
187
+		if ($retVal == 0)
188 188
 		{
189
-			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
189
+			$dirArray=array_merge($dirArray, explode(':', $sysDirs));
190 190
 		}
191 191
 		else
192 192
 		{
193
-			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
194
-			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
193
+			$translateOut=exec($this->Config()->get('config', 'snmptranslate').' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
194
+			if (preg_match('/MIBDIRS.*\'([^\']+)\'/', $translateOut, $matches))
195 195
 			{
196
-				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
196
+				$dirArray=array_merge($dirArray, explode(':', $matches[1]));
197 197
 			}
198 198
 			else
199 199
 			{
200
-				array_push($dirArray,'Install net-snmp-config to see system directories');
200
+				array_push($dirArray, 'Install net-snmp-config to see system directories');
201 201
 			}
202 202
 		}
203 203
 		
204 204
 		$this->view->dirArray=$dirArray;
205 205
 		
206 206
 		$output=null;
207
-		foreach (explode(':',$DirConf) as $mibdir)
207
+		foreach (explode(':', $DirConf) as $mibdir)
208 208
 		{
209
-			exec('ls '.$mibdir.' | grep -v traplist.txt',$output);
209
+			exec('ls '.$mibdir.' | grep -v traplist.txt', $output);
210 210
 		}
211 211
 		//$i=0;$listFiles='';while (isset($output[$i])) $listFiles.=$output[$i++];
212 212
 		//$this->view->fileList=explode(' ',$listFiles);
213 213
 		$this->view->fileList=$output;
214 214
 		
215 215
 		// Zend form 
216
-		$this->view->form= new UploadForm();
216
+		$this->view->form=new UploadForm();
217 217
 		//$this->view->form= new Form('upload-form');
218 218
 		
219 219
 		
@@ -237,18 +237,18 @@  discard block
 block discarded – undo
237 237
 		$this->view->templateForm_output='';
238 238
 		if (isset($postData['template_name']) && isset($postData['template_revert_time']))
239 239
 		{
240
-			$template_create = 'icingacli director service create --json \'{ "check_command": "dummy", ';
241
-			$template_create .= '"check_interval": "' .$postData['template_revert_time']. '", "check_timeout": "20", "disabled": false, "enable_active_checks": true, "enable_event_handler": true, "enable_notifications": true, "enable_passive_checks": true, "enable_perfdata": true, "max_check_attempts": "1", ';
242
-			$template_create .= '"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
240
+			$template_create='icingacli director service create --json \'{ "check_command": "dummy", ';
241
+			$template_create.='"check_interval": "'.$postData['template_revert_time'].'", "check_timeout": "20", "disabled": false, "enable_active_checks": true, "enable_event_handler": true, "enable_notifications": true, "enable_passive_checks": true, "enable_perfdata": true, "max_check_attempts": "1", ';
242
+			$template_create.='"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
243 243
 			$output=array();
244 244
 			$ret_code=0;
245
-			exec($template_create,$output,$ret_code);
245
+			exec($template_create, $output, $ret_code);
246 246
 			if ($ret_code != 0)
247 247
 			{
248
-				$this->displayExitError("Status -> Services","Error creating template : ".$output[0].'<br>Command was : '.$template_create);
248
+				$this->displayExitError("Status -> Services", "Error creating template : ".$output[0].'<br>Command was : '.$template_create);
249 249
 			}
250
-			exec('icingacli director config deploy',$output,$ret_code);
251
-			$this->view->templateForm_output='Template '.$postData['template_name']. ' created';
250
+			exec('icingacli director config deploy', $output, $ret_code);
251
+			$this->view->templateForm_output='Template '.$postData['template_name'].' created';
252 252
 		}
253 253
 		
254 254
 		// template creation form
@@ -261,13 +261,13 @@  discard block
 block discarded – undo
261 261
 	{
262 262
 		return $this->getTabs()->add('status', array(
263 263
 			'label' => $this->translate('Status'),
264
-			'url'   => $this->getModuleConfig()->urlPath() . '/status')
264
+			'url'   => $this->getModuleConfig()->urlPath().'/status')
265 265
 		)->add('mib', array(
266 266
 			'label' => $this->translate('MIB Management'),
267
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
267
+			'url'   => $this->getModuleConfig()->urlPath().'/status/mib')
268 268
 		)->add('services', array(
269 269
 			'label' => $this->translate('Services management'),
270
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
270
+			'url'   => $this->getModuleConfig()->urlPath().'/status/services')
271 271
 		);
272 272
 	} 
273 273
 }
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 // TODO : see if useless 
276 276
 class UploadForm extends Form
277 277
 { 
278
-    public function __construct($options = null) 
278
+    public function __construct($options=null) 
279 279
     {
280 280
         parent::__construct($options);
281 281
         $this->addElements2();
@@ -284,11 +284,11 @@  discard block
 block discarded – undo
284 284
     public function addElements2()
285 285
     {
286 286
         // File Input
287
-        $file = new File('mib-file');
287
+        $file=new File('mib-file');
288 288
         $file->setLabel('Mib upload');
289 289
              //->setAttrib('multiple', null);
290 290
         $this->addElement($file);
291
-		$button = new Submit("upload",array('ignore'=>false));
292
-		$this->addElement($button);//->setIgnore(false);
291
+		$button=new Submit("upload", array('ignore'=>false));
292
+		$this->addElement($button); //->setIgnore(false);
293 293
     }
294 294
 }
Please login to merge, or discard this patch.
Braces   +10 added lines, -20 removed lines patch added patch discarded remove patch
@@ -41,8 +41,7 @@  discard block
 block discarded – undo
41 41
  			
42 42
 			$this->view->trap_days_delete=$this->getDBConfigValue('db_remove_days');
43 43
 			
44
-		}
45
-		catch (Exception $e)
44
+		} catch (Exception $e)
46 45
 		{
47 46
 			$this->displayExitError('status',$e->getMessage());
48 47
 		}
@@ -56,8 +55,7 @@  discard block
 block discarded – undo
56 55
 			$this->view->currentLogFile=$this->getDBConfigValue('log_file');
57 56
 			$this->view->logLevels=$this->getModuleConfig()->getlogLevels();
58 57
 			$this->view->currentLogLevel=$this->getDBConfigValue('log_level');
59
-		}
60
-		catch (Exception $e)
58
+		} catch (Exception $e)
61 59
 		{
62 60
 			$this->displayExitError('status',$e->getMessage());
63 61
 		}		
@@ -107,8 +105,7 @@  discard block
 block discarded – undo
107 105
 					if ($retVal == 0)
108 106
 					{ // process is alive
109 107
 						$this->_helper->json(array('status'=>'Alive and kicking'));
110
-					}
111
-					else
108
+					} else
112 109
 					{ // process is dead
113 110
 					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
114 111
 					}
@@ -124,21 +121,18 @@  discard block
 block discarded – undo
124 121
 				if (!is_dir($destDir))
125 122
 				{
126 123
 				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
127
-				}
128
-				else
124
+				} else
129 125
 				{
130 126
 				    if (!is_writable($destDir))
131 127
 				    {
132 128
 				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
133
-				    }
134
-				    else
129
+				    } else
135 130
 				    {
136 131
 				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
137 132
     				    if (move_uploaded_file($_FILES['mibfile']['tmp_name'],$destination)===false)
138 133
     				    {
139 134
     				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
140
-    				    }
141
-    				    else
135
+    				    } else
142 136
     				    {
143 137
     				        $this->view->uploadStatus="File $name uploaded in $destDir";
144 138
     				    }
@@ -160,13 +154,11 @@  discard block
 block discarded – undo
160 154
 			{
161 155
 				$this->view->snmptranslate='works fine';
162 156
 				$this->view->snmptranslate_state='ok';
163
-			}
164
-			else
157
+			} else
165 158
 			{
166 159
 				$this->view->snmptranslate='can execute but no resolution';
167 160
 			}
168
-		}
169
-		else
161
+		} else
170 162
 		{
171 163
 			$this->view->snmptranslate='cannot execute';
172 164
 		}
@@ -187,15 +179,13 @@  discard block
 block discarded – undo
187 179
 		if ($retVal==0)
188 180
 		{
189 181
 			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
190
-		}
191
-		else
182
+		} else
192 183
 		{
193 184
 			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
194 185
 			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
195 186
 			{
196 187
 				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
197
-			}
198
-			else
188
+			} else
199 189
 			{
200 190
 				array_push($dirArray,'Install net-snmp-config to see system directories');
201 191
 			}
Please login to merge, or discard this patch.
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
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.
Indentation   +223 added lines, -223 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'];
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 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
-	    }
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.