Passed
Pull Request — master (#78)
by
unknown
03:51
created
application/controllers/HelperController.php 3 patches
Indentation   +151 added lines, -151 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();
@@ -22,15 +22,15 @@  discard block
 block discarded – undo
22 22
 		
23 23
 		$retHosts=array('status'=>'OK','hosts' => array());
24 24
 		$this->getIdoConn(); // set apiMode to correct val
25
-        if ($this->apiMode === TRUE)
26
-        {
27
-          $hosts=$this->getIdoConn()->getHostByNameOrIP($hostFilter);
28
-          $retHosts['test']=count($hosts);
29
-        }
30
-        else 
31
-        {
25
+		if ($this->apiMode === TRUE)
26
+		{
27
+		  $hosts=$this->getIdoConn()->getHostByNameOrIP($hostFilter);
28
+		  $retHosts['test']=count($hosts);
29
+		}
30
+		else 
31
+		{
32 32
 		  $hosts=$this->getIdoConn()->getHostByIP($hostFilter);
33
-        }
33
+		}
34 34
 		foreach ($hosts as $val)
35 35
 		{
36 36
 			array_push($retHosts['hosts'],$val->name);
@@ -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();
@@ -60,11 +60,11 @@  discard block
 block discarded – undo
60 60
 	}
61 61
 	
62 62
 	/** Get service list by host name ( host=<host> )
63
-	*	returns in JSON : 
64
-	*		status=>OK/No services found/More than one host matches
65
-	*		services=>array of services (name)
66
-	*		hostid = host object id or -1 if not found.
67
-	*/
63
+	 *	returns in JSON : 
64
+	 *		status=>OK/No services found/More than one host matches
65
+	 *		services=>array of services (name)
66
+	 *		hostid = host object id or -1 if not found.
67
+	 */
68 68
 	public function getservicesAction()
69 69
 	{
70 70
 		$postData=$this->getRequest()->getPost();
@@ -106,11 +106,11 @@  discard block
 block discarded – undo
106 106
 	}
107 107
 	
108 108
 	/** Get service list by host group ( name=<host> )
109
-	*	returns in JSON : 
110
-	*		status=>OK/No services found/More than one host matches
111
-	*		services=>array of services (name)
112
-	*		groupid = group object id or -1 if not found.
113
-	*/
109
+	 *	returns in JSON : 
110
+	 *		status=>OK/No services found/More than one host matches
111
+	 *		services=>array of services (name)
112
+	 *		groupid = group object id or -1 if not found.
113
+	 */
114 114
 	public function gethostgroupservicesAction()
115 115
 	{
116 116
 		$postData=$this->getRequest()->getPost();
@@ -140,10 +140,10 @@  discard block
 block discarded – undo
140 140
 	}
141 141
 
142 142
 	/** Get traps from mib  : entry : mib=<mib>
143
-	*	returns in JSON : 
144
-	*		status=>OK/No mib/Error getting mibs
145
-	*		traps=>array of array( oid -> name)
146
-	*/
143
+	 *	returns in JSON : 
144
+	 *		status=>OK/No mib/Error getting mibs
145
+	 *		traps=>array of array( oid -> name)
146
+	 */
147 147
 	public function gettrapsAction()
148 148
 	{
149 149
 		$postData=$this->getRequest()->getPost();
@@ -163,10 +163,10 @@  discard block
 block discarded – undo
163 163
 	}	
164 164
 
165 165
 	/** Get trap objects from mib  : entry : trap=<oid>
166
-	*	returns in JSON : 
167
-	*		status=>OK/no trap/not found
168
-	*		objects=>array of array( oid -> name, oid->mib)
169
-	*/
166
+	 *	returns in JSON : 
167
+	 *		status=>OK/no trap/not found
168
+	 *		objects=>array of array( oid -> name, oid->mib)
169
+	 */
170 170
 	public function gettrapobjectsAction()
171 171
 	{
172 172
 		$postData=$this->getRequest()->getPost();
@@ -186,8 +186,8 @@  discard block
 block discarded – undo
186 186
 	}	
187 187
 	
188 188
 	/** Get list of all loaded mibs : entry : none
189
-	*	return : array of strings.
190
-	*/
189
+	 *	return : array of strings.
190
+	 */
191 191
 	public function getmiblistAction()
192 192
 	{
193 193
 		try
@@ -202,10 +202,10 @@  discard block
 block discarded – undo
202 202
 	}
203 203
 	
204 204
 	/** Get MIB::Name from OID : entry : oid
205
-	*		status=>OK/No oid/not found
206
-	*		mib=>string
207
-	*		name=>string
208
-	*/	
205
+	 *		status=>OK/No oid/not found
206
+	 *		mib=>string
207
+	 *		name=>string
208
+	 */	
209 209
 	public function translateoidAction()
210 210
 	{
211 211
 		$postData=$this->getRequest()->getPost();
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 					'name' => $object['name'],
227 227
 					'type' => $object['type'],
228 228
 					'type_enum' => $object['type_enum'],
229
-				    'description' => $object['description']
229
+					'description' => $object['description']
230 230
 				)
231 231
 			);
232 232
 		}
@@ -234,10 +234,10 @@  discard block
 block discarded – undo
234 234
 	}
235 235
 	
236 236
 	/** Save or execute database purge of <n> days
237
-	*	days=>int 
238
-	*	action=>save/execute
239
-	*	return : status=>OK/Message error
240
-	*/
237
+	 *	days=>int 
238
+	 *	action=>save/execute
239
+	 *	return : status=>OK/Message error
240
+	 */
241 241
 	public function dbmaintenanceAction()
242 242
 	{
243 243
 		
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 		{
253 253
 			try
254 254
 			{
255
-			    $this->getUIDatabase()->setDBConfigValue('db_remove_days',$days);
255
+				$this->getUIDatabase()->setDBConfigValue('db_remove_days',$days);
256 256
 			}
257 257
 			catch (Exception $e)
258 258
 			{
@@ -290,33 +290,33 @@  discard block
 block discarded – undo
290 290
 	 */
291 291
 	public function snmpconfigAction()
292 292
 	{
293
-	    $postData=$this->getRequest()->getPost();
293
+		$postData=$this->getRequest()->getPost();
294 294
 	    
295
-	    $snmpUse = $this->checkPostVar($postData, 'useTrapAddr', '0|1');
295
+		$snmpUse = $this->checkPostVar($postData, 'useTrapAddr', '0|1');
296 296
 	    
297
-	    $snmpOID = $this->checkPostVar($postData, 'trapAddrOID', '^[\.0-9]+$');
297
+		$snmpOID = $this->checkPostVar($postData, 'trapAddrOID', '^[\.0-9]+$');
298 298
 	    	    
299
-	    try
300
-	    {
301
-	        $this->getUIDatabase()->setDBConfigValue('use_SnmpTrapAddess',$snmpUse);
302
-	        $this->getUIDatabase()->setDBConfigValue('SnmpTrapAddess_oid',$snmpOID);
303
-	    }
304
-	    catch (Exception $e)
305
-	    {
306
-	        $this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
307
-	        return;
308
-	    }
309
-	    $this->_helper->json(array('status'=>'OK'));
310
-	    return;
299
+		try
300
+		{
301
+			$this->getUIDatabase()->setDBConfigValue('use_SnmpTrapAddess',$snmpUse);
302
+			$this->getUIDatabase()->setDBConfigValue('SnmpTrapAddess_oid',$snmpOID);
303
+		}
304
+		catch (Exception $e)
305
+		{
306
+			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
307
+			return;
308
+		}
309
+		$this->_helper->json(array('status'=>'OK'));
310
+		return;
311 311
 	    
312 312
 	}
313 313
 	
314 314
 	/** Save log output to db
315
-	*	destination=>log destination 
316
-	*	file=>file name
317
-	*	level => int 
318
-	*	return : status=>OK/Message error
319
-	*/
315
+	 *	destination=>log destination 
316
+	 *	file=>file name
317
+	 *	level => int 
318
+	 *	return : status=>OK/Message error
319
+	 */
320 320
 	public function logdestinationAction()
321 321
 	{
322 322
 		$postData=$this->getRequest()->getPost();
@@ -335,8 +335,8 @@  discard block
 block discarded – undo
335 335
 			$fileHandler=@fopen($file,'w');
336 336
 			if ($fileHandler == false)
337 337
 			{   // File os note writabe / cannot create
338
-			    $this->_helper->json(array('status'=>'File not writable :  '.$file));
339
-			    return;
338
+				$this->_helper->json(array('status'=>'File not writable :  '.$file));
339
+				return;
340 340
 			}
341 341
 		}
342 342
 		else
@@ -356,9 +356,9 @@  discard block
 block discarded – undo
356 356
 				
357 357
 		try
358 358
 		{
359
-		    $this->getUIDatabase()->setDBConfigValue('log_destination',$destination);
360
-		    $this->getUIDatabase()->setDBConfigValue('log_file',$file);
361
-		    $this->getUIDatabase()->setDBConfigValue('log_level',$level);
359
+			$this->getUIDatabase()->setDBConfigValue('log_destination',$destination);
360
+			$this->getUIDatabase()->setDBConfigValue('log_file',$file);
361
+			$this->getUIDatabase()->setDBConfigValue('log_level',$level);
362 362
 		}
363 363
 		catch (Exception $e)
364 364
 		{
@@ -378,33 +378,33 @@  discard block
 block discarded – undo
378 378
 	public function testruleAction()
379 379
 	{
380 380
 	    
381
-	    $postData=$this->getRequest()->getPost();
381
+		$postData=$this->getRequest()->getPost();
382 382
 	   
383
-	    $rule = $this->checkPostVar($postData, 'rule', '.*');
383
+		$rule = $this->checkPostVar($postData, 'rule', '.*');
384 384
 
385
-	    $action = $this->checkPostVar($postData, 'action', 'evaluate');
385
+		$action = $this->checkPostVar($postData, 'action', 'evaluate');
386 386
 
387
-	    if ($action == 'evaluate')
388
-	    {
389
-	        try
390
-	        {
391
-	            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
392
-	            $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
393
-	            $trap = new Trap($icingaweb2_etc);
394
-	            // Cleanup spaces before eval
395
-	            $rule=$trap->ruleClass->eval_cleanup($rule);
396
-	            // Eval
397
-	            $item=0;
398
-	            $rule=$trap->ruleClass->evaluation($rule,$item);
399
-	        }
400
-	        catch (Exception $e)
401
-	        {
402
-	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
403
-	            return;
404
-	        }
405
-	        $return=($rule==true)?'true':'false';
406
-	        $this->_helper->json(array('status'=>'OK', 'message' => $return));
407
-	    }
387
+		if ($action == 'evaluate')
388
+		{
389
+			try
390
+			{
391
+				require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
392
+				$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
393
+				$trap = new Trap($icingaweb2_etc);
394
+				// Cleanup spaces before eval
395
+				$rule=$trap->ruleClass->eval_cleanup($rule);
396
+				// Eval
397
+				$item=0;
398
+				$rule=$trap->ruleClass->evaluation($rule,$item);
399
+			}
400
+			catch (Exception $e)
401
+			{
402
+				$this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
403
+				return;
404
+			}
405
+			$return=($rule==true)?'true':'false';
406
+			$this->_helper->json(array('status'=>'OK', 'message' => $return));
407
+		}
408 408
 	    
409 409
 	}	
410 410
 
@@ -415,35 +415,35 @@  discard block
 block discarded – undo
415 415
 	 */
416 416
 	public function pluginAction()
417 417
 	{
418
-	    $postData=$this->getRequest()->getPost();
418
+		$postData=$this->getRequest()->getPost();
419 419
 	    
420
-	    $pluginName = $this->checkPostVar($postData, 'name', '.*');
420
+		$pluginName = $this->checkPostVar($postData, 'name', '.*');
421 421
 	    
422
-	    $action = $this->checkPostVar($postData, 'action', 'enable|disable');
422
+		$action = $this->checkPostVar($postData, 'action', 'enable|disable');
423 423
 	    
424
-        try
425
-        {
426
-            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
427
-            $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
428
-            $trap = new Trap($icingaweb2_etc);
429
-            // Enable plugin.
430
-            $action=($action == 'enable') ? true : false;
431
-            $retVal=$trap->pluginClass->enablePlugin($pluginName, $action);
424
+		try
425
+		{
426
+			require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
427
+			$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
428
+			$trap = new Trap($icingaweb2_etc);
429
+			// Enable plugin.
430
+			$action=($action == 'enable') ? true : false;
431
+			$retVal=$trap->pluginClass->enablePlugin($pluginName, $action);
432 432
             
433
-        }
434
-        catch (Exception $e)
435
-        {
436
-            $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
437
-            return;
438
-        }
439
-        if ($retVal === true)
440
-        {
441
-            $this->_helper->json(array('status'=>'OK'));
442
-        }
443
-        else
444
-        {
445
-            $this->_helper->json(array('status'=>'Error, see logs'));
446
-        }
433
+		}
434
+		catch (Exception $e)
435
+		{
436
+			$this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
437
+			return;
438
+		}
439
+		if ($retVal === true)
440
+		{
441
+			$this->_helper->json(array('status'=>'OK'));
442
+		}
443
+		else
444
+		{
445
+			$this->_helper->json(array('status'=>'Error, see logs'));
446
+		}
447 447
 	}
448 448
 	
449 449
 	/** Function evaluation
@@ -453,49 +453,49 @@  discard block
 block discarded – undo
453 453
 	 */
454 454
 	public function functionAction()
455 455
 	{
456
-	    $postData=$this->getRequest()->getPost();
456
+		$postData=$this->getRequest()->getPost();
457 457
 	    
458
-	    $functionString = $this->checkPostVar($postData, 'function', '.*');
458
+		$functionString = $this->checkPostVar($postData, 'function', '.*');
459 459
 	    
460
-	    $this->checkPostVar($postData, 'action', 'evaluate');
460
+		$this->checkPostVar($postData, 'action', 'evaluate');
461 461
 	    
462
-	    // Only one action possible for now, no tests on action.
463
-	    try
464
-	    {
465
-	        require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
466
-	        $icingaweb2Etc=$this->Config()->get('config', 'icingaweb2_etc');
467
-	        $trap = new Trap($icingaweb2Etc);
468
-	        // load all plugins in case tested function is not enabled.
469
-	        $trap->pluginClass->registerAllPlugins(false);
470
-	        // Clean all spaces
471
-	        $functionString = $trap->ruleClass->eval_cleanup($functionString);
472
-	        // Eval functions
473
-	        $result = $trap->pluginClass->evaluateFunctionString($functionString);	        
474
-	    }
475
-	    catch (Exception $e)
476
-	    {
477
-	        $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
478
-	        return;
479
-	    }
462
+		// Only one action possible for now, no tests on action.
463
+		try
464
+		{
465
+			require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
466
+			$icingaweb2Etc=$this->Config()->get('config', 'icingaweb2_etc');
467
+			$trap = new Trap($icingaweb2Etc);
468
+			// load all plugins in case tested function is not enabled.
469
+			$trap->pluginClass->registerAllPlugins(false);
470
+			// Clean all spaces
471
+			$functionString = $trap->ruleClass->eval_cleanup($functionString);
472
+			// Eval functions
473
+			$result = $trap->pluginClass->evaluateFunctionString($functionString);	        
474
+		}
475
+		catch (Exception $e)
476
+		{
477
+			$this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
478
+			return;
479
+		}
480 480
 	    
481
-        $result = ($result === true)?'True':'False';
482
-        $this->_helper->json(array('status'=>'OK','message' => $result));
481
+		$result = ($result === true)?'True':'False';
482
+		$this->_helper->json(array('status'=>'OK','message' => $result));
483 483
 	}
484 484
 
485
-    /**************   Utilities **********************/
485
+	/**************   Utilities **********************/
486 486
 
487 487
 	private function checkPostVar(array $postData,string $postVar, string $validRegexp) : string
488 488
 	{
489
-	    if (!isset ($postData[$postVar]))
490
-	    {
491
-	        $this->_helper->json(array('status'=>'No ' . $postVar));
492
-	        return '';
493
-	    }
494
-	    if (preg_match('/'.$validRegexp.'/', $postData[$postVar]) != 1)
495
-	    {
496
-	        $this->_helper->json(array('status'=>'Unknown ' . $postVar . ' value '.$postData[$postVar]));
497
-	        return '';
498
-	    }
499
-	    return $postData[$postVar];
489
+		if (!isset ($postData[$postVar]))
490
+		{
491
+			$this->_helper->json(array('status'=>'No ' . $postVar));
492
+			return '';
493
+		}
494
+		if (preg_match('/'.$validRegexp.'/', $postData[$postVar]) != 1)
495
+		{
496
+			$this->_helper->json(array('status'=>'Unknown ' . $postVar . ' value '.$postData[$postVar]));
497
+			return '';
498
+		}
499
+		return $postData[$postVar];
500 500
 	}
501 501
 }
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -18,9 +18,9 @@  discard block
 block discarded – undo
18 18
 	{
19 19
 		$postData=$this->getRequest()->getPost();
20 20
 		
21
-		$hostFilter = $this->checkPostVar($postData, 'hostFilter', '.*');
21
+		$hostFilter=$this->checkPostVar($postData, 'hostFilter', '.*');
22 22
 		
23
-		$retHosts=array('status'=>'OK','hosts' => array());
23
+		$retHosts=array('status'=>'OK', 'hosts' => array());
24 24
 		$this->getIdoConn(); // set apiMode to correct val
25 25
         if ($this->apiMode === TRUE)
26 26
         {
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
         }
34 34
 		foreach ($hosts as $val)
35 35
 		{
36
-			array_push($retHosts['hosts'],$val->name);
36
+			array_push($retHosts['hosts'], $val->name);
37 37
 		}
38 38
 		
39 39
 		$this->_helper->json($retHosts);
@@ -46,14 +46,14 @@  discard block
 block discarded – undo
46 46
 	{
47 47
 		$postData=$this->getRequest()->getPost();
48 48
 		
49
-		$hostFilter = $this->checkPostVar($postData, 'hostFilter', '.*');
49
+		$hostFilter=$this->checkPostVar($postData, 'hostFilter', '.*');
50 50
 		
51
-		$retHosts=array('status'=>'OK','hosts' => array());
51
+		$retHosts=array('status'=>'OK', 'hosts' => array());
52 52
 
53 53
 		$hosts=$this->getIdoConn()->getHostGroupByName($hostFilter);
54 54
 		foreach ($hosts as $val)
55 55
 		{
56
-			array_push($retHosts['hosts'],$val->name);
56
+			array_push($retHosts['hosts'], $val->name);
57 57
 		}
58 58
 		
59 59
 		$this->_helper->json($retHosts);
@@ -76,31 +76,31 @@  discard block
 block discarded – undo
76 76
 		}
77 77
 		else
78 78
 		{
79
-			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
79
+			$this->_helper->json(array('status'=>'No Hosts', 'hostid' => -1));
80 80
 			return;
81 81
 		}
82 82
 		
83 83
 		$hostArray=$this->getIdoConn()->getHostByName($host);
84 84
 		if (count($hostArray) > 1)
85 85
 		{	
86
-			$this->_helper->json(array('status'=>'More than one host matches','hostid' => -1));
86
+			$this->_helper->json(array('status'=>'More than one host matches', 'hostid' => -1));
87 87
 			return;
88 88
 		}
89 89
 		else if (count($hostArray) == 0)
90 90
 		{
91
-			$this->_helper->json(array('status'=>'No host matches','hostid' => -1));
91
+			$this->_helper->json(array('status'=>'No host matches', 'hostid' => -1));
92 92
 			return;
93 93
 		}
94 94
 		$services=$this->getIdoConn()->getServicesByHostid($hostArray[0]->id);
95 95
 		if (count($services) < 1)
96 96
 		{
97
-			$this->_helper->json(array('status'=>'No services found for host','hostid' => $hostArray[0]->id));
97
+			$this->_helper->json(array('status'=>'No services found for host', 'hostid' => $hostArray[0]->id));
98 98
 			return;
99 99
 		}
100
-		$retServices=array('status'=>'OK','services' => array(),'hostid' => $hostArray[0]->id);
100
+		$retServices=array('status'=>'OK', 'services' => array(), 'hostid' => $hostArray[0]->id);
101 101
 		foreach ($services as $val)
102 102
 		{
103
-			array_push($retServices['services'],array($val->id , $val->name));
103
+			array_push($retServices['services'], array($val->id, $val->name));
104 104
 		}
105 105
 		$this->_helper->json($retServices);
106 106
 	}
@@ -115,26 +115,26 @@  discard block
 block discarded – undo
115 115
 	{
116 116
 		$postData=$this->getRequest()->getPost();
117 117
 		
118
-		$host = $this->checkPostVar($postData, 'host', '.+');
118
+		$host=$this->checkPostVar($postData, 'host', '.+');
119 119
 		
120 120
 		$hostArray=$this->getIdoConn()->getHostGroupByName($host);
121 121
 		if (count($hostArray) > 1)
122 122
 		{	
123
-			$this->_helper->json(array('status'=>'More than one hostgroup matches','hostid' => -1));
123
+			$this->_helper->json(array('status'=>'More than one hostgroup matches', 'hostid' => -1));
124 124
 			return;
125 125
 		}
126 126
 		else if (count($hostArray) == 0)
127 127
 		{
128
-			$this->_helper->json(array('status'=>'No hostgroup matches','hostid' => -1));
128
+			$this->_helper->json(array('status'=>'No hostgroup matches', 'hostid' => -1));
129 129
 			return;
130 130
 		}
131 131
 		$services=$this->getIdoConn()->getServicesByHostGroupid($hostArray[0]->id);
132 132
 		if (count($services) < 1)
133 133
 		{
134
-			$this->_helper->json(array('status'=>'No services found for hostgroup','hostid' => $hostArray[0]->id));
134
+			$this->_helper->json(array('status'=>'No services found for hostgroup', 'hostid' => $hostArray[0]->id));
135 135
 			return;
136 136
 		}
137
-		$retServices=array('status'=>'OK','services' => $services,'hostid' => $hostArray[0]->id);
137
+		$retServices=array('status'=>'OK', 'services' => $services, 'hostid' => $hostArray[0]->id);
138 138
 		
139 139
 		$this->_helper->json($retServices);
140 140
 	}
@@ -148,12 +148,12 @@  discard block
 block discarded – undo
148 148
 	{
149 149
 		$postData=$this->getRequest()->getPost();
150 150
 		
151
-		$mib = $this->checkPostVar($postData, 'mib', '.*');
151
+		$mib=$this->checkPostVar($postData, 'mib', '.*');
152 152
 
153 153
 		try
154 154
 		{
155 155
 			$traplist=$this->getMIB()->getTrapList($mib);
156
-			$retTraps=array('status'=>'OK','traps' => $traplist);
156
+			$retTraps=array('status'=>'OK', 'traps' => $traplist);
157 157
 		} 
158 158
 		catch (Exception $e) 
159 159
 		{ 
@@ -171,12 +171,12 @@  discard block
 block discarded – undo
171 171
 	{
172 172
 		$postData=$this->getRequest()->getPost();
173 173
 		
174
-		$trap = $this->checkPostVar($postData, 'trap', '.*');
174
+		$trap=$this->checkPostVar($postData, 'trap', '.*');
175 175
 		
176 176
 		try
177 177
 		{
178 178
 			$objectlist=$this->getMIB()->getObjectList($trap);
179
-			$retObjects=array('status'=>'OK','objects' => $objectlist);
179
+			$retObjects=array('status'=>'OK', 'objects' => $objectlist);
180 180
 		} 
181 181
 		catch (Exception $e) 
182 182
 		{ 
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
 	{
211 211
 		$postData=$this->getRequest()->getPost();
212 212
 		
213
-		$oid = $this->checkPostVar($postData, 'oid', '.*');
213
+		$oid=$this->checkPostVar($postData, 'oid', '.*');
214 214
 		
215 215
 		// Try to get oid name from snmptranslate
216 216
 		if (($object=$this->getMIB()->translateOID($oid)) == null)
@@ -243,20 +243,20 @@  discard block
 block discarded – undo
243 243
 		
244 244
 		$postData=$this->getRequest()->getPost();
245 245
 		
246
-		$days = $this->checkPostVar($postData, 'days', '^[0-9]+$');
246
+		$days=$this->checkPostVar($postData, 'days', '^[0-9]+$');
247 247
 		$days=intval($days);
248 248
 
249
-		$action = $this->checkPostVar($postData, 'action', 'save|execute');
249
+		$action=$this->checkPostVar($postData, 'action', 'save|execute');
250 250
 		
251 251
 		if ($action == 'save')
252 252
 		{
253 253
 			try
254 254
 			{
255
-			    $this->getUIDatabase()->setDBConfigValue('db_remove_days',$days);
255
+			    $this->getUIDatabase()->setDBConfigValue('db_remove_days', $days);
256 256
 			}
257 257
 			catch (Exception $e)
258 258
 			{
259
-				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
259
+				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage()));
260 260
 				return;
261 261
 			}
262 262
 			$this->_helper->json(array('status'=>'OK'));
@@ -266,16 +266,16 @@  discard block
 block discarded – undo
266 266
 		{
267 267
 			try
268 268
 			{
269
-				require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
269
+				require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
270 270
 				$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
271 271
 				$debug_level=4;
272
-				$trap = new Trap($icingaweb2_etc);
273
-				$trap->setLogging($debug_level,'syslog');
272
+				$trap=new Trap($icingaweb2_etc);
273
+				$trap->setLogging($debug_level, 'syslog');
274 274
 				$trap->eraseOldTraps($days);
275 275
 			}
276 276
 			catch (Exception $e)
277 277
 			{
278
-				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage() ));
278
+				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage()));
279 279
 				return;
280 280
 			}			
281 281
 			$this->_helper->json(array('status'=>'OK'));
@@ -292,18 +292,18 @@  discard block
 block discarded – undo
292 292
 	{
293 293
 	    $postData=$this->getRequest()->getPost();
294 294
 	    
295
-	    $snmpUse = $this->checkPostVar($postData, 'useTrapAddr', '0|1');
295
+	    $snmpUse=$this->checkPostVar($postData, 'useTrapAddr', '0|1');
296 296
 	    
297
-	    $snmpOID = $this->checkPostVar($postData, 'trapAddrOID', '^[\.0-9]+$');
297
+	    $snmpOID=$this->checkPostVar($postData, 'trapAddrOID', '^[\.0-9]+$');
298 298
 	    	    
299 299
 	    try
300 300
 	    {
301
-	        $this->getUIDatabase()->setDBConfigValue('use_SnmpTrapAddess',$snmpUse);
302
-	        $this->getUIDatabase()->setDBConfigValue('SnmpTrapAddess_oid',$snmpOID);
301
+	        $this->getUIDatabase()->setDBConfigValue('use_SnmpTrapAddess', $snmpUse);
302
+	        $this->getUIDatabase()->setDBConfigValue('SnmpTrapAddess_oid', $snmpOID);
303 303
 	    }
304 304
 	    catch (Exception $e)
305 305
 	    {
306
-	        $this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
306
+	        $this->_helper->json(array('status'=>'Save error : '.$e->getMessage()));
307 307
 	        return;
308 308
 	    }
309 309
 	    $this->_helper->json(array('status'=>'OK'));
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
 	{
322 322
 		$postData=$this->getRequest()->getPost();
323 323
 		
324
-		$destination = $this->checkPostVar($postData, 'destination', '.*');
324
+		$destination=$this->checkPostVar($postData, 'destination', '.*');
325 325
 		$logDest=$this->getModuleConfig()->getLogDestinations();
326 326
 		if (!isset($logDest[$destination]))
327 327
 		{
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 		if (isset($postData['file']))
333 333
 		{ 
334 334
 			$file=$postData['file'];
335
-			$fileHandler=@fopen($file,'w');
335
+			$fileHandler=@fopen($file, 'w');
336 336
 			if ($fileHandler == false)
337 337
 			{   // File os note writabe / cannot create
338 338
 			    $this->_helper->json(array('status'=>'File not writable :  '.$file));
@@ -352,17 +352,17 @@  discard block
 block discarded – undo
352 352
 			}
353 353
 		}
354 354
 
355
-		$level = $this->checkPostVar($postData, 'level', '[0-9]');
355
+		$level=$this->checkPostVar($postData, 'level', '[0-9]');
356 356
 				
357 357
 		try
358 358
 		{
359
-		    $this->getUIDatabase()->setDBConfigValue('log_destination',$destination);
360
-		    $this->getUIDatabase()->setDBConfigValue('log_file',$file);
361
-		    $this->getUIDatabase()->setDBConfigValue('log_level',$level);
359
+		    $this->getUIDatabase()->setDBConfigValue('log_destination', $destination);
360
+		    $this->getUIDatabase()->setDBConfigValue('log_file', $file);
361
+		    $this->getUIDatabase()->setDBConfigValue('log_level', $level);
362 362
 		}
363 363
 		catch (Exception $e)
364 364
 		{
365
-			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
365
+			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage()));
366 366
 			return;
367 367
 		}
368 368
 		$this->_helper->json(array('status'=>'OK'));
@@ -380,29 +380,29 @@  discard block
 block discarded – undo
380 380
 	    
381 381
 	    $postData=$this->getRequest()->getPost();
382 382
 	   
383
-	    $rule = $this->checkPostVar($postData, 'rule', '.*');
383
+	    $rule=$this->checkPostVar($postData, 'rule', '.*');
384 384
 
385
-	    $action = $this->checkPostVar($postData, 'action', 'evaluate');
385
+	    $action=$this->checkPostVar($postData, 'action', 'evaluate');
386 386
 
387 387
 	    if ($action == 'evaluate')
388 388
 	    {
389 389
 	        try
390 390
 	        {
391
-	            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
391
+	            require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
392 392
 	            $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
393
-	            $trap = new Trap($icingaweb2_etc);
393
+	            $trap=new Trap($icingaweb2_etc);
394 394
 	            // Cleanup spaces before eval
395 395
 	            $rule=$trap->ruleClass->eval_cleanup($rule);
396 396
 	            // Eval
397 397
 	            $item=0;
398
-	            $rule=$trap->ruleClass->evaluation($rule,$item);
398
+	            $rule=$trap->ruleClass->evaluation($rule, $item);
399 399
 	        }
400 400
 	        catch (Exception $e)
401 401
 	        {
402
-	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
402
+	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage()));
403 403
 	            return;
404 404
 	        }
405
-	        $return=($rule==true)?'true':'false';
405
+	        $return=($rule == true) ? 'true' : 'false';
406 406
 	        $this->_helper->json(array('status'=>'OK', 'message' => $return));
407 407
 	    }
408 408
 	    
@@ -417,15 +417,15 @@  discard block
 block discarded – undo
417 417
 	{
418 418
 	    $postData=$this->getRequest()->getPost();
419 419
 	    
420
-	    $pluginName = $this->checkPostVar($postData, 'name', '.*');
420
+	    $pluginName=$this->checkPostVar($postData, 'name', '.*');
421 421
 	    
422
-	    $action = $this->checkPostVar($postData, 'action', 'enable|disable');
422
+	    $action=$this->checkPostVar($postData, 'action', 'enable|disable');
423 423
 	    
424 424
         try
425 425
         {
426
-            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
426
+            require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
427 427
             $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
428
-            $trap = new Trap($icingaweb2_etc);
428
+            $trap=new Trap($icingaweb2_etc);
429 429
             // Enable plugin.
430 430
             $action=($action == 'enable') ? true : false;
431 431
             $retVal=$trap->pluginClass->enablePlugin($pluginName, $action);
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
         }
434 434
         catch (Exception $e)
435 435
         {
436
-            $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
436
+            $this->_helper->json(array('status'=>'Action error : '.$e->getMessage()));
437 437
             return;
438 438
         }
439 439
         if ($retVal === true)
@@ -455,45 +455,45 @@  discard block
 block discarded – undo
455 455
 	{
456 456
 	    $postData=$this->getRequest()->getPost();
457 457
 	    
458
-	    $functionString = $this->checkPostVar($postData, 'function', '.*');
458
+	    $functionString=$this->checkPostVar($postData, 'function', '.*');
459 459
 	    
460 460
 	    $this->checkPostVar($postData, 'action', 'evaluate');
461 461
 	    
462 462
 	    // Only one action possible for now, no tests on action.
463 463
 	    try
464 464
 	    {
465
-	        require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
465
+	        require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
466 466
 	        $icingaweb2Etc=$this->Config()->get('config', 'icingaweb2_etc');
467
-	        $trap = new Trap($icingaweb2Etc);
467
+	        $trap=new Trap($icingaweb2Etc);
468 468
 	        // load all plugins in case tested function is not enabled.
469 469
 	        $trap->pluginClass->registerAllPlugins(false);
470 470
 	        // Clean all spaces
471
-	        $functionString = $trap->ruleClass->eval_cleanup($functionString);
471
+	        $functionString=$trap->ruleClass->eval_cleanup($functionString);
472 472
 	        // Eval functions
473
-	        $result = $trap->pluginClass->evaluateFunctionString($functionString);	        
473
+	        $result=$trap->pluginClass->evaluateFunctionString($functionString);	        
474 474
 	    }
475 475
 	    catch (Exception $e)
476 476
 	    {
477
-	        $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
477
+	        $this->_helper->json(array('status'=>'Action error : '.$e->getMessage()));
478 478
 	        return;
479 479
 	    }
480 480
 	    
481
-        $result = ($result === true)?'True':'False';
482
-        $this->_helper->json(array('status'=>'OK','message' => $result));
481
+        $result=($result === true) ? 'True' : 'False';
482
+        $this->_helper->json(array('status'=>'OK', 'message' => $result));
483 483
 	}
484 484
 
485 485
     /**************   Utilities **********************/
486 486
 
487
-	private function checkPostVar(array $postData,string $postVar, string $validRegexp) : string
487
+	private function checkPostVar(array $postData, string $postVar, string $validRegexp) : string
488 488
 	{
489 489
 	    if (!isset ($postData[$postVar]))
490 490
 	    {
491
-	        $this->_helper->json(array('status'=>'No ' . $postVar));
491
+	        $this->_helper->json(array('status'=>'No '.$postVar));
492 492
 	        return '';
493 493
 	    }
494 494
 	    if (preg_match('/'.$validRegexp.'/', $postData[$postVar]) != 1)
495 495
 	    {
496
-	        $this->_helper->json(array('status'=>'Unknown ' . $postVar . ' value '.$postData[$postVar]));
496
+	        $this->_helper->json(array('status'=>'Unknown '.$postVar.' value '.$postData[$postVar]));
497 497
 	        return '';
498 498
 	    }
499 499
 	    return $postData[$postVar];
Please login to merge, or discard this patch.
Braces   +18 added lines, -36 removed lines patch added patch discarded remove patch
@@ -26,8 +26,7 @@  discard block
 block discarded – undo
26 26
         {
27 27
           $hosts=$this->getIdoConn()->getHostByNameOrIP($hostFilter);
28 28
           $retHosts['test']=count($hosts);
29
-        }
30
-        else 
29
+        } else 
31 30
         {
32 31
 		  $hosts=$this->getIdoConn()->getHostByIP($hostFilter);
33 32
         }
@@ -73,8 +72,7 @@  discard block
 block discarded – undo
73 72
 		if (isset($postData['host']))
74 73
 		{
75 74
 			$host=$postData['host'];
76
-		}
77
-		else
75
+		} else
78 76
 		{
79 77
 			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
80 78
 			return;
@@ -85,8 +83,7 @@  discard block
 block discarded – undo
85 83
 		{	
86 84
 			$this->_helper->json(array('status'=>'More than one host matches','hostid' => -1));
87 85
 			return;
88
-		}
89
-		else if (count($hostArray) == 0)
86
+		} else if (count($hostArray) == 0)
90 87
 		{
91 88
 			$this->_helper->json(array('status'=>'No host matches','hostid' => -1));
92 89
 			return;
@@ -122,8 +119,7 @@  discard block
 block discarded – undo
122 119
 		{	
123 120
 			$this->_helper->json(array('status'=>'More than one hostgroup matches','hostid' => -1));
124 121
 			return;
125
-		}
126
-		else if (count($hostArray) == 0)
122
+		} else if (count($hostArray) == 0)
127 123
 		{
128 124
 			$this->_helper->json(array('status'=>'No hostgroup matches','hostid' => -1));
129 125
 			return;
@@ -154,8 +150,7 @@  discard block
 block discarded – undo
154 150
 		{
155 151
 			$traplist=$this->getMIB()->getTrapList($mib);
156 152
 			$retTraps=array('status'=>'OK','traps' => $traplist);
157
-		} 
158
-		catch (Exception $e) 
153
+		} catch (Exception $e) 
159 154
 		{ 
160 155
 			$retTraps=array('status' => 'Error getting mibs');
161 156
 		}
@@ -177,8 +172,7 @@  discard block
 block discarded – undo
177 172
 		{
178 173
 			$objectlist=$this->getMIB()->getObjectList($trap);
179 174
 			$retObjects=array('status'=>'OK','objects' => $objectlist);
180
-		} 
181
-		catch (Exception $e) 
175
+		} catch (Exception $e) 
182 176
 		{ 
183 177
 			$retObjects=array('status' => 'not found');
184 178
 		}
@@ -193,8 +187,7 @@  discard block
 block discarded – undo
193 187
 		try
194 188
 		{
195 189
 			$miblist=$this->getMIB()->getMIBList();
196
-		} 
197
-		catch (Exception $e) 
190
+		} catch (Exception $e) 
198 191
 		{ 
199 192
 			$miblist=array('Error getting mibs');
200 193
 		}
@@ -217,8 +210,7 @@  discard block
 block discarded – undo
217 210
 		{
218 211
 			$this->_helper->json(array('status'=>'Not found'));
219 212
 			return;
220
-		}
221
-		else
213
+		} else
222 214
 		{
223 215
 			$this->_helper->json(
224 216
 				array('status'=>'OK',
@@ -253,8 +245,7 @@  discard block
 block discarded – undo
253 245
 			try
254 246
 			{
255 247
 			    $this->getUIDatabase()->setDBConfigValue('db_remove_days',$days);
256
-			}
257
-			catch (Exception $e)
248
+			} catch (Exception $e)
258 249
 			{
259 250
 				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
260 251
 				return;
@@ -272,8 +263,7 @@  discard block
 block discarded – undo
272 263
 				$trap = new Trap($icingaweb2_etc);
273 264
 				$trap->setLogging($debug_level,'syslog');
274 265
 				$trap->eraseOldTraps($days);
275
-			}
276
-			catch (Exception $e)
266
+			} catch (Exception $e)
277 267
 			{
278 268
 				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage() ));
279 269
 				return;
@@ -300,8 +290,7 @@  discard block
 block discarded – undo
300 290
 	    {
301 291
 	        $this->getUIDatabase()->setDBConfigValue('use_SnmpTrapAddess',$snmpUse);
302 292
 	        $this->getUIDatabase()->setDBConfigValue('SnmpTrapAddess_oid',$snmpOID);
303
-	    }
304
-	    catch (Exception $e)
293
+	    } catch (Exception $e)
305 294
 	    {
306 295
 	        $this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
307 296
 	        return;
@@ -338,14 +327,12 @@  discard block
 block discarded – undo
338 327
 			    $this->_helper->json(array('status'=>'File not writable :  '.$file));
339 328
 			    return;
340 329
 			}
341
-		}
342
-		else
330
+		} else
343 331
 		{
344 332
 			if ($destination != 'file')
345 333
 			{
346 334
 				$file=null;
347
-			}
348
-			else
335
+			} else
349 336
 			{
350 337
 				$this->_helper->json(array('status'=>'No file'));
351 338
 				return;
@@ -359,8 +346,7 @@  discard block
 block discarded – undo
359 346
 		    $this->getUIDatabase()->setDBConfigValue('log_destination',$destination);
360 347
 		    $this->getUIDatabase()->setDBConfigValue('log_file',$file);
361 348
 		    $this->getUIDatabase()->setDBConfigValue('log_level',$level);
362
-		}
363
-		catch (Exception $e)
349
+		} catch (Exception $e)
364 350
 		{
365 351
 			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
366 352
 			return;
@@ -396,8 +382,7 @@  discard block
 block discarded – undo
396 382
 	            // Eval
397 383
 	            $item=0;
398 384
 	            $rule=$trap->ruleClass->evaluation($rule,$item);
399
-	        }
400
-	        catch (Exception $e)
385
+	        } catch (Exception $e)
401 386
 	        {
402 387
 	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
403 388
 	            return;
@@ -430,8 +415,7 @@  discard block
 block discarded – undo
430 415
             $action=($action == 'enable') ? true : false;
431 416
             $retVal=$trap->pluginClass->enablePlugin($pluginName, $action);
432 417
             
433
-        }
434
-        catch (Exception $e)
418
+        } catch (Exception $e)
435 419
         {
436 420
             $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
437 421
             return;
@@ -439,8 +423,7 @@  discard block
 block discarded – undo
439 423
         if ($retVal === true)
440 424
         {
441 425
             $this->_helper->json(array('status'=>'OK'));
442
-        }
443
-        else
426
+        } else
444 427
         {
445 428
             $this->_helper->json(array('status'=>'Error, see logs'));
446 429
         }
@@ -471,8 +454,7 @@  discard block
 block discarded – undo
471 454
 	        $functionString = $trap->ruleClass->eval_cleanup($functionString);
472 455
 	        // Eval functions
473 456
 	        $result = $trap->pluginClass->evaluateFunctionString($functionString);	        
474
-	    }
475
-	    catch (Exception $e)
457
+	    } catch (Exception $e)
476 458
 	    {
477 459
 	        $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
478 460
 	        return;
Please login to merge, or discard this patch.
library/Trapdirector/Icinga2API.php 3 patches
Braces   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -84,10 +84,11 @@  discard block
 block discarded – undo
84 84
     {
85 85
         $host = $this->getHostByFilter(
86 86
             'host.__name=="'. $name .'"');
87
-        if (isset($host[0]))
88
-            return $host[0];
89
-        else
90
-            return NULL;
87
+        if (isset($host[0])) {
88
+                    return $host[0];
89
+        } else {
90
+                    return NULL;
91
+        }
91 92
     }
92 93
  
93 94
     /**
@@ -173,8 +174,7 @@  discard block
 block discarded – undo
173 174
                 {
174 175
                     $serviceList[$service->name]=
175 176
                         array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
176
-                }
177
-                else
177
+                } else
178 178
                 {
179 179
                     $serviceList[$service->name]['num']++;
180 180
                 }
Please login to merge, or discard this patch.
Indentation   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -10,303 +10,303 @@
 block discarded – undo
10 10
 class Icinga2API extends IcingaApiBase
11 11
 {
12 12
     
13
-    /**
14
-     * Creates Icinga2API object
15
-     * 
16
-     * @param string $host host name or IP
17
-     * @param number $port API port
18
-     */
19
-    public function __construct($host, $port = 5665)
20
-    {
21
-        parent::__construct($host,$port);
22
-    }
23
-    /**
13
+	/**
14
+	 * Creates Icinga2API object
15
+	 * 
16
+	 * @param string $host host name or IP
17
+	 * @param number $port API port
18
+	 */
19
+	public function __construct($host, $port = 5665)
20
+	{
21
+		parent::__construct($host,$port);
22
+	}
23
+	/**
24 24
 
25 25
 /************ Host query ************/  
26 26
 
27
-    /**
28
-     * return array of host by filter
29
-     * @param string $hostfilter
30
-     * @throws Exception
31
-     * @return array objects : array('__name','name','display_name','id' (=__name), 'address', 'ip4' (=address), 'address6', 'ip6' (=address6)
32
-     */
33
-    public function getHostByFilter(string $hostfilter)
34
-    {
35
-        $hosts = $this->standardQuery(
36
-            'host',
37
-            $hostfilter,
38
-            //'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
39
-            array('__name','name','display_name','address','address6')
40
-            );
41
-        foreach ( array_keys($hosts) as $key )
42
-        {
43
-            $hosts[$key]->id = $hosts[$key]->__name;
44
-            $hosts[$key]->ip4 = $hosts[$key]->address;
45
-            $hosts[$key]->ip6 = $hosts[$key]->address6;
46
-        }
47
-        return $hosts;
48
-    }
27
+	/**
28
+	 * return array of host by filter
29
+	 * @param string $hostfilter
30
+	 * @throws Exception
31
+	 * @return array objects : array('__name','name','display_name','id' (=__name), 'address', 'ip4' (=address), 'address6', 'ip6' (=address6)
32
+	 */
33
+	public function getHostByFilter(string $hostfilter)
34
+	{
35
+		$hosts = $this->standardQuery(
36
+			'host',
37
+			$hostfilter,
38
+			//'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
39
+			array('__name','name','display_name','address','address6')
40
+			);
41
+		foreach ( array_keys($hosts) as $key )
42
+		{
43
+			$hosts[$key]->id = $hosts[$key]->__name;
44
+			$hosts[$key]->ip4 = $hosts[$key]->address;
45
+			$hosts[$key]->ip6 = $hosts[$key]->address6;
46
+		}
47
+		return $hosts;
48
+	}
49 49
     
50
-    /**
51
-     * return array of host by IP (4 or 6)
52
-     * @param string $ip
53
-     * @throws Exception
54
-     * @return array objects : array('__name','name','display_name')
55
-     */
56
-    public function getHostByIP(string $ip) 
57
-    {
58
-        return $this->getHostByFilter('match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6)');
59
-    }
50
+	/**
51
+	 * return array of host by IP (4 or 6)
52
+	 * @param string $ip
53
+	 * @throws Exception
54
+	 * @return array objects : array('__name','name','display_name')
55
+	 */
56
+	public function getHostByIP(string $ip) 
57
+	{
58
+		return $this->getHostByFilter('match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6)');
59
+	}
60 60
 
61 61
     
62
-    /**
63
-     * Get host(s) by name in API
64
-     * @param string $name
65
-     * @return array|NULL[] : see getHostByIP
66
-     */
67
-    public function getHostByName(string $name)
68
-    {
69
-        return $this->getHostByFilter('match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name)');
70
-    }
62
+	/**
63
+	 * Get host(s) by name in API
64
+	 * @param string $name
65
+	 * @return array|NULL[] : see getHostByIP
66
+	 */
67
+	public function getHostByName(string $name)
68
+	{
69
+		return $this->getHostByFilter('match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name)');
70
+	}
71 71
 
72
-    /**
73
-     * Get host(s) by name in API
74
-     * @param string $name
75
-     * @return array|NULL[] : see getHostByIP
76
-     */
77
-    public function getHostByNameOrIP(string $name)
78
-    {
79
-        return $this->getHostByFilter( 
80
-            'match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name) || match("*' . $name . '*",host.address) || match("*' . $name . '*",host.address6)');
81
-    }
72
+	/**
73
+	 * Get host(s) by name in API
74
+	 * @param string $name
75
+	 * @return array|NULL[] : see getHostByIP
76
+	 */
77
+	public function getHostByNameOrIP(string $name)
78
+	{
79
+		return $this->getHostByFilter( 
80
+			'match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name) || match("*' . $name . '*",host.address) || match("*' . $name . '*",host.address6)');
81
+	}
82 82
     
83
-    public function getHostInfoByID(string $name)
84
-    {
85
-        $host = $this->getHostByFilter(
86
-            'host.__name=="'. $name .'"');
87
-        if (isset($host[0]))
88
-            return $host[0];
89
-        else
90
-            return NULL;
91
-    }
83
+	public function getHostInfoByID(string $name)
84
+	{
85
+		$host = $this->getHostByFilter(
86
+			'host.__name=="'. $name .'"');
87
+		if (isset($host[0]))
88
+			return $host[0];
89
+		else
90
+			return NULL;
91
+	}
92 92
  
93
-    /**
94
-     * Get all host and IP from hostgroup
95
-     * @param string $hostGroup
96
-     * @throws Exception
97
-     * @return array : attributes : address, address6, name
98
-     */
99
-    public function getHostsIPByHostGroup($hostGroup)
100
-    {        
101
-        return $this->standardQuery(
102
-            'host', 
103
-            '"' . $hostGroup . '" in host.groups',
104
-            array('address','address6','name')
93
+	/**
94
+	 * Get all host and IP from hostgroup
95
+	 * @param string $hostGroup
96
+	 * @throws Exception
97
+	 * @return array : attributes : address, address6, name
98
+	 */
99
+	public function getHostsIPByHostGroup($hostGroup)
100
+	{        
101
+		return $this->standardQuery(
102
+			'host', 
103
+			'"' . $hostGroup . '" in host.groups',
104
+			array('address','address6','name')
105 105
                 
106
-        );
107
-    }
106
+		);
107
+	}
108 108
 
109 109
 
110
-    /** Get services from host in API
111
-     *	
112
-     *  @throws Exception
113
-     *	@param $id string host name
114
-     *  @param bool $active
115
-     *  @param bool $passive_svc
116
-     *	@return array display_name (of service), service_object_id
117
-     */
118
-    public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
119
-    {
120
-        $filter = 'match("' . $id . '!*", service.__name)';
121
-        if ($active === TRUE)
122
-        {
123
-            $filter .= ' && service.active==true';
124
-        }
125
-        if ($passive_svc === TRUE)
126
-        {
127
-            $filter .= ' && service.enable_passive_checks==true';
128
-        }
129
-        $services =  $this->standardQuery(
130
-            'service',
131
-            $filter,
132
-            array('__name','name','display_name','active')
133
-            );
110
+	/** Get services from host in API
111
+	 *	
112
+	 *  @throws Exception
113
+	 *	@param $id string host name
114
+	 *  @param bool $active
115
+	 *  @param bool $passive_svc
116
+	 *	@return array display_name (of service), service_object_id
117
+	 */
118
+	public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
119
+	{
120
+		$filter = 'match("' . $id . '!*", service.__name)';
121
+		if ($active === TRUE)
122
+		{
123
+			$filter .= ' && service.active==true';
124
+		}
125
+		if ($passive_svc === TRUE)
126
+		{
127
+			$filter .= ' && service.enable_passive_checks==true';
128
+		}
129
+		$services =  $this->standardQuery(
130
+			'service',
131
+			$filter,
132
+			array('__name','name','display_name','active')
133
+			);
134 134
         
135
-        foreach ( array_keys($services) as $key )
136
-        {
137
-            $services[$key]->id = $services[$key]->__name;
138
-        }
135
+		foreach ( array_keys($services) as $key )
136
+		{
137
+			$services[$key]->id = $services[$key]->__name;
138
+		}
139 139
         
140
-        return $services;
140
+		return $services;
141 141
         
142
-    }
142
+	}
143 143
 
144 144
 /************  Host group query ************/    
145
-    /**
146
-     * return array of host by IP (4 or 6) or name
147
-     * @param string $group Host group name
148
-     * @throws Exception
149
-     * @return array objects : array('name','display_name')
150
-     */
151
-    public function getHostsByGroup(string $group)
152
-    {
153
-         return $this->standardQuery(
154
-            'host',
155
-            '"' . $group . '" in host.groups',
156
-            array('name','display_name')
157
-            );
158
-    }
145
+	/**
146
+	 * return array of host by IP (4 or 6) or name
147
+	 * @param string $group Host group name
148
+	 * @throws Exception
149
+	 * @return array objects : array('name','display_name')
150
+	 */
151
+	public function getHostsByGroup(string $group)
152
+	{
153
+		 return $this->standardQuery(
154
+			'host',
155
+			'"' . $group . '" in host.groups',
156
+			array('name','display_name')
157
+			);
158
+	}
159 159
     
160
-    public function getServicesByHostGroupid(string $group)
161
-    {
162
-        $hostList = $this->getHostsByGroup($group);
163
-        //return $hostList;
164
-        $hostNum = count($hostList);
165
-        $serviceList=array();
166
-        foreach ($hostList as $curHost)
167
-        {
168
-            $services = $this->getServicesByHostid($curHost->name);
169
-            foreach ($services as $service)
170
-            {
171
-                //return $service;
172
-                if (! isset($serviceList[$service->name]))
173
-                {
174
-                    $serviceList[$service->name]=
175
-                        array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
176
-                }
177
-                else
178
-                {
179
-                    $serviceList[$service->name]['num']++;
180
-                }
181
-            }
182
-        }
183
-        $commonServices=array();
184
-        foreach ($serviceList as $key => $values)
185
-        {
186
-            if ($values['num'] >= $hostNum)
187
-            {
188
-                array_push($commonServices,array($key,$values['display_name']));
189
-            }
190
-        }
191
-        return $commonServices;
192
-    }
160
+	public function getServicesByHostGroupid(string $group)
161
+	{
162
+		$hostList = $this->getHostsByGroup($group);
163
+		//return $hostList;
164
+		$hostNum = count($hostList);
165
+		$serviceList=array();
166
+		foreach ($hostList as $curHost)
167
+		{
168
+			$services = $this->getServicesByHostid($curHost->name);
169
+			foreach ($services as $service)
170
+			{
171
+				//return $service;
172
+				if (! isset($serviceList[$service->name]))
173
+				{
174
+					$serviceList[$service->name]=
175
+						array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
176
+				}
177
+				else
178
+				{
179
+					$serviceList[$service->name]['num']++;
180
+				}
181
+			}
182
+		}
183
+		$commonServices=array();
184
+		foreach ($serviceList as $key => $values)
185
+		{
186
+			if ($values['num'] >= $hostNum)
187
+			{
188
+				array_push($commonServices,array($key,$values['display_name']));
189
+			}
190
+		}
191
+		return $commonServices;
192
+	}
193 193
  
194
-    /**
195
-     * Get all host and IP from hostgroup
196
-     * @param string $hostGroup
197
-     * @throws Exception
198
-     * @return array : attributes : address, address6, name
199
-     */
200
-    public function getHostGroupByName($name)
201
-    {
202
-        $hosts = $this->standardQuery(
203
-            'hostgroup',
204
-            'match("*' . $name . '*",hostgroup.name)',
205
-            array('__name','name','display_name')
194
+	/**
195
+	 * Get all host and IP from hostgroup
196
+	 * @param string $hostGroup
197
+	 * @throws Exception
198
+	 * @return array : attributes : address, address6, name
199
+	 */
200
+	public function getHostGroupByName($name)
201
+	{
202
+		$hosts = $this->standardQuery(
203
+			'hostgroup',
204
+			'match("*' . $name . '*",hostgroup.name)',
205
+			array('__name','name','display_name')
206 206
             
207
-            );
208
-        foreach ( array_keys($hosts) as $key )
209
-        {
210
-            $hosts[$key]->id = $hosts[$key]->__name;
211
-        }
212
-        return $hosts;
213
-    }
207
+			);
208
+		foreach ( array_keys($hosts) as $key )
209
+		{
210
+			$hosts[$key]->id = $hosts[$key]->__name;
211
+		}
212
+		return $hosts;
213
+	}
214 214
     
215
-    /**
216
-     * Get hostgroup by id (__name)
217
-     * @param string $hostGroup
218
-     * @throws Exception
219
-     * @return array : __name, name, display_name
220
-     */
221
-    public function getHostGroupById($name)
222
-    {
223
-        $hosts = $this->standardQuery(
224
-            'hostgroup',
225
-            'hostgroup.__name=="'. $name .'"',
226
-            array('__name','name','display_name')
215
+	/**
216
+	 * Get hostgroup by id (__name)
217
+	 * @param string $hostGroup
218
+	 * @throws Exception
219
+	 * @return array : __name, name, display_name
220
+	 */
221
+	public function getHostGroupById($name)
222
+	{
223
+		$hosts = $this->standardQuery(
224
+			'hostgroup',
225
+			'hostgroup.__name=="'. $name .'"',
226
+			array('__name','name','display_name')
227 227
             
228
-            );
229
-        $hosts[0]->id = $hosts[0]->__name;
230
-        return $hosts[0];
231
-    }
228
+			);
229
+		$hosts[0]->id = $hosts[0]->__name;
230
+		return $hosts[0];
231
+	}
232 232
     
233 233
 /****************   Service queries ************/
234
-    /** Get services object id by host name / service name
235
-     *	does not catch exceptions
236
-     *	@param $hostname string host name
237
-     *	@param $name string service name
238
-     *  @param bool $active : if true, return only active service
239
-     *  @param bool $passive_svc : if true, return only service accepting passive checks
240
-     *	@return array  service id
241
-     */
242
-    public function getServiceIDByName($hostname,$name,bool $active = TRUE, bool $passive_svc = TRUE)
243
-    {
244
-        $filter = 'service.__name=="' . $hostname . '!'. $name .'"';
245
-        if ($active === TRUE)
246
-        {
247
-            $filter .= ' && service.active==true';
248
-        }
249
-        if ($passive_svc === TRUE)
250
-        {
251
-            $filter .= ' && service.enable_passive_checks==true';
252
-        }
253
-        $services =  $this->standardQuery(
254
-            'service',
255
-            $filter,
256
-            array('__name','name','display_name','active','enable_passive_checks')
257
-            );
234
+	/** Get services object id by host name / service name
235
+	 *	does not catch exceptions
236
+	 *	@param $hostname string host name
237
+	 *	@param $name string service name
238
+	 *  @param bool $active : if true, return only active service
239
+	 *  @param bool $passive_svc : if true, return only service accepting passive checks
240
+	 *	@return array  service id
241
+	 */
242
+	public function getServiceIDByName($hostname,$name,bool $active = TRUE, bool $passive_svc = TRUE)
243
+	{
244
+		$filter = 'service.__name=="' . $hostname . '!'. $name .'"';
245
+		if ($active === TRUE)
246
+		{
247
+			$filter .= ' && service.active==true';
248
+		}
249
+		if ($passive_svc === TRUE)
250
+		{
251
+			$filter .= ' && service.enable_passive_checks==true';
252
+		}
253
+		$services =  $this->standardQuery(
254
+			'service',
255
+			$filter,
256
+			array('__name','name','display_name','active','enable_passive_checks')
257
+			);
258 258
         
259
-        foreach ( array_keys($services) as $key )
260
-        {
261
-            $services[$key]->id = $services[$key]->__name;
262
-        }
259
+		foreach ( array_keys($services) as $key )
260
+		{
261
+			$services[$key]->id = $services[$key]->__name;
262
+		}
263 263
         
264
-        return $services;
265
-    }
264
+		return $services;
265
+	}
266 266
  
267
-    /** Get services object by id (host!name)
268
-     *	does not catch exceptions
269
-     *	@param $name string service __name (host!name)
270
-     *	@return array  service id
271
-     */
272
-    public function getServiceById($name)
273
-    {
274
-        $filter = 'service.__name=="' .  $name .'"';
275
-        $services =  $this->standardQuery(
276
-            'service',
277
-            $filter,
278
-            array('__name','name','display_name','active','enable_passive_checks')
279
-            );
267
+	/** Get services object by id (host!name)
268
+	 *	does not catch exceptions
269
+	 *	@param $name string service __name (host!name)
270
+	 *	@return array  service id
271
+	 */
272
+	public function getServiceById($name)
273
+	{
274
+		$filter = 'service.__name=="' .  $name .'"';
275
+		$services =  $this->standardQuery(
276
+			'service',
277
+			$filter,
278
+			array('__name','name','display_name','active','enable_passive_checks')
279
+			);
280 280
         
281
-        foreach ( array_keys($services) as $key )
282
-        {
283
-            $services[$key]->id = $services[$key]->__name;
284
-        }
281
+		foreach ( array_keys($services) as $key )
282
+		{
283
+			$services[$key]->id = $services[$key]->__name;
284
+		}
285 285
         
286
-        return $services;
287
-    }
286
+		return $services;
287
+	}
288 288
 
289
-    /** Get services object by id (host!name)
290
-     *	does not catch exceptions
291
-     *	@param $name string service __name (host!name)
292
-     *	@return array  service id
293
-     */
294
-    public function getNOKService()
295
-    {
296
-        $filter = 'service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
-        $services =  $this->standardQuery(
298
-            'service',
299
-            $filter,
300
-            array('__name','name','last_check','host_name','state')
301
-            );
289
+	/** Get services object by id (host!name)
290
+	 *	does not catch exceptions
291
+	 *	@param $name string service __name (host!name)
292
+	 *	@return array  service id
293
+	 */
294
+	public function getNOKService()
295
+	{
296
+		$filter = 'service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
+		$services =  $this->standardQuery(
298
+			'service',
299
+			$filter,
300
+			array('__name','name','last_check','host_name','state')
301
+			);
302 302
         
303
-        foreach ( array_keys($services) as $key )
304
-        {
305
-            $services[$key]->id = $services[$key]->__name;
306
-        }
303
+		foreach ( array_keys($services) as $key )
304
+		{
305
+			$services[$key]->id = $services[$key]->__name;
306
+		}
307 307
         
308
-        return $services;
309
-    }
308
+		return $services;
309
+	}
310 310
     
311 311
     
312 312
 }
Please login to merge, or discard this patch.
Spacing   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -16,9 +16,9 @@  discard block
 block discarded – undo
16 16
      * @param string $host host name or IP
17 17
      * @param number $port API port
18 18
      */
19
-    public function __construct($host, $port = 5665)
19
+    public function __construct($host, $port=5665)
20 20
     {
21
-        parent::__construct($host,$port);
21
+        parent::__construct($host, $port);
22 22
     }
23 23
     /**
24 24
 
@@ -32,17 +32,17 @@  discard block
 block discarded – undo
32 32
      */
33 33
     public function getHostByFilter(string $hostfilter)
34 34
     {
35
-        $hosts = $this->standardQuery(
35
+        $hosts=$this->standardQuery(
36 36
             'host',
37 37
             $hostfilter,
38 38
             //'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
39
-            array('__name','name','display_name','address','address6')
39
+            array('__name', 'name', 'display_name', 'address', 'address6')
40 40
             );
41
-        foreach ( array_keys($hosts) as $key )
41
+        foreach (array_keys($hosts) as $key)
42 42
         {
43
-            $hosts[$key]->id = $hosts[$key]->__name;
44
-            $hosts[$key]->ip4 = $hosts[$key]->address;
45
-            $hosts[$key]->ip6 = $hosts[$key]->address6;
43
+            $hosts[$key]->id=$hosts[$key]->__name;
44
+            $hosts[$key]->ip4=$hosts[$key]->address;
45
+            $hosts[$key]->ip6=$hosts[$key]->address6;
46 46
         }
47 47
         return $hosts;
48 48
     }
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
      */
56 56
     public function getHostByIP(string $ip) 
57 57
     {
58
-        return $this->getHostByFilter('match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6)');
58
+        return $this->getHostByFilter('match("*'.$ip.'*",host.address) || match("*'.$ip.'*",host.address6)');
59 59
     }
60 60
 
61 61
     
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
      */
67 67
     public function getHostByName(string $name)
68 68
     {
69
-        return $this->getHostByFilter('match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name)');
69
+        return $this->getHostByFilter('match("*'.$name.'*",host.name) || match("*'.$name.'*",host.display_name)');
70 70
     }
71 71
 
72 72
     /**
@@ -77,13 +77,13 @@  discard block
 block discarded – undo
77 77
     public function getHostByNameOrIP(string $name)
78 78
     {
79 79
         return $this->getHostByFilter( 
80
-            'match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name) || match("*' . $name . '*",host.address) || match("*' . $name . '*",host.address6)');
80
+            'match("*'.$name.'*",host.name) || match("*'.$name.'*",host.display_name) || match("*'.$name.'*",host.address) || match("*'.$name.'*",host.address6)');
81 81
     }
82 82
     
83 83
     public function getHostInfoByID(string $name)
84 84
     {
85
-        $host = $this->getHostByFilter(
86
-            'host.__name=="'. $name .'"');
85
+        $host=$this->getHostByFilter(
86
+            'host.__name=="'.$name.'"');
87 87
         if (isset($host[0]))
88 88
             return $host[0];
89 89
         else
@@ -100,8 +100,8 @@  discard block
 block discarded – undo
100 100
     {        
101 101
         return $this->standardQuery(
102 102
             'host', 
103
-            '"' . $hostGroup . '" in host.groups',
104
-            array('address','address6','name')
103
+            '"'.$hostGroup.'" in host.groups',
104
+            array('address', 'address6', 'name')
105 105
                 
106 106
         );
107 107
     }
@@ -115,26 +115,26 @@  discard block
 block discarded – undo
115 115
      *  @param bool $passive_svc
116 116
      *	@return array display_name (of service), service_object_id
117 117
      */
118
-    public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
118
+    public function getServicesByHostid(string $id, bool $active=TRUE, bool $passive_svc=TRUE)
119 119
     {
120
-        $filter = 'match("' . $id . '!*", service.__name)';
120
+        $filter='match("'.$id.'!*", service.__name)';
121 121
         if ($active === TRUE)
122 122
         {
123
-            $filter .= ' && service.active==true';
123
+            $filter.=' && service.active==true';
124 124
         }
125 125
         if ($passive_svc === TRUE)
126 126
         {
127
-            $filter .= ' && service.enable_passive_checks==true';
127
+            $filter.=' && service.enable_passive_checks==true';
128 128
         }
129
-        $services =  $this->standardQuery(
129
+        $services=$this->standardQuery(
130 130
             'service',
131 131
             $filter,
132
-            array('__name','name','display_name','active')
132
+            array('__name', 'name', 'display_name', 'active')
133 133
             );
134 134
         
135
-        foreach ( array_keys($services) as $key )
135
+        foreach (array_keys($services) as $key)
136 136
         {
137
-            $services[$key]->id = $services[$key]->__name;
137
+            $services[$key]->id=$services[$key]->__name;
138 138
         }
139 139
         
140 140
         return $services;
@@ -152,27 +152,27 @@  discard block
 block discarded – undo
152 152
     {
153 153
          return $this->standardQuery(
154 154
             'host',
155
-            '"' . $group . '" in host.groups',
156
-            array('name','display_name')
155
+            '"'.$group.'" in host.groups',
156
+            array('name', 'display_name')
157 157
             );
158 158
     }
159 159
     
160 160
     public function getServicesByHostGroupid(string $group)
161 161
     {
162
-        $hostList = $this->getHostsByGroup($group);
162
+        $hostList=$this->getHostsByGroup($group);
163 163
         //return $hostList;
164
-        $hostNum = count($hostList);
164
+        $hostNum=count($hostList);
165 165
         $serviceList=array();
166 166
         foreach ($hostList as $curHost)
167 167
         {
168
-            $services = $this->getServicesByHostid($curHost->name);
168
+            $services=$this->getServicesByHostid($curHost->name);
169 169
             foreach ($services as $service)
170 170
             {
171 171
                 //return $service;
172
-                if (! isset($serviceList[$service->name]))
172
+                if (!isset($serviceList[$service->name]))
173 173
                 {
174 174
                     $serviceList[$service->name]=
175
-                        array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
175
+                        array('num'=> 1, '__name' => $service->__name, 'display_name' => $service->display_name);
176 176
                 }
177 177
                 else
178 178
                 {
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
         {
186 186
             if ($values['num'] >= $hostNum)
187 187
             {
188
-                array_push($commonServices,array($key,$values['display_name']));
188
+                array_push($commonServices, array($key, $values['display_name']));
189 189
             }
190 190
         }
191 191
         return $commonServices;
@@ -199,15 +199,15 @@  discard block
 block discarded – undo
199 199
      */
200 200
     public function getHostGroupByName($name)
201 201
     {
202
-        $hosts = $this->standardQuery(
202
+        $hosts=$this->standardQuery(
203 203
             'hostgroup',
204
-            'match("*' . $name . '*",hostgroup.name)',
205
-            array('__name','name','display_name')
204
+            'match("*'.$name.'*",hostgroup.name)',
205
+            array('__name', 'name', 'display_name')
206 206
             
207 207
             );
208
-        foreach ( array_keys($hosts) as $key )
208
+        foreach (array_keys($hosts) as $key)
209 209
         {
210
-            $hosts[$key]->id = $hosts[$key]->__name;
210
+            $hosts[$key]->id=$hosts[$key]->__name;
211 211
         }
212 212
         return $hosts;
213 213
     }
@@ -220,13 +220,13 @@  discard block
 block discarded – undo
220 220
      */
221 221
     public function getHostGroupById($name)
222 222
     {
223
-        $hosts = $this->standardQuery(
223
+        $hosts=$this->standardQuery(
224 224
             'hostgroup',
225
-            'hostgroup.__name=="'. $name .'"',
226
-            array('__name','name','display_name')
225
+            'hostgroup.__name=="'.$name.'"',
226
+            array('__name', 'name', 'display_name')
227 227
             
228 228
             );
229
-        $hosts[0]->id = $hosts[0]->__name;
229
+        $hosts[0]->id=$hosts[0]->__name;
230 230
         return $hosts[0];
231 231
     }
232 232
     
@@ -239,26 +239,26 @@  discard block
 block discarded – undo
239 239
      *  @param bool $passive_svc : if true, return only service accepting passive checks
240 240
      *	@return array  service id
241 241
      */
242
-    public function getServiceIDByName($hostname,$name,bool $active = TRUE, bool $passive_svc = TRUE)
242
+    public function getServiceIDByName($hostname, $name, bool $active=TRUE, bool $passive_svc=TRUE)
243 243
     {
244
-        $filter = 'service.__name=="' . $hostname . '!'. $name .'"';
244
+        $filter='service.__name=="'.$hostname.'!'.$name.'"';
245 245
         if ($active === TRUE)
246 246
         {
247
-            $filter .= ' && service.active==true';
247
+            $filter.=' && service.active==true';
248 248
         }
249 249
         if ($passive_svc === TRUE)
250 250
         {
251
-            $filter .= ' && service.enable_passive_checks==true';
251
+            $filter.=' && service.enable_passive_checks==true';
252 252
         }
253
-        $services =  $this->standardQuery(
253
+        $services=$this->standardQuery(
254 254
             'service',
255 255
             $filter,
256
-            array('__name','name','display_name','active','enable_passive_checks')
256
+            array('__name', 'name', 'display_name', 'active', 'enable_passive_checks')
257 257
             );
258 258
         
259
-        foreach ( array_keys($services) as $key )
259
+        foreach (array_keys($services) as $key)
260 260
         {
261
-            $services[$key]->id = $services[$key]->__name;
261
+            $services[$key]->id=$services[$key]->__name;
262 262
         }
263 263
         
264 264
         return $services;
@@ -271,16 +271,16 @@  discard block
 block discarded – undo
271 271
      */
272 272
     public function getServiceById($name)
273 273
     {
274
-        $filter = 'service.__name=="' .  $name .'"';
275
-        $services =  $this->standardQuery(
274
+        $filter='service.__name=="'.$name.'"';
275
+        $services=$this->standardQuery(
276 276
             'service',
277 277
             $filter,
278
-            array('__name','name','display_name','active','enable_passive_checks')
278
+            array('__name', 'name', 'display_name', 'active', 'enable_passive_checks')
279 279
             );
280 280
         
281
-        foreach ( array_keys($services) as $key )
281
+        foreach (array_keys($services) as $key)
282 282
         {
283
-            $services[$key]->id = $services[$key]->__name;
283
+            $services[$key]->id=$services[$key]->__name;
284 284
         }
285 285
         
286 286
         return $services;
@@ -293,16 +293,16 @@  discard block
 block discarded – undo
293 293
      */
294 294
     public function getNOKService()
295 295
     {
296
-        $filter = 'service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
-        $services =  $this->standardQuery(
296
+        $filter='service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
+        $services=$this->standardQuery(
298 298
             'service',
299 299
             $filter,
300
-            array('__name','name','last_check','host_name','state')
300
+            array('__name', 'name', 'last_check', 'host_name', 'state')
301 301
             );
302 302
         
303
-        foreach ( array_keys($services) as $key )
303
+        foreach (array_keys($services) as $key)
304 304
         {
305
-            $services[$key]->id = $services[$key]->__name;
305
+            $services[$key]->id=$services[$key]->__name;
306 306
         }
307 307
         
308 308
         return $services;
Please login to merge, or discard this patch.
application/controllers/StatusController.php 3 patches
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -21,8 +21,8 @@  discard block
 block discarded – undo
21 21
 		/************  Trapdb ***********/
22 22
 		try
23 23
 		{
24
-		    $dbConn = $this->getUIDatabase()->getDbConn();
25
-		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
24
+			$dbConn = $this->getUIDatabase()->getDbConn();
25
+			if ($dbConn === null) throw new \ErrorException('uncatched db error');
26 26
 			$query = $dbConn->select()->from(
27 27
 				$this->getModuleConfig()->getTrapTableName(),
28 28
 				array('COUNT(*)')
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 		
52 52
 		try
53 53
 		{		
54
-		    $this->view->currentLogDestination=$this->getUIDatabase()->getDBConfigValue('log_destination');
54
+			$this->view->currentLogDestination=$this->getUIDatabase()->getDBConfigValue('log_destination');
55 55
 			$this->view->logDestinations=$this->getModuleConfig()->getLogDestinations();
56 56
 			$this->view->currentLogFile=$this->getUIDatabase()->getDBConfigValue('log_file');
57 57
 			$this->view->logLevels=$this->getModuleConfig()->getlogLevels();
@@ -65,23 +65,23 @@  discard block
 block discarded – undo
65 65
 		/*************** SNMP configuration ****************/
66 66
 		try
67 67
 		{
68
-		    $this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
69
-		    $this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
-		    $this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
68
+			$this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
69
+			$this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
+			$this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
71 71
 		    
72 72
 		}
73 73
 		catch (Exception $e)
74 74
 		{
75
-		    $this->displayExitError('status',$e->getMessage());
75
+			$this->displayExitError('status',$e->getMessage());
76 76
 		}		
77 77
 		
78 78
 	} 
79 79
   
80 80
 	/** Mib management
81
-	*	Post param : action=update_mib_db : update mib database
82
-	*	Post param : ation=check_update : check if mib update is finished
83
-	*	File post : mibfile -> save mib file
84
-	*/
81
+	 *	Post param : action=update_mib_db : update mib database
82
+	 *	Post param : ation=check_update : check if mib update is finished
83
+	 *	File post : mibfile -> save mib file
84
+	 */
85 85
 	public function mibAction()
86 86
 	{
87 87
 		$this->prepareTabs()->activate('mib');
@@ -100,22 +100,22 @@  discard block
 block discarded – undo
100 100
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
101 101
 					if (preg_match('/OK/',$return))
102 102
 					{
103
-					    $this->_helper->json(array('status'=>'OK'));
103
+						$this->_helper->json(array('status'=>'OK'));
104 104
 					}
105 105
 					// Error
106 106
 					$this->_helper->json(array('status'=>$return));
107 107
 				}
108 108
 				if ($action == 'check_update')
109 109
 				{
110
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
111
-				    if ($file == false)
112
-				    {   // process is dead
113
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
114
-				        return;
115
-				    }
116
-				    $pid=fgets($file);
117
-				    $output=array();
118
-				    $retVal=0;
110
+					$file=@fopen('/tmp/trapdirector_update.pid','r');
111
+					if ($file == false)
112
+					{   // process is dead
113
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
114
+						return;
115
+					}
116
+					$pid=fgets($file);
117
+					$output=array();
118
+					$retVal=0;
119 119
 					exec('ps '.$pid,$output,$retVal);
120 120
 					if ($retVal == 0)
121 121
 					{ // process is alive
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 					}
124 124
 					else
125 125
 					{ // process is dead
126
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
126
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
127 127
 					}
128 128
 				}
129 129
 				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
@@ -136,27 +136,27 @@  discard block
 block discarded – undo
136 136
 				$destDir=array_shift($DirConf);
137 137
 				if (!is_dir($destDir))
138 138
 				{
139
-				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
139
+					$this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
140 140
 				}
141 141
 				else
142 142
 				{
143
-				    if (!is_writable($destDir))
144
-				    {
145
-				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
146
-				    }
147
-				    else
148
-				    {
149
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150
-				        $sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']);
151
-				        if (move_uploaded_file($sourceTmpNam,$destination)===false)
152
-    				    {
153
-    				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154
-    				    }
155
-    				    else
156
-    				    {
157
-    				        $this->view->uploadStatus="File $name uploaded in $destDir";
158
-    				    }
159
-				    }
143
+					if (!is_writable($destDir))
144
+					{
145
+						$this->view->uploadStatus="ERROR : $destDir directory is not writable";
146
+					}
147
+					else
148
+					{
149
+						$destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150
+						$sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']);
151
+						if (move_uploaded_file($sourceTmpNam,$destination)===false)
152
+						{
153
+							$this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154
+						}
155
+						else
156
+						{
157
+							$this->view->uploadStatus="File $name uploaded in $destDir";
158
+						}
159
+					}
160 160
 				}
161 161
 
162 162
 			}
@@ -172,16 +172,16 @@  discard block
 block discarded – undo
172 172
 			$translate=exec($snmptranslate . ' 1');
173 173
 			if (preg_match('/iso/',$translate))
174 174
 			{
175
-			    $translate=exec($snmptranslate . ' 1.3.6.1.4');
176
-			    if (preg_match('/private/',$translate))
177
-			    {		    
178
-    				$this->view->snmptranslate='works fine';
179
-    				$this->view->snmptranslate_state='ok';
180
-			    }
181
-			    else
182
-			    {
183
-			        $this->view->snmptranslate='works fine but missing basic MIBs';
184
-			    }
175
+				$translate=exec($snmptranslate . ' 1.3.6.1.4');
176
+				if (preg_match('/private/',$translate))
177
+				{		    
178
+					$this->view->snmptranslate='works fine';
179
+					$this->view->snmptranslate_state='ok';
180
+				}
181
+				else
182
+				{
183
+					$this->view->snmptranslate='works fine but missing basic MIBs';
184
+				}
185 185
 			}
186 186
 			else
187 187
 			{
@@ -244,63 +244,63 @@  discard block
 block discarded – undo
244 244
 	/** UI options */
245 245
 	public function uimgtAction()
246 246
 	{
247
-	    $this->prepareTabs()->activate('uimgt');
247
+		$this->prepareTabs()->activate('uimgt');
248 248
 	    
249
-	    $this->view->setError='';
250
-	    $this->view->setOKMsg='';
249
+		$this->view->setError='';
250
+		$this->view->setOKMsg='';
251 251
 	    
252
-	    //max_rows=25&row_update=update
253
-	    if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
254
-	    {
255
-	        $maxRows = $this->getRequest()->getParam('max_rows');
256
-	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257
-	        {
258
-	            $this->view->setError='Max rows must be a number';
259
-	        }
260
-	        else
261
-	        {
262
-	            $this->setitemListDisplay($maxRows);
263
-	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
264
-	        }
265
-	    }
252
+		//max_rows=25&row_update=update
253
+		if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
254
+		{
255
+			$maxRows = $this->getRequest()->getParam('max_rows');
256
+			if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257
+			{
258
+				$this->view->setError='Max rows must be a number';
259
+			}
260
+			else
261
+			{
262
+				$this->setitemListDisplay($maxRows);
263
+				$this->view->setOKMsg='Set max rows to ' . $maxRows;
264
+			}
265
+		}
266 266
 	    
267
-	    if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
268
-	    {
269
-	        $addCat = $this->getRequest()->getParam('add_category');
270
-            $this->addHandlersCategory($addCat);
271
-	    }
267
+		if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
268
+		{
269
+			$addCat = $this->getRequest()->getParam('add_category');
270
+			$this->addHandlersCategory($addCat);
271
+		}
272 272
 	    
273
-	    if ( $this->getRequest()->getPost('type',NULL) !== NULL )
274
-	    {
275
-	        $type = $this->getRequest()->getPost('type',NULL);
276
-	        $index = $this->getRequest()->getPost('index',NULL);
277
-	        $newname = $this->getRequest()->getPost('newname',NULL);
273
+		if ( $this->getRequest()->getPost('type',NULL) !== NULL )
274
+		{
275
+			$type = $this->getRequest()->getPost('type',NULL);
276
+			$index = $this->getRequest()->getPost('index',NULL);
277
+			$newname = $this->getRequest()->getPost('newname',NULL);
278 278
 
279
-	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280
-	            $this->_helper->json(array('status'=>'Bad index'));
279
+			if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280
+				$this->_helper->json(array('status'=>'Bad index'));
281 281
 	        
282
-	        switch ($type)
283
-	        {
284
-	            case 'delete':
285
-	                $this->delHandlersCategory($index);
286
-	                $this->_helper->json(array('status'=>'OK'));
287
-	                return;
288
-	                break;
289
-	            case 'rename':
290
-	                $this->renameHandlersCategory($index, $newname);
291
-	                $this->_helper->json(array('status'=>'OK'));
292
-	                return;
293
-	                break;
294
-	            default:
295
-	                $this->_helper->json(array('status'=>'Unknwon command'));
296
-	                return;
297
-	                break;
298
-	        }
299
-	    }
282
+			switch ($type)
283
+			{
284
+				case 'delete':
285
+					$this->delHandlersCategory($index);
286
+					$this->_helper->json(array('status'=>'OK'));
287
+					return;
288
+					break;
289
+				case 'rename':
290
+					$this->renameHandlersCategory($index, $newname);
291
+					$this->_helper->json(array('status'=>'OK'));
292
+					return;
293
+					break;
294
+				default:
295
+					$this->_helper->json(array('status'=>'Unknwon command'));
296
+					return;
297
+					break;
298
+			}
299
+		}
300 300
 	    
301
-	    $this->view->maxRows = $this->itemListDisplay();
301
+		$this->view->maxRows = $this->itemListDisplay();
302 302
 	    
303
-	    $this->view->categories = $this->getHandlersCategory();
303
+		$this->view->categories = $this->getHandlersCategory();
304 304
 	    
305 305
 	    
306 306
 	    
@@ -349,47 +349,47 @@  discard block
 block discarded – undo
349 349
 	 */
350 350
 	public function pluginsAction()
351 351
 	{
352
-	    $this->prepareTabs()->activate('plugins');
352
+		$this->prepareTabs()->activate('plugins');
353 353
 	    
354
-	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
355
-	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
356
-	    $Trap = new Trap($icingaweb2_etc,4);
354
+		require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
355
+		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
356
+		$Trap = new Trap($icingaweb2_etc,4);
357 357
 	    
358
-	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
358
+		$this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
359 359
 	    
360
-	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
360
+		$enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
361 361
 
362
-	    $pluginList = $Trap->pluginClass->pluginList();
362
+		$pluginList = $Trap->pluginClass->pluginList();
363 363
 	    
364
-	    // Plugin list and fill function name list
365
-	    $functionList=array();
366
-	    $this->view->pluginArray=array();
367
-	    foreach ($pluginList as $plugin)
368
-	    {
369
-	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
370
-	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
371
-	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
372
-	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
373
-	        $pluginDetails->description = htmlentities($pluginDetails->description);
374
-	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
375
-	        array_push($this->view->pluginArray, $pluginDetails);
376
-	        // Get functions for function details
377
-	        foreach ($pluginDetails->funcArray as $function)
378
-	        {
379
-	            array_push($functionList,$function);
380
-	        }
381
-	    }
364
+		// Plugin list and fill function name list
365
+		$functionList=array();
366
+		$this->view->pluginArray=array();
367
+		foreach ($pluginList as $plugin)
368
+		{
369
+			$pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
370
+			$pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
371
+			$pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
372
+			$pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
373
+			$pluginDetails->description = htmlentities($pluginDetails->description);
374
+			$pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
375
+			array_push($this->view->pluginArray, $pluginDetails);
376
+			// Get functions for function details
377
+			foreach ($pluginDetails->funcArray as $function)
378
+			{
379
+				array_push($functionList,$function);
380
+			}
381
+		}
382 382
 	    
383
-	    // Function list with details
384
-	    $this->view->functionList=array();
385
-	    foreach ($functionList as $function)
386
-	    {
387
-	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
388
-	        $functionDetail->params = htmlentities($functionDetail->params);
389
-	        $functionDetail->description = htmlentities($functionDetail->description);
390
-	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
391
-	        array_push($this->view->functionList, $functionDetail);
392
-	    }
383
+		// Function list with details
384
+		$this->view->functionList=array();
385
+		foreach ($functionList as $function)
386
+		{
387
+			$functionDetail = $Trap->pluginClass->getFunctionDetails($function);
388
+			$functionDetail->params = htmlentities($functionDetail->params);
389
+			$functionDetail->description = htmlentities($functionDetail->description);
390
+			$functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
391
+			array_push($this->view->functionList, $functionDetail);
392
+		}
393 393
 
394 394
 	}
395 395
 
@@ -398,47 +398,47 @@  discard block
 block discarded – undo
398 398
 	 */
399 399
 	public function debugAction()
400 400
 	{
401
-	    $this->view->answer='No answer';
402
-	    $this->view->input1 = '';
401
+		$this->view->answer='No answer';
402
+		$this->view->input1 = '';
403 403
 	    
404
-	    $postData=$this->getRequest()->getPost();
405
-	    if (isset($postData['input1']))
406
-	    {
407
-	        $input1 = $postData['input1'];
408
-	        $input2 = $postData['input2'];
409
-	        $input3 = $postData['input3'];
410
-	        $this->view->input1 = $input1;
411
-	        //$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
412
-	        try {
413
-	            $this->view->answer = 'Answer : ';
414
-	            $API = $this->getIdoConn();
415
-	            $DB = $this->getUIDatabase();
404
+		$postData=$this->getRequest()->getPost();
405
+		if (isset($postData['input1']))
406
+		{
407
+			$input1 = $postData['input1'];
408
+			$input2 = $postData['input2'];
409
+			$input3 = $postData['input3'];
410
+			$this->view->input1 = $input1;
411
+			//$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
412
+			try {
413
+				$this->view->answer = 'Answer : ';
414
+				$API = $this->getIdoConn();
415
+				$DB = $this->getUIDatabase();
416 416
 
417
-	            //$hosts = $DB->getServicesByHostGroupid($input1);
418
-	            //$this->view->answer .= 'services : '.print_r($hosts,true);
417
+				//$hosts = $DB->getServicesByHostGroupid($input1);
418
+				//$this->view->answer .= 'services : '.print_r($hosts,true);
419 419
 	            
420
-	            $hosts = $API->getServicesByHostGroupid($input1);
421
-	            $this->view->answer .= 'services : '.print_r($hosts,true);
420
+				$hosts = $API->getServicesByHostGroupid($input1);
421
+				$this->view->answer .= 'services : '.print_r($hosts,true);
422 422
 	            
423 423
 
424 424
 	            
425
-	            return;
426
-	            $hosts = $API->getHostByIP($input1);
427
-	            $this->view->answer .= 'Host : '. print_r($hosts,true);
428
-	            $hosts = $API->getHostGroupByName($input1);
429
-	            $this->view->answer .= 'Group : '.print_r($hosts,true);
430
-	            $hosts = $API->getServicesByHostid($input1);
431
-	            $this->view->answer .= 'service : '.print_r($hosts,true);
425
+				return;
426
+				$hosts = $API->getHostByIP($input1);
427
+				$this->view->answer .= 'Host : '. print_r($hosts,true);
428
+				$hosts = $API->getHostGroupByName($input1);
429
+				$this->view->answer .= 'Group : '.print_r($hosts,true);
430
+				$hosts = $API->getServicesByHostid($input1);
431
+				$this->view->answer .= 'service : '.print_r($hosts,true);
432 432
 	            
433
-	            /* $hosts = $API->getHostsIPByHostGroup($input1);
433
+				/* $hosts = $API->getHostsIPByHostGroup($input1);
434 434
 	            $this->view->answer .= "\n Hostgrp : " . print_r($hosts,true); */
435 435
 	            
436
-	        } catch (Exception $e)
437
-	        {
438
-	            $this->view->answer = "Exception : " . print_r($e);
439
-	        }
436
+			} catch (Exception $e)
437
+			{
438
+				$this->view->answer = "Exception : " . print_r($e);
439
+			}
440 440
 	        
441
-	    }
441
+		}
442 442
 	    
443 443
 	}
444 444
 	
@@ -450,36 +450,36 @@  discard block
 block discarded – undo
450 450
 		)->add('mib', array(
451 451
 			'label' => $this->translate('MIB Management'),
452 452
 			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
453
-	    )->add('uimgt', array(
454
-	        'label' => $this->translate('UI Configuration'),
455
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
456
-        )->add('services', array(
453
+		)->add('uimgt', array(
454
+			'label' => $this->translate('UI Configuration'),
455
+			'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
456
+		)->add('services', array(
457 457
 			'label' => $this->translate('Services management'),
458 458
 			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
459
-	    )->add('plugins', array(
460
-	        'label' => $this->translate('Plugins management'),
461
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
462
-	    );
459
+		)->add('plugins', array(
460
+			'label' => $this->translate('Plugins management'),
461
+			'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
462
+		);
463 463
 	} 
464 464
 }
465 465
 
466 466
 // TODO : see if useless 
467 467
 class UploadForm extends Form
468 468
 { 
469
-    public function __construct($options = null) 
470
-    {
471
-        parent::__construct($options);
472
-        $this->addElements2();
473
-    }
469
+	public function __construct($options = null) 
470
+	{
471
+		parent::__construct($options);
472
+		$this->addElements2();
473
+	}
474 474
 
475
-    public function addElements2()
476
-    {
477
-        // File Input
478
-        $file = new File('mib-file');
479
-        $file->setLabel('Mib upload');
480
-             //->setAttrib('multiple', null);
481
-        $this->addElement($file);
475
+	public function addElements2()
476
+	{
477
+		// File Input
478
+		$file = new File('mib-file');
479
+		$file->setLabel('Mib upload');
480
+			 //->setAttrib('multiple', null);
481
+		$this->addElement($file);
482 482
 		$button = new Submit("upload",array('ignore'=>false));
483 483
 		$this->addElement($button);//->setIgnore(false);
484
-    }
484
+	}
485 485
 }
Please login to merge, or discard this patch.
Spacing   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -21,19 +21,19 @@  discard block
 block discarded – undo
21 21
 		/************  Trapdb ***********/
22 22
 		try
23 23
 		{
24
-		    $dbConn = $this->getUIDatabase()->getDbConn();
24
+		    $dbConn=$this->getUIDatabase()->getDbConn();
25 25
 		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
26
-			$query = $dbConn->select()->from(
26
+			$query=$dbConn->select()->from(
27 27
 				$this->getModuleConfig()->getTrapTableName(),
28 28
 				array('COUNT(*)')
29 29
 			);			
30 30
 			$this->view->trap_count=$dbConn->fetchOne($query);
31
-			$query = $dbConn->select()->from(
31
+			$query=$dbConn->select()->from(
32 32
 				$this->getModuleConfig()->getTrapDataTableName(),
33 33
 				array('COUNT(*)')
34 34
 			);			
35 35
 			$this->view->trap_object_count=$dbConn->fetchOne($query);
36
-			$query = $dbConn->select()->from(
36
+			$query=$dbConn->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,20 +59,20 @@  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
 		/*************** SNMP configuration ****************/
66 66
 		try
67 67
 		{
68
-		    $this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
68
+		    $this->view->useSnmpTrapAddess=($this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1) ? TRUE : FALSE;
69 69
 		    $this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
-		    $this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
70
+		    $this->view->SnmpTrapAddressOIDDefault=($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid']) ? TRUE : FALSE;
71 71
 		    
72 72
 		}
73 73
 		catch (Exception $e)
74 74
 		{
75
-		    $this->displayExitError('status',$e->getMessage());
75
+		    $this->displayExitError('status', $e->getMessage());
76 76
 		}		
77 77
 		
78 78
 	} 
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 				if ($action == 'update_mib_db')
99 99
 				{ // Do the update in background
100 100
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
101
-					if (preg_match('/OK/',$return))
101
+					if (preg_match('/OK/', $return))
102 102
 					{
103 103
 					    $this->_helper->json(array('status'=>'OK'));
104 104
 					}
@@ -107,32 +107,32 @@  discard block
 block discarded – undo
107 107
 				}
108 108
 				if ($action == 'check_update')
109 109
 				{
110
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
110
+				    $file=@fopen('/tmp/trapdirector_update.pid', 'r');
111 111
 				    if ($file == false)
112 112
 				    {   // process is dead
113
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
113
+				        $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'Cannot open file'));
114 114
 				        return;
115 115
 				    }
116 116
 				    $pid=fgets($file);
117 117
 				    $output=array();
118 118
 				    $retVal=0;
119
-					exec('ps '.$pid,$output,$retVal);
119
+					exec('ps '.$pid, $output, $retVal);
120 120
 					if ($retVal == 0)
121 121
 					{ // process is alive
122 122
 						$this->_helper->json(array('status'=>'Alive and kicking'));
123 123
 					}
124 124
 					else
125 125
 					{ // process is dead
126
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
126
+					    $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'no proc'.$pid));
127 127
 					}
128 128
 				}
129
-				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
129
+				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible'));
130 130
 			}
131 131
 			/** Check for mib file UPLOAD */
132 132
 			if (isset($_FILES['mibfile']))
133 133
 			{
134 134
 				$name=htmlspecialchars($_FILES['mibfile']['name']);
135
-				$DirConf=explode(':',$this->Config()->get('config', 'snmptranslate_dirs'));
135
+				$DirConf=explode(':', $this->Config()->get('config', 'snmptranslate_dirs'));
136 136
 				$destDir=array_shift($DirConf);
137 137
 				if (!is_dir($destDir))
138 138
 				{
@@ -146,9 +146,9 @@  discard block
 block discarded – undo
146 146
 				    }
147 147
 				    else
148 148
 				    {
149
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
149
+				        $destination=$destDir.'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150 150
 				        $sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']);
151
-				        if (move_uploaded_file($sourceTmpNam,$destination)===false)
151
+				        if (move_uploaded_file($sourceTmpNam, $destination) === false)
152 152
     				    {
153 153
     				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154 154
     				    }
@@ -164,16 +164,16 @@  discard block
 block discarded – undo
164 164
 		}
165 165
 		
166 166
 		// snmptranslate tests
167
-		$snmptranslate = $this->Config()->get('config', 'snmptranslate');
167
+		$snmptranslate=$this->Config()->get('config', 'snmptranslate');
168 168
 		$this->view->snmptranslate_bin=$snmptranslate;
169 169
 		$this->view->snmptranslate_state='warn';
170
-		if (is_executable ( $snmptranslate ))
170
+		if (is_executable($snmptranslate))
171 171
 		{
172
-			$translate=exec($snmptranslate . ' 1');
173
-			if (preg_match('/iso/',$translate))
172
+			$translate=exec($snmptranslate.' 1');
173
+			if (preg_match('/iso/', $translate))
174 174
 			{
175
-			    $translate=exec($snmptranslate . ' 1.3.6.1.4');
176
-			    if (preg_match('/private/',$translate))
175
+			    $translate=exec($snmptranslate.' 1.3.6.1.4');
176
+			    if (preg_match('/private/', $translate))
177 177
 			    {		    
178 178
     				$this->view->snmptranslate='works fine';
179 179
     				$this->view->snmptranslate_state='ok';
@@ -196,46 +196,46 @@  discard block
 block discarded – undo
196 196
 		// mib database
197 197
 		
198 198
 		$this->view->mibDbCount=$this->getMIB()->countObjects();
199
-		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null,21);
199
+		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null, 21);
200 200
 		
201 201
 		// mib dirs
202 202
 		$DirConf=$this->Config()->get('config', 'snmptranslate_dirs');
203
-		$dirArray=explode(':',$DirConf);
203
+		$dirArray=explode(':', $DirConf);
204 204
 
205 205
 		// Get base directories from net-snmp-config
206 206
 		$output=$matches=array();
207 207
 		$retVal=0;
208
-		$sysDirs=exec('net-snmp-config --default-mibdirs',$output,$retVal);
209
-		if ($retVal==0)
208
+		$sysDirs=exec('net-snmp-config --default-mibdirs', $output, $retVal);
209
+		if ($retVal == 0)
210 210
 		{
211
-			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
211
+			$dirArray=array_merge($dirArray, explode(':', $sysDirs));
212 212
 		}
213 213
 		else
214 214
 		{
215
-			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
216
-			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
215
+			$translateOut=exec($this->Config()->get('config', 'snmptranslate').' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
216
+			if (preg_match('/MIBDIRS.*\'([^\']+)\'/', $translateOut, $matches))
217 217
 			{
218
-				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
218
+				$dirArray=array_merge($dirArray, explode(':', $matches[1]));
219 219
 			}
220 220
 			else
221 221
 			{
222
-				array_push($dirArray,'Install net-snmp-config to see system directories');
222
+				array_push($dirArray, 'Install net-snmp-config to see system directories');
223 223
 			}
224 224
 		}
225 225
 		
226 226
 		$this->view->dirArray=$dirArray;
227 227
 		
228 228
 		$output=null;
229
-		foreach (explode(':',$DirConf) as $mibdir)
229
+		foreach (explode(':', $DirConf) as $mibdir)
230 230
 		{
231
-			exec('ls '.$mibdir.' | grep -v traplist.txt',$output);
231
+			exec('ls '.$mibdir.' | grep -v traplist.txt', $output);
232 232
 		}
233 233
 		//$i=0;$listFiles='';while (isset($output[$i])) $listFiles.=$output[$i++];
234 234
 		//$this->view->fileList=explode(' ',$listFiles);
235 235
 		$this->view->fileList=$output;
236 236
 		
237 237
 		// Zend form 
238
-		$this->view->form= new UploadForm();
238
+		$this->view->form=new UploadForm();
239 239
 		//$this->view->form= new Form('upload-form');
240 240
 		
241 241
 		
@@ -250,9 +250,9 @@  discard block
 block discarded – undo
250 250
 	    $this->view->setOKMsg='';
251 251
 	    
252 252
 	    //max_rows=25&row_update=update
253
-	    if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
253
+	    if ($this->getRequest()->getParam('max_rows', NULL) !== NULL)
254 254
 	    {
255
-	        $maxRows = $this->getRequest()->getParam('max_rows');
255
+	        $maxRows=$this->getRequest()->getParam('max_rows');
256 256
 	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257 257
 	        {
258 258
 	            $this->view->setError='Max rows must be a number';
@@ -260,21 +260,21 @@  discard block
 block discarded – undo
260 260
 	        else
261 261
 	        {
262 262
 	            $this->setitemListDisplay($maxRows);
263
-	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
263
+	            $this->view->setOKMsg='Set max rows to '.$maxRows;
264 264
 	        }
265 265
 	    }
266 266
 	    
267
-	    if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
267
+	    if ($this->getRequest()->getParam('add_category', NULL) !== NULL)
268 268
 	    {
269
-	        $addCat = $this->getRequest()->getParam('add_category');
269
+	        $addCat=$this->getRequest()->getParam('add_category');
270 270
             $this->addHandlersCategory($addCat);
271 271
 	    }
272 272
 	    
273
-	    if ( $this->getRequest()->getPost('type',NULL) !== NULL )
273
+	    if ($this->getRequest()->getPost('type', NULL) !== NULL)
274 274
 	    {
275
-	        $type = $this->getRequest()->getPost('type',NULL);
276
-	        $index = $this->getRequest()->getPost('index',NULL);
277
-	        $newname = $this->getRequest()->getPost('newname',NULL);
275
+	        $type=$this->getRequest()->getPost('type', NULL);
276
+	        $index=$this->getRequest()->getPost('index', NULL);
277
+	        $newname=$this->getRequest()->getPost('newname', NULL);
278 278
 
279 279
 	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280 280
 	            $this->_helper->json(array('status'=>'Bad index'));
@@ -298,9 +298,9 @@  discard block
 block discarded – undo
298 298
 	        }
299 299
 	    }
300 300
 	    
301
-	    $this->view->maxRows = $this->itemListDisplay();
301
+	    $this->view->maxRows=$this->itemListDisplay();
302 302
 	    
303
-	    $this->view->categories = $this->getHandlersCategory();
303
+	    $this->view->categories=$this->getHandlersCategory();
304 304
 	    
305 305
 	    
306 306
 	    
@@ -324,18 +324,18 @@  discard block
 block discarded – undo
324 324
 		$this->view->templateForm_output='';
325 325
 		if (isset($postData['template_name']) && isset($postData['template_revert_time']))
326 326
 		{
327
-			$template_create = 'icingacli director service create --json \'{ "check_command": "dummy", ';
328
-			$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", ';
329
-			$template_create .= '"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
327
+			$template_create='icingacli director service create --json \'{ "check_command": "dummy", ';
328
+			$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", ';
329
+			$template_create.='"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
330 330
 			$output=array();
331 331
 			$ret_code=0;
332
-			exec($template_create,$output,$ret_code);
332
+			exec($template_create, $output, $ret_code);
333 333
 			if ($ret_code != 0)
334 334
 			{
335
-				$this->displayExitError("Status -> Services","Error creating template : ".$output[0].'<br>Command was : '.$template_create);
335
+				$this->displayExitError("Status -> Services", "Error creating template : ".$output[0].'<br>Command was : '.$template_create);
336 336
 			}
337
-			exec('icingacli director config deploy',$output,$ret_code);
338
-			$this->view->templateForm_output='Template '.$postData['template_name']. ' created';
337
+			exec('icingacli director config deploy', $output, $ret_code);
338
+			$this->view->templateForm_output='Template '.$postData['template_name'].' created';
339 339
 		}
340 340
 		
341 341
 		// template creation form
@@ -351,15 +351,15 @@  discard block
 block discarded – undo
351 351
 	{
352 352
 	    $this->prepareTabs()->activate('plugins');
353 353
 	    
354
-	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
354
+	    require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
355 355
 	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
356
-	    $Trap = new Trap($icingaweb2_etc,4);
356
+	    $Trap=new Trap($icingaweb2_etc, 4);
357 357
 	    
358
-	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
358
+	    $this->view->pluginLoaded=htmlentities($Trap->pluginClass->registerAllPlugins(false));
359 359
 	    
360
-	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
360
+	    $enabledPlugins=$Trap->pluginClass->getEnabledPlugins();
361 361
 
362
-	    $pluginList = $Trap->pluginClass->pluginList();
362
+	    $pluginList=$Trap->pluginClass->pluginList();
363 363
 	    
364 364
 	    // Plugin list and fill function name list
365 365
 	    $functionList=array();
@@ -367,16 +367,16 @@  discard block
 block discarded – undo
367 367
 	    foreach ($pluginList as $plugin)
368 368
 	    {
369 369
 	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
370
-	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
371
-	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
372
-	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
373
-	        $pluginDetails->description = htmlentities($pluginDetails->description);
374
-	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
370
+	        $pluginDetails->enabled=(in_array($plugin, $enabledPlugins)) ? true : false;
371
+	        $pluginDetails->catchAllTraps=($pluginDetails->catchAllTraps === true) ? 'Yes' : 'No';
372
+	        $pluginDetails->processTraps=($pluginDetails->processTraps === true) ? 'Yes' : 'No';
373
+	        $pluginDetails->description=htmlentities($pluginDetails->description);
374
+	        $pluginDetails->description=preg_replace('/\n/', '<br>', $pluginDetails->description);
375 375
 	        array_push($this->view->pluginArray, $pluginDetails);
376 376
 	        // Get functions for function details
377 377
 	        foreach ($pluginDetails->funcArray as $function)
378 378
 	        {
379
-	            array_push($functionList,$function);
379
+	            array_push($functionList, $function);
380 380
 	        }
381 381
 	    }
382 382
 	    
@@ -384,10 +384,10 @@  discard block
 block discarded – undo
384 384
 	    $this->view->functionList=array();
385 385
 	    foreach ($functionList as $function)
386 386
 	    {
387
-	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
388
-	        $functionDetail->params = htmlentities($functionDetail->params);
389
-	        $functionDetail->description = htmlentities($functionDetail->description);
390
-	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
387
+	        $functionDetail=$Trap->pluginClass->getFunctionDetails($function);
388
+	        $functionDetail->params=htmlentities($functionDetail->params);
389
+	        $functionDetail->description=htmlentities($functionDetail->description);
390
+	        $functionDetail->description=preg_replace('/\n/', '<br>', $functionDetail->description);
391 391
 	        array_push($this->view->functionList, $functionDetail);
392 392
 	    }
393 393
 
@@ -399,43 +399,43 @@  discard block
 block discarded – undo
399 399
 	public function debugAction()
400 400
 	{
401 401
 	    $this->view->answer='No answer';
402
-	    $this->view->input1 = '';
402
+	    $this->view->input1='';
403 403
 	    
404 404
 	    $postData=$this->getRequest()->getPost();
405 405
 	    if (isset($postData['input1']))
406 406
 	    {
407
-	        $input1 = $postData['input1'];
408
-	        $input2 = $postData['input2'];
409
-	        $input3 = $postData['input3'];
410
-	        $this->view->input1 = $input1;
407
+	        $input1=$postData['input1'];
408
+	        $input2=$postData['input2'];
409
+	        $input3=$postData['input3'];
410
+	        $this->view->input1=$input1;
411 411
 	        //$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
412 412
 	        try {
413
-	            $this->view->answer = 'Answer : ';
414
-	            $API = $this->getIdoConn();
415
-	            $DB = $this->getUIDatabase();
413
+	            $this->view->answer='Answer : ';
414
+	            $API=$this->getIdoConn();
415
+	            $DB=$this->getUIDatabase();
416 416
 
417 417
 	            //$hosts = $DB->getServicesByHostGroupid($input1);
418 418
 	            //$this->view->answer .= 'services : '.print_r($hosts,true);
419 419
 	            
420
-	            $hosts = $API->getServicesByHostGroupid($input1);
421
-	            $this->view->answer .= 'services : '.print_r($hosts,true);
420
+	            $hosts=$API->getServicesByHostGroupid($input1);
421
+	            $this->view->answer.='services : '.print_r($hosts, true);
422 422
 	            
423 423
 
424 424
 	            
425 425
 	            return;
426
-	            $hosts = $API->getHostByIP($input1);
427
-	            $this->view->answer .= 'Host : '. print_r($hosts,true);
428
-	            $hosts = $API->getHostGroupByName($input1);
429
-	            $this->view->answer .= 'Group : '.print_r($hosts,true);
430
-	            $hosts = $API->getServicesByHostid($input1);
431
-	            $this->view->answer .= 'service : '.print_r($hosts,true);
426
+	            $hosts=$API->getHostByIP($input1);
427
+	            $this->view->answer.='Host : '.print_r($hosts, true);
428
+	            $hosts=$API->getHostGroupByName($input1);
429
+	            $this->view->answer.='Group : '.print_r($hosts, true);
430
+	            $hosts=$API->getServicesByHostid($input1);
431
+	            $this->view->answer.='service : '.print_r($hosts, true);
432 432
 	            
433 433
 	            /* $hosts = $API->getHostsIPByHostGroup($input1);
434 434
 	            $this->view->answer .= "\n Hostgrp : " . print_r($hosts,true); */
435 435
 	            
436 436
 	        } catch (Exception $e)
437 437
 	        {
438
-	            $this->view->answer = "Exception : " . print_r($e);
438
+	            $this->view->answer="Exception : ".print_r($e);
439 439
 	        }
440 440
 	        
441 441
 	    }
@@ -446,19 +446,19 @@  discard block
 block discarded – undo
446 446
 	{
447 447
 		return $this->getTabs()->add('status', array(
448 448
 			'label' => $this->translate('Status'),
449
-			'url'   => $this->getModuleConfig()->urlPath() . '/status')
449
+			'url'   => $this->getModuleConfig()->urlPath().'/status')
450 450
 		)->add('mib', array(
451 451
 			'label' => $this->translate('MIB Management'),
452
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
452
+			'url'   => $this->getModuleConfig()->urlPath().'/status/mib')
453 453
 	    )->add('uimgt', array(
454 454
 	        'label' => $this->translate('UI Configuration'),
455
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
455
+	        'url'   => $this->getModuleConfig()->urlPath().'/status/uimgt')
456 456
         )->add('services', array(
457 457
 			'label' => $this->translate('Services management'),
458
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
458
+			'url'   => $this->getModuleConfig()->urlPath().'/status/services')
459 459
 	    )->add('plugins', array(
460 460
 	        'label' => $this->translate('Plugins management'),
461
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
461
+	        'url'   => $this->getModuleConfig()->urlPath().'/status/plugins')
462 462
 	    );
463 463
 	} 
464 464
 }
@@ -466,7 +466,7 @@  discard block
 block discarded – undo
466 466
 // TODO : see if useless 
467 467
 class UploadForm extends Form
468 468
 { 
469
-    public function __construct($options = null) 
469
+    public function __construct($options=null) 
470 470
     {
471 471
         parent::__construct($options);
472 472
         $this->addElements2();
@@ -475,11 +475,11 @@  discard block
 block discarded – undo
475 475
     public function addElements2()
476 476
     {
477 477
         // File Input
478
-        $file = new File('mib-file');
478
+        $file=new File('mib-file');
479 479
         $file->setLabel('Mib upload');
480 480
              //->setAttrib('multiple', null);
481 481
         $this->addElement($file);
482
-		$button = new Submit("upload",array('ignore'=>false));
483
-		$this->addElement($button);//->setIgnore(false);
482
+		$button=new Submit("upload", array('ignore'=>false));
483
+		$this->addElement($button); //->setIgnore(false);
484 484
     }
485 485
 }
Please login to merge, or discard this patch.
Braces   +19 added lines, -29 removed lines patch added patch discarded remove patch
@@ -22,7 +22,9 @@  discard block
 block discarded – undo
22 22
 		try
23 23
 		{
24 24
 		    $dbConn = $this->getUIDatabase()->getDbConn();
25
-		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
25
+		    if ($dbConn === null) {
26
+		    	throw new \ErrorException('uncatched db error');
27
+		    }
26 28
 			$query = $dbConn->select()->from(
27 29
 				$this->getModuleConfig()->getTrapTableName(),
28 30
 				array('COUNT(*)')
@@ -41,8 +43,7 @@  discard block
 block discarded – undo
41 43
  			
42 44
 			$this->view->trap_days_delete=$this->getUIDatabase()->getDBConfigValue('db_remove_days');
43 45
 			
44
-		}
45
-		catch (Exception $e)
46
+		} catch (Exception $e)
46 47
 		{
47 48
 			$this->displayExitError('status',$e->getMessage());
48 49
 		}
@@ -56,8 +57,7 @@  discard block
 block discarded – undo
56 57
 			$this->view->currentLogFile=$this->getUIDatabase()->getDBConfigValue('log_file');
57 58
 			$this->view->logLevels=$this->getModuleConfig()->getlogLevels();
58 59
 			$this->view->currentLogLevel=$this->getUIDatabase()->getDBConfigValue('log_level');
59
-		}
60
-		catch (Exception $e)
60
+		} catch (Exception $e)
61 61
 		{
62 62
 			$this->displayExitError('status',$e->getMessage());
63 63
 		}
@@ -69,8 +69,7 @@  discard block
 block discarded – undo
69 69
 		    $this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70 70
 		    $this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
71 71
 		    
72
-		}
73
-		catch (Exception $e)
72
+		} catch (Exception $e)
74 73
 		{
75 74
 		    $this->displayExitError('status',$e->getMessage());
76 75
 		}		
@@ -120,8 +119,7 @@  discard block
 block discarded – undo
120 119
 					if ($retVal == 0)
121 120
 					{ // process is alive
122 121
 						$this->_helper->json(array('status'=>'Alive and kicking'));
123
-					}
124
-					else
122
+					} else
125 123
 					{ // process is dead
126 124
 					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
127 125
 					}
@@ -137,22 +135,19 @@  discard block
 block discarded – undo
137 135
 				if (!is_dir($destDir))
138 136
 				{
139 137
 				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
140
-				}
141
-				else
138
+				} else
142 139
 				{
143 140
 				    if (!is_writable($destDir))
144 141
 				    {
145 142
 				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
146
-				    }
147
-				    else
143
+				    } else
148 144
 				    {
149 145
 				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150 146
 				        $sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']);
151 147
 				        if (move_uploaded_file($sourceTmpNam,$destination)===false)
152 148
     				    {
153 149
     				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154
-    				    }
155
-    				    else
150
+    				    } else
156 151
     				    {
157 152
     				        $this->view->uploadStatus="File $name uploaded in $destDir";
158 153
     				    }
@@ -177,18 +172,15 @@  discard block
 block discarded – undo
177 172
 			    {		    
178 173
     				$this->view->snmptranslate='works fine';
179 174
     				$this->view->snmptranslate_state='ok';
180
-			    }
181
-			    else
175
+			    } else
182 176
 			    {
183 177
 			        $this->view->snmptranslate='works fine but missing basic MIBs';
184 178
 			    }
185
-			}
186
-			else
179
+			} else
187 180
 			{
188 181
 				$this->view->snmptranslate='Can execute but no OID to name resolution';
189 182
 			}
190
-		}
191
-		else
183
+		} else
192 184
 		{
193 185
 			$this->view->snmptranslate='Cannot execute';
194 186
 		}
@@ -209,15 +201,13 @@  discard block
 block discarded – undo
209 201
 		if ($retVal==0)
210 202
 		{
211 203
 			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
212
-		}
213
-		else
204
+		} else
214 205
 		{
215 206
 			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
216 207
 			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
217 208
 			{
218 209
 				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
219
-			}
220
-			else
210
+			} else
221 211
 			{
222 212
 				array_push($dirArray,'Install net-snmp-config to see system directories');
223 213
 			}
@@ -256,8 +246,7 @@  discard block
 block discarded – undo
256 246
 	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257 247
 	        {
258 248
 	            $this->view->setError='Max rows must be a number';
259
-	        }
260
-	        else
249
+	        } else
261 250
 	        {
262 251
 	            $this->setitemListDisplay($maxRows);
263 252
 	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
@@ -276,8 +265,9 @@  discard block
 block discarded – undo
276 265
 	        $index = $this->getRequest()->getPost('index',NULL);
277 266
 	        $newname = $this->getRequest()->getPost('newname',NULL);
278 267
 
279
-	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280
-	            $this->_helper->json(array('status'=>'Bad index'));
268
+	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1) {
269
+	        	            $this->_helper->json(array('status'=>'Bad index'));
270
+	        }
281 271
 	        
282 272
 	        switch ($type)
283 273
 	        {
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/TrapConfig.php 3 patches
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -15,197 +15,197 @@
 block discarded – undo
15 15
 trait TrapConfig
16 16
 {
17 17
 
18
-    /** @return \Trapdirector\Logging   */
19
-    abstract public function getLogging();
20
-    /** @return \Trapdirector\TrapApi   */
21
-    abstract public function getTrapApi();
18
+	/** @return \Trapdirector\Logging   */
19
+	abstract public function getLogging();
20
+	/** @return \Trapdirector\TrapApi   */
21
+	abstract public function getTrapApi();
22 22
 
23
-    // TODO : Get default values from TrapModuleConfig 
24
-    /** @var bool	Use SnmpTrapAddess as source adress */
25
-    public $useSnmpTrapAddess=TRUE;
26
-    /** @var string	Special OID to get IP source address of trap emitter */
27
-    public $snmpTrapAddressOID='.1.3.6.1.6.3.18.1.3';
23
+	// TODO : Get default values from TrapModuleConfig 
24
+	/** @var bool	Use SnmpTrapAddess as source adress */
25
+	public $useSnmpTrapAddess=TRUE;
26
+	/** @var string	Special OID to get IP source address of trap emitter */
27
+	public $snmpTrapAddressOID='.1.3.6.1.6.3.18.1.3';
28 28
     
29
-    /**
30
-     * Get option from array of ini file, send message if empty
31
-     * @param string $option_array Array of ini file
32
-     * @param string $option_category category in ini file
33
-     * @param string $option_name name of option in category
34
-     * @param mixed $option_var variable to fill if found, left untouched if not found
35
-     * @param integer $log_level default 2 (warning)
36
-     * @param string $message warning message if not found
37
-     * @return boolean true if found, or false
38
-     */
39
-    protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = WARN, $message = null)
40
-    {
41
-        if (!isset($option_array[$option_category][$option_name]))
42
-        {
43
-            if ($message === null)
44
-            {
45
-                $message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
46
-            }
47
-            $this->getLogging()->log($message,$log_level);
48
-            return false;
49
-        }
50
-        else
51
-        {
52
-            $option_var=$option_array[$option_category][$option_name];
53
-            return true;
54
-        }
55
-    }
29
+	/**
30
+	 * Get option from array of ini file, send message if empty
31
+	 * @param string $option_array Array of ini file
32
+	 * @param string $option_category category in ini file
33
+	 * @param string $option_name name of option in category
34
+	 * @param mixed $option_var variable to fill if found, left untouched if not found
35
+	 * @param integer $log_level default 2 (warning)
36
+	 * @param string $message warning message if not found
37
+	 * @return boolean true if found, or false
38
+	 */
39
+	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = WARN, $message = null)
40
+	{
41
+		if (!isset($option_array[$option_category][$option_name]))
42
+		{
43
+			if ($message === null)
44
+			{
45
+				$message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
46
+			}
47
+			$this->getLogging()->log($message,$log_level);
48
+			return false;
49
+		}
50
+		else
51
+		{
52
+			$option_var=$option_array[$option_category][$option_name];
53
+			return true;
54
+		}
55
+	}
56 56
 
57
-    /**
58
-     * Get options in database
59
-     */
60
-    protected function getDatabaseOptions()
61
-    {
62
-        // Database options
63
-        if ($this->logSetup === false) // Only if logging was no setup in constructor
64
-        {
65
-            $this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
66
-            $this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
67
-            $this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
68
-        }
69
-        
70
-        $tmpVal = -1; // Get boolean coded in database as 1/0
71
-        $this->getDBConfigIfSet('use_SnmpTrapAddess', $tmpVal);
72
-        if ($tmpVal != -1) $this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
73
-        
74
-        $this->getDBConfigIfSet('SnmpTrapAddess_oid', $this->snmpTrapAddressOID); // Get oid then replace '.' with '\.' to use in regexp whrn reading traps
75
-        $this->snmpTrapAddressOID = preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
76
-    }
77
-        
78
-    /** Set $variable to value if $element found in database config table
79
-     * @param string $element
80
-     * @param string $variable
81
-     */
82
-    protected function getDBConfigIfSet($element,&$variable)
83
-    {
84
-        $value=$this->getDBConfig($element);
85
-        if ($value != null) $variable=$value;
86
-    }
57
+	/**
58
+	 * Get options in database
59
+	 */
60
+	protected function getDatabaseOptions()
61
+	{
62
+		// Database options
63
+		if ($this->logSetup === false) // Only if logging was no setup in constructor
64
+		{
65
+			$this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
66
+			$this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
67
+			$this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
68
+		}
69
+        
70
+		$tmpVal = -1; // Get boolean coded in database as 1/0
71
+		$this->getDBConfigIfSet('use_SnmpTrapAddess', $tmpVal);
72
+		if ($tmpVal != -1) $this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
73
+        
74
+		$this->getDBConfigIfSet('SnmpTrapAddess_oid', $this->snmpTrapAddressOID); // Get oid then replace '.' with '\.' to use in regexp whrn reading traps
75
+		$this->snmpTrapAddressOID = preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
76
+	}
77
+        
78
+	/** Set $variable to value if $element found in database config table
79
+	 * @param string $element
80
+	 * @param string $variable
81
+	 */
82
+	protected function getDBConfigIfSet($element,&$variable)
83
+	{
84
+		$value=$this->getDBConfig($element);
85
+		if ($value != null) $variable=$value;
86
+	}
87 87
     
88
-    /**
89
-     *   Get data from db_config
90
-     *	@param $element string name of param
91
-     *	@return mixed : value (or null)
92
-     */
93
-    protected function getDBConfig($element)  // TODO : put this in DB class
94
-    {
95
-        $db_conn=$this->trapsDB->db_connect_trap();
96
-        $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
97
-        if (($ret_code=$db_conn->query($sql)) === false) {
98
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
99
-            return null;
100
-        }
101
-        $value=$ret_code->fetch();
102
-        if ($value != null && isset($value['value']))
103
-        {
104
-            return $value['value'];
105
-        }
106
-        return null;
107
-    }
88
+	/**
89
+	 *   Get data from db_config
90
+	 *	@param $element string name of param
91
+	 *	@return mixed : value (or null)
92
+	 */
93
+	protected function getDBConfig($element)  // TODO : put this in DB class
94
+	{
95
+		$db_conn=$this->trapsDB->db_connect_trap();
96
+		$sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
97
+		if (($ret_code=$db_conn->query($sql)) === false) {
98
+			$this->logging->log('No result in query : ' . $sql,WARN,'');
99
+			return null;
100
+		}
101
+		$value=$ret_code->fetch();
102
+		if ($value != null && isset($value['value']))
103
+		{
104
+			return $value['value'];
105
+		}
106
+		return null;
107
+	}
108 108
     
109
-    /**
110
-     * Get options from ini file
111
-     * @param array $trap_config : ini file array
112
-     */
113
-    protected function getMainOptions($trapConfig)
114
-    {
115
-        
116
-        $nodeStatus='';
117
-        $this->getOptionIfSet($trapConfig,'config','node', $nodeStatus);
118
-        if ($this->getTrapApi()->setStatus($nodeStatus) === FALSE)
119
-        {
120
-            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
121
-            $this->getTrapApi()->setStatusMaster();
122
-        }
123
-        else 
124
-        {
125
-            if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
126
-            {
127
-                // Get options to connect to API
128
-                $IP = $port = $user =  $pass = null;
129
-                $this->getOptionIfSet($trapConfig,'config','masterIP', $IP, ERROR);
130
-                $this->getOptionIfSet($trapConfig,'config','masterPort', $port, ERROR);
131
-                $this->getOptionIfSet($trapConfig,'config','masterUser', $user, ERROR);
132
-                $this->getOptionIfSet($trapConfig,'config','masterPass', $pass, ERROR);
133
-                $this->getTrapApi()->setParams($IP, $port, $user, $pass);
134
-                return;
135
-            }
136
-        }
137
-        
138
-        // Snmptranslate binary path
139
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
140
-        
141
-        // mibs path
142
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
143
-        
144
-        // icinga2cmd path
145
-        $this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
146
-        
147
-        // table prefix
148
-        $this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
149
-        
150
-        // API options
151
-        if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
152
-        {
153
-            $this->apiUse=true;
154
-            // Get API options or throw exception as not configured correctly
155
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort,ERROR);
156
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername,ERROR);
157
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword,ERROR);
158
-        }
159
-    }
109
+	/**
110
+	 * Get options from ini file
111
+	 * @param array $trap_config : ini file array
112
+	 */
113
+	protected function getMainOptions($trapConfig)
114
+	{
115
+        
116
+		$nodeStatus='';
117
+		$this->getOptionIfSet($trapConfig,'config','node', $nodeStatus);
118
+		if ($this->getTrapApi()->setStatus($nodeStatus) === FALSE)
119
+		{
120
+			$this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
121
+			$this->getTrapApi()->setStatusMaster();
122
+		}
123
+		else 
124
+		{
125
+			if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
126
+			{
127
+				// Get options to connect to API
128
+				$IP = $port = $user =  $pass = null;
129
+				$this->getOptionIfSet($trapConfig,'config','masterIP', $IP, ERROR);
130
+				$this->getOptionIfSet($trapConfig,'config','masterPort', $port, ERROR);
131
+				$this->getOptionIfSet($trapConfig,'config','masterUser', $user, ERROR);
132
+				$this->getOptionIfSet($trapConfig,'config','masterPass', $pass, ERROR);
133
+				$this->getTrapApi()->setParams($IP, $port, $user, $pass);
134
+				return;
135
+			}
136
+		}
137
+        
138
+		// Snmptranslate binary path
139
+		$this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
140
+        
141
+		// mibs path
142
+		$this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
143
+        
144
+		// icinga2cmd path
145
+		$this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
146
+        
147
+		// table prefix
148
+		$this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
149
+        
150
+		// API options
151
+		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
152
+		{
153
+			$this->apiUse=true;
154
+			// Get API options or throw exception as not configured correctly
155
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort,ERROR);
156
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername,ERROR);
157
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword,ERROR);
158
+		}
159
+	}
160 160
     
161
-    /**
162
-     * Create and setup database class for trap & ido (if no api) db
163
-     * @param array $trap_config : ini file array
164
-     */
165
-    protected function setupDatabase($trapConfig)
166
-    {
167
-        // Trap database
168
-        if (!array_key_exists('database',$trapConfig['config']))
169
-        {
170
-            $this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
171
-            return;
172
-        }
173
-        $dbTrapName=$trapConfig['config']['database'];
174
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
175
-        
176
-        if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
177
-        {
178
-            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
179
-            return;
180
-        }
181
-        if (!array_key_exists($dbTrapName,$dbConfig))
182
-        {
183
-            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
184
-            return;
185
-        }
186
-        
187
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
188
-        
189
-        $this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG );
190
-        
191
-        //TODO enable this again when API queries are all done :
192
-        if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
193
-        
194
-        // IDO Database
195
-        if (!array_key_exists('IDOdatabase',$trapConfig['config']))
196
-        {
197
-            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
198
-        }
199
-        $dbIdoName=$trapConfig['config']['IDOdatabase'];
200
-        
201
-        $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
202
-        if (!array_key_exists($dbIdoName,$dbConfig))
203
-        {
204
-            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
205
-            return;
206
-        }
207
-        
208
-        $this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
209
-    }
161
+	/**
162
+	 * Create and setup database class for trap & ido (if no api) db
163
+	 * @param array $trap_config : ini file array
164
+	 */
165
+	protected function setupDatabase($trapConfig)
166
+	{
167
+		// Trap database
168
+		if (!array_key_exists('database',$trapConfig['config']))
169
+		{
170
+			$this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
171
+			return;
172
+		}
173
+		$dbTrapName=$trapConfig['config']['database'];
174
+		$this->logging->log("Found database in config file: ".$dbTrapName,INFO );
175
+        
176
+		if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
177
+		{
178
+			$this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
179
+			return;
180
+		}
181
+		if (!array_key_exists($dbTrapName,$dbConfig))
182
+		{
183
+			$this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
184
+			return;
185
+		}
186
+        
187
+		$this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
188
+        
189
+		$this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG );
190
+        
191
+		//TODO enable this again when API queries are all done :
192
+		if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
193
+        
194
+		// IDO Database
195
+		if (!array_key_exists('IDOdatabase',$trapConfig['config']))
196
+		{
197
+			$this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
198
+		}
199
+		$dbIdoName=$trapConfig['config']['IDOdatabase'];
200
+        
201
+		$this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
202
+		if (!array_key_exists($dbIdoName,$dbConfig))
203
+		{
204
+			$this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
205
+			return;
206
+		}
207
+        
208
+		$this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
209
+	}
210 210
     
211 211
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -36,15 +36,15 @@  discard block
 block discarded – undo
36 36
      * @param string $message warning message if not found
37 37
      * @return boolean true if found, or false
38 38
      */
39
-    protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = WARN, $message = null)
39
+    protected function getOptionIfSet($option_array, $option_category, $option_name, &$option_var, $log_level=WARN, $message=null)
40 40
     {
41 41
         if (!isset($option_array[$option_category][$option_name]))
42 42
         {
43 43
             if ($message === null)
44 44
             {
45
-                $message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
45
+                $message='No '.$option_name.' in config file: '.$this->trapModuleConfig;
46 46
             }
47
-            $this->getLogging()->log($message,$log_level);
47
+            $this->getLogging()->log($message, $log_level);
48 48
             return false;
49 49
         }
50 50
         else
@@ -62,24 +62,24 @@  discard block
 block discarded – undo
62 62
         // Database options
63 63
         if ($this->logSetup === false) // Only if logging was no setup in constructor
64 64
         {
65
-            $this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
66
-            $this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
67
-            $this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
65
+            $this->getDBConfigIfSet('log_level', $this->getLogging()->debugLevel);
66
+            $this->getDBConfigIfSet('log_destination', $this->getLogging()->outputMode);
67
+            $this->getDBConfigIfSet('log_file', $this->getLogging()->outputFile);
68 68
         }
69 69
         
70
-        $tmpVal = -1; // Get boolean coded in database as 1/0
70
+        $tmpVal=-1; // Get boolean coded in database as 1/0
71 71
         $this->getDBConfigIfSet('use_SnmpTrapAddess', $tmpVal);
72
-        if ($tmpVal != -1) $this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
72
+        if ($tmpVal != -1) $this->useSnmpTrapAddess=($tmpVal == 1) ? TRUE : FALSE;
73 73
         
74 74
         $this->getDBConfigIfSet('SnmpTrapAddess_oid', $this->snmpTrapAddressOID); // Get oid then replace '.' with '\.' to use in regexp whrn reading traps
75
-        $this->snmpTrapAddressOID = preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
75
+        $this->snmpTrapAddressOID=preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
76 76
     }
77 77
         
78 78
     /** Set $variable to value if $element found in database config table
79 79
      * @param string $element
80 80
      * @param string $variable
81 81
      */
82
-    protected function getDBConfigIfSet($element,&$variable)
82
+    protected function getDBConfigIfSet($element, &$variable)
83 83
     {
84 84
         $value=$this->getDBConfig($element);
85 85
         if ($value != null) $variable=$value;
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
         $db_conn=$this->trapsDB->db_connect_trap();
96 96
         $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
97 97
         if (($ret_code=$db_conn->query($sql)) === false) {
98
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
98
+            $this->logging->log('No result in query : '.$sql, WARN, '');
99 99
             return null;
100 100
         }
101 101
         $value=$ret_code->fetch();
@@ -114,10 +114,10 @@  discard block
 block discarded – undo
114 114
     {
115 115
         
116 116
         $nodeStatus='';
117
-        $this->getOptionIfSet($trapConfig,'config','node', $nodeStatus);
117
+        $this->getOptionIfSet($trapConfig, 'config', 'node', $nodeStatus);
118 118
         if ($this->getTrapApi()->setStatus($nodeStatus) === FALSE)
119 119
         {
120
-            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
120
+            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER', WARN);
121 121
             $this->getTrapApi()->setStatusMaster();
122 122
         }
123 123
         else 
@@ -125,36 +125,36 @@  discard block
 block discarded – undo
125 125
             if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
126 126
             {
127 127
                 // Get options to connect to API
128
-                $IP = $port = $user =  $pass = null;
129
-                $this->getOptionIfSet($trapConfig,'config','masterIP', $IP, ERROR);
130
-                $this->getOptionIfSet($trapConfig,'config','masterPort', $port, ERROR);
131
-                $this->getOptionIfSet($trapConfig,'config','masterUser', $user, ERROR);
132
-                $this->getOptionIfSet($trapConfig,'config','masterPass', $pass, ERROR);
128
+                $IP=$port=$user=$pass=null;
129
+                $this->getOptionIfSet($trapConfig, 'config', 'masterIP', $IP, ERROR);
130
+                $this->getOptionIfSet($trapConfig, 'config', 'masterPort', $port, ERROR);
131
+                $this->getOptionIfSet($trapConfig, 'config', 'masterUser', $user, ERROR);
132
+                $this->getOptionIfSet($trapConfig, 'config', 'masterPass', $pass, ERROR);
133 133
                 $this->getTrapApi()->setParams($IP, $port, $user, $pass);
134 134
                 return;
135 135
             }
136 136
         }
137 137
         
138 138
         // Snmptranslate binary path
139
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
139
+        $this->getOptionIfSet($trapConfig, 'config', 'snmptranslate', $this->snmptranslate);
140 140
         
141 141
         // mibs path
142
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
142
+        $this->getOptionIfSet($trapConfig, 'config', 'snmptranslate_dirs', $this->snmptranslate_dirs);
143 143
         
144 144
         // icinga2cmd path
145
-        $this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
145
+        $this->getOptionIfSet($trapConfig, 'config', 'icingacmd', $this->icinga2cmd);
146 146
         
147 147
         // table prefix
148
-        $this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
148
+        $this->getOptionIfSet($trapConfig, 'config', 'database_prefix', $this->dbPrefix);
149 149
         
150 150
         // API options
151
-        if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
151
+        if ($this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_host', $this->apiHostname))
152 152
         {
153 153
             $this->apiUse=true;
154 154
             // Get API options or throw exception as not configured correctly
155
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort,ERROR);
156
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername,ERROR);
157
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword,ERROR);
155
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_port', $this->apiPort, ERROR);
156
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_user', $this->apiUsername, ERROR);
157
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_password', $this->apiPassword, ERROR);
158 158
         }
159 159
     }
160 160
     
@@ -165,43 +165,43 @@  discard block
 block discarded – undo
165 165
     protected function setupDatabase($trapConfig)
166 166
     {
167 167
         // Trap database
168
-        if (!array_key_exists('database',$trapConfig['config']))
168
+        if (!array_key_exists('database', $trapConfig['config']))
169 169
         {
170
-            $this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
170
+            $this->logging->log("No database in config file: ".$this->trapModuleConfig, ERROR, '');
171 171
             return;
172 172
         }
173 173
         $dbTrapName=$trapConfig['config']['database'];
174
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
174
+        $this->logging->log("Found database in config file: ".$dbTrapName, INFO);
175 175
         
176
-        if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
176
+        if (($dbConfig=parse_ini_file($this->icingaweb2Ressources, true)) === false)
177 177
         {
178
-            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
178
+            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources, ERROR, '');
179 179
             return;
180 180
         }
181
-        if (!array_key_exists($dbTrapName,$dbConfig))
181
+        if (!array_key_exists($dbTrapName, $dbConfig))
182 182
         {
183
-            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
183
+            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources, ERROR, '');
184 184
             return;
185 185
         }
186 186
         
187
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
187
+        $this->trapsDB=new Database($this->logging, $dbConfig[$dbTrapName], $this->dbPrefix);
188 188
         
189
-        $this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG );
189
+        $this->logging->log("API Use : ".print_r($this->apiUse, true), DEBUG);
190 190
         
191 191
         //TODO enable this again when API queries are all done :
192 192
         if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
193 193
         
194 194
         // IDO Database
195
-        if (!array_key_exists('IDOdatabase',$trapConfig['config']))
195
+        if (!array_key_exists('IDOdatabase', $trapConfig['config']))
196 196
         {
197
-            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
197
+            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig, ERROR, '');
198 198
         }
199 199
         $dbIdoName=$trapConfig['config']['IDOdatabase'];
200 200
         
201
-        $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
202
-        if (!array_key_exists($dbIdoName,$dbConfig))
201
+        $this->logging->log("Found IDO database in config file: ".$dbIdoName, INFO);
202
+        if (!array_key_exists($dbIdoName, $dbConfig))
203 203
         {
204
-            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
204
+            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources, ERROR, '');
205 205
             return;
206 206
         }
207 207
         
Please login to merge, or discard this patch.
Braces   +15 added lines, -8 removed lines patch added patch discarded remove patch
@@ -46,8 +46,7 @@  discard block
 block discarded – undo
46 46
             }
47 47
             $this->getLogging()->log($message,$log_level);
48 48
             return false;
49
-        }
50
-        else
49
+        } else
51 50
         {
52 51
             $option_var=$option_array[$option_category][$option_name];
53 52
             return true;
@@ -60,16 +59,20 @@  discard block
 block discarded – undo
60 59
     protected function getDatabaseOptions()
61 60
     {
62 61
         // Database options
63
-        if ($this->logSetup === false) // Only if logging was no setup in constructor
62
+        if ($this->logSetup === false) {
63
+        	// Only if logging was no setup in constructor
64 64
         {
65 65
             $this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
66
+        }
66 67
             $this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
67 68
             $this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
68 69
         }
69 70
         
70 71
         $tmpVal = -1; // Get boolean coded in database as 1/0
71 72
         $this->getDBConfigIfSet('use_SnmpTrapAddess', $tmpVal);
72
-        if ($tmpVal != -1) $this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
73
+        if ($tmpVal != -1) {
74
+        	$this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
75
+        }
73 76
         
74 77
         $this->getDBConfigIfSet('SnmpTrapAddess_oid', $this->snmpTrapAddressOID); // Get oid then replace '.' with '\.' to use in regexp whrn reading traps
75 78
         $this->snmpTrapAddressOID = preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
@@ -82,7 +85,9 @@  discard block
 block discarded – undo
82 85
     protected function getDBConfigIfSet($element,&$variable)
83 86
     {
84 87
         $value=$this->getDBConfig($element);
85
-        if ($value != null) $variable=$value;
88
+        if ($value != null) {
89
+        	$variable=$value;
90
+        }
86 91
     }
87 92
     
88 93
     /**
@@ -119,8 +124,7 @@  discard block
 block discarded – undo
119 124
         {
120 125
             $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
121 126
             $this->getTrapApi()->setStatusMaster();
122
-        }
123
-        else 
127
+        } else 
124 128
         {
125 129
             if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
126 130
             {
@@ -189,7 +193,10 @@  discard block
 block discarded – undo
189 193
         $this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG );
190 194
         
191 195
         //TODO enable this again when API queries are all done :
192
-        if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
196
+        if ($this->apiUse === true) {
197
+        	return;
198
+        }
199
+        // In case of API use, no IDO is necessary
193 200
         
194 201
         // IDO Database
195 202
         if (!array_key_exists('IDOdatabase',$trapConfig['config']))
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Trap.php 3 patches
Indentation   +836 added lines, -836 removed lines patch added patch discarded remove patch
@@ -17,855 +17,855 @@  discard block
 block discarded – undo
17 17
  */
18 18
 class Trap
19 19
 {
20
-    use TrapConfig;
20
+	use TrapConfig;
21 21
     
22
-    // Configuration files and dirs
23
-    /** @var string Icinga etc path */
24
-    protected $icingaweb2Etc;
25
-    /** @var string $trapModuleConfig config.ini of module */
26
-    protected $trapModuleConfig;
27
-    /** @var string $icingaweb2Ressources resources.ini of icingaweb2 */
28
-    protected $icingaweb2Ressources;
29
-    // Options from config.ini (default values)
30
-    /** @var string $snmptranslate */
31
-    protected $snmptranslate='/usr/bin/snmptranslate';
32
-    /** @var string $snmptranslate_dirs */
33
-    protected $snmptranslate_dirs='/usr/share/icingaweb2/modules/trapdirector/mibs';
34
-    /** @var string $icinga2cmd */
35
-    protected $icinga2cmd='/var/run/icinga2/cmd/icinga2.cmd';
36
-    /** @var string $dbPrefix */
37
-    protected $dbPrefix='traps_';
22
+	// Configuration files and dirs
23
+	/** @var string Icinga etc path */
24
+	protected $icingaweb2Etc;
25
+	/** @var string $trapModuleConfig config.ini of module */
26
+	protected $trapModuleConfig;
27
+	/** @var string $icingaweb2Ressources resources.ini of icingaweb2 */
28
+	protected $icingaweb2Ressources;
29
+	// Options from config.ini (default values)
30
+	/** @var string $snmptranslate */
31
+	protected $snmptranslate='/usr/bin/snmptranslate';
32
+	/** @var string $snmptranslate_dirs */
33
+	protected $snmptranslate_dirs='/usr/share/icingaweb2/modules/trapdirector/mibs';
34
+	/** @var string $icinga2cmd */
35
+	protected $icinga2cmd='/var/run/icinga2/cmd/icinga2.cmd';
36
+	/** @var string $dbPrefix */
37
+	protected $dbPrefix='traps_';
38 38
     
39
-    // API
40
-    /** @var boolean $apiUse */
41
-    protected $apiUse=false;
42
-    /** @var Icinga2API $icinga2api */
43
-    protected $icinga2api=null;
44
-    /** @var string $apiHostname */
45
-    protected $apiHostname='';
46
-    /** @var integer $apiPort */
47
-    protected $apiPort=0;
48
-    /** @var string $apiUsername */
49
-    protected $apiUsername='';
50
-    /** @var string $apiPassword */
51
-    protected $apiPassword='';
39
+	// API
40
+	/** @var boolean $apiUse */
41
+	protected $apiUse=false;
42
+	/** @var Icinga2API $icinga2api */
43
+	protected $icinga2api=null;
44
+	/** @var string $apiHostname */
45
+	protected $apiHostname='';
46
+	/** @var integer $apiPort */
47
+	protected $apiPort=0;
48
+	/** @var string $apiUsername */
49
+	protected $apiUsername='';
50
+	/** @var string $apiPassword */
51
+	protected $apiPassword='';
52 52
     
53
-    // Logs
54
-    /** @var Logging Logging class. */
55
-    public $logging;    //< Logging class.
56
-    /** @var bool true if log was setup in constructor */
57
-    protected $logSetup;   //< bool true if log was setup in constructor
53
+	// Logs
54
+	/** @var Logging Logging class. */
55
+	public $logging;    //< Logging class.
56
+	/** @var bool true if log was setup in constructor */
57
+	protected $logSetup;   //< bool true if log was setup in constructor
58 58
     
59
-    // Databases
60
-    /** @var Database $trapsDB  Database class*/
61
-    public $trapsDB = null;
59
+	// Databases
60
+	/** @var Database $trapsDB  Database class*/
61
+	public $trapsDB = null;
62 62
     
63
-    // Trap received data
64
-    protected $receivingHost;
65
-    /** @var array	Main trap data (oid, source...) */
66
-    public $trapData=array();
67
-    /** @var array $trapDataExt Additional trap data objects (oid/value).*/
68
-    public $trapDataExt=array(); 
69
-    /** @var int $trapId trap_id after sql insert*/
70
-    public $trapId=null;
71
-    /** @var string $trapAction trap action for final write*/
72
-    public $trapAction=null;
73
-    /** @var boolean $trapToDb log trap to DB */
74
-    protected $trapToDb=true;
63
+	// Trap received data
64
+	protected $receivingHost;
65
+	/** @var array	Main trap data (oid, source...) */
66
+	public $trapData=array();
67
+	/** @var array $trapDataExt Additional trap data objects (oid/value).*/
68
+	public $trapDataExt=array(); 
69
+	/** @var int $trapId trap_id after sql insert*/
70
+	public $trapId=null;
71
+	/** @var string $trapAction trap action for final write*/
72
+	public $trapAction=null;
73
+	/** @var boolean $trapToDb log trap to DB */
74
+	protected $trapToDb=true;
75 75
     
76
-    /** @var Mib mib class */
77
-    public $mibClass = null;
76
+	/** @var Mib mib class */
77
+	public $mibClass = null;
78 78
     
79
-    /** @var Rule rule class */
80
-    public $ruleClass = null;
79
+	/** @var Rule rule class */
80
+	public $ruleClass = null;
81 81
     
82
-    /** @var Plugins plugins manager **/
83
-    public $pluginClass = null;
82
+	/** @var Plugins plugins manager **/
83
+	public $pluginClass = null;
84 84
     
85
-    /** @var TrapApi $trapApiClass */
86
-    public $trapApiClass = null;
85
+	/** @var TrapApi $trapApiClass */
86
+	public $trapApiClass = null;
87 87
     
88
-    function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
89
-    {
90
-        // Paths of ini files
91
-        $this->icingaweb2Etc=$etcDir;
92
-        $this->trapModuleConfig=$this->icingaweb2Etc."/modules/trapdirector/config.ini";
93
-        $this->icingaweb2Ressources=$this->icingaweb2Etc."/resources.ini";
88
+	function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
89
+	{
90
+		// Paths of ini files
91
+		$this->icingaweb2Etc=$etcDir;
92
+		$this->trapModuleConfig=$this->icingaweb2Etc."/modules/trapdirector/config.ini";
93
+		$this->icingaweb2Ressources=$this->icingaweb2Etc."/resources.ini";
94 94
 
95
-        // Setup logging
96
-        $this->logging = new Logging();
97
-        if ($baseLogLevel != null)
98
-        {
99
-            $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
100
-            $this->logSetup=true;
101
-        }
102
-        else
103
-        {
104
-            $this->logSetup=false;
105
-        }
106
-        $this->logging->log('Loggin started', INFO);
107
-        
108
-        
109
-        // Create distributed API object
110
-        
111
-        $this->trapApiClass = new TrapApi($this->logging);
112
-        
113
-        // Get options from ini files
114
-        if (! is_file($this->trapModuleConfig))
115
-        {
116
-            throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
117
-        }
118
-        $trapConfig=parse_ini_file($this->trapModuleConfig,true);
119
-        if ($trapConfig == false)
120
-        {
121
-            $this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
122
-            throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
123
-        }
124
-        $this->getMainOptions($trapConfig); // Get main options from ini file
125
-        
126
-        // Setup database class & get options
127
-        $this->setupDatabase($trapConfig);
128
-        
129
-        $this->getDatabaseOptions(); // Get options in database
130
-        
131
-        // Setup API
132
-        if ($this->apiUse === true) $this->getAPI(); // Setup API
133
-        
134
-        // Setup MIB
135
-        $this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
136
-        
137
-        // Setup Rule
138
-        $this->ruleClass = new Rule($this); //< Create Rule class
139
-        
140
-        $this->trapData=array(  // TODO : put this in a reset function (DAEMON_MODE)
141
-            'source_ip'	=> 'unknown',
142
-            'source_port'	=> 'unknown',
143
-            'destination_ip'	=> 'unknown',
144
-            'destination_port'	=> 'unknown',
145
-            'trap_oid'	=> 'unknown'
146
-        );
147
-        
148
-        // Setup Plugins
149
-        //Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
150
-        $this->pluginClass = new Plugins($this);
95
+		// Setup logging
96
+		$this->logging = new Logging();
97
+		if ($baseLogLevel != null)
98
+		{
99
+			$this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
100
+			$this->logSetup=true;
101
+		}
102
+		else
103
+		{
104
+			$this->logSetup=false;
105
+		}
106
+		$this->logging->log('Loggin started', INFO);
107
+        
108
+        
109
+		// Create distributed API object
110
+        
111
+		$this->trapApiClass = new TrapApi($this->logging);
112
+        
113
+		// Get options from ini files
114
+		if (! is_file($this->trapModuleConfig))
115
+		{
116
+			throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
117
+		}
118
+		$trapConfig=parse_ini_file($this->trapModuleConfig,true);
119
+		if ($trapConfig == false)
120
+		{
121
+			$this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
122
+			throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
123
+		}
124
+		$this->getMainOptions($trapConfig); // Get main options from ini file
125
+        
126
+		// Setup database class & get options
127
+		$this->setupDatabase($trapConfig);
128
+        
129
+		$this->getDatabaseOptions(); // Get options in database
130
+        
131
+		// Setup API
132
+		if ($this->apiUse === true) $this->getAPI(); // Setup API
133
+        
134
+		// Setup MIB
135
+		$this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
136
+        
137
+		// Setup Rule
138
+		$this->ruleClass = new Rule($this); //< Create Rule class
139
+        
140
+		$this->trapData=array(  // TODO : put this in a reset function (DAEMON_MODE)
141
+			'source_ip'	=> 'unknown',
142
+			'source_port'	=> 'unknown',
143
+			'destination_ip'	=> 'unknown',
144
+			'destination_port'	=> 'unknown',
145
+			'trap_oid'	=> 'unknown'
146
+		);
147
+        
148
+		// Setup Plugins
149
+		//Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
150
+		$this->pluginClass = new Plugins($this);
151 151
             
152 152
             
153
-    }
153
+	}
154 154
 
155
-    /** @return \Trapdirector\Logging   */
156
-    public function getLogging()
157
-    {
158
-        return $this->logging;
159
-    }
155
+	/** @return \Trapdirector\Logging   */
156
+	public function getLogging()
157
+	{
158
+		return $this->logging;
159
+	}
160 160
 
161
-    /** @return \Trapdirector\TrapApi   */
162
-    public function getTrapApi()
163
-    {
164
-        return $this->trapApiClass;
165
-    }
161
+	/** @return \Trapdirector\TrapApi   */
162
+	public function getTrapApi()
163
+	{
164
+		return $this->trapApiClass;
165
+	}
166 166
     
167
-    /** @return \Trapdirector\Database */
168
-    public function getTrapsDB()
169
-    {
170
-        return $this->trapsDB;
171
-    }
167
+	/** @return \Trapdirector\Database */
168
+	public function getTrapsDB()
169
+	{
170
+		return $this->trapsDB;
171
+	}
172 172
     
173
-    /** OBSOLETE Send log. Throws exception on critical error
174
-     *	@param	string $message Message to log
175
-     *	@param	int $level 1=critical 2=warning 3=trace 4=debug
176
-     *	@param  string $destination file/syslog/display
177
-     *	@return void
178
-     **/
179
-    public function trapLog( $message, $level, $destination ='') // OBSOLETE
180
-    {
181
-        // TODO : replace ref with $this->logging->log
182
-        $this->logging->log($message, $level, $destination);
183
-    }
173
+	/** OBSOLETE Send log. Throws exception on critical error
174
+	 *	@param	string $message Message to log
175
+	 *	@param	int $level 1=critical 2=warning 3=trace 4=debug
176
+	 *	@param  string $destination file/syslog/display
177
+	 *	@return void
178
+	 **/
179
+	public function trapLog( $message, $level, $destination ='') // OBSOLETE
180
+	{
181
+		// TODO : replace ref with $this->logging->log
182
+		$this->logging->log($message, $level, $destination);
183
+	}
184 184
     
185
-    public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
186
-    {
187
-        $this->logging->setLogging($debugLvl, $outputType,$outputOption);
188
-    }
185
+	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
186
+	{
187
+		$this->logging->setLogging($debugLvl, $outputType,$outputOption);
188
+	}
189 189
     
190
-    /**
191
-     * Returns or create new IcingaAPI object
192
-     * @return \Icinga\Module\Trapdirector\Icinga2API
193
-     */
194
-    protected function getAPI()
195
-    {
196
-        if ($this->icinga2api == null)
197
-        {
198
-            $this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
199
-        }
200
-        return $this->icinga2api;
201
-    }
190
+	/**
191
+	 * Returns or create new IcingaAPI object
192
+	 * @return \Icinga\Module\Trapdirector\Icinga2API
193
+	 */
194
+	protected function getAPI()
195
+	{
196
+		if ($this->icinga2api == null)
197
+		{
198
+			$this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
199
+		}
200
+		return $this->icinga2api;
201
+	}
202 202
     
203 203
     
204
-    /**
205
-     * read data from stream
206
-     *	@param $stream string input stream, defaults to "php://stdin"
207
-     *	@return mixed array trap data or exception with error
208
-     */
209
-    public function read_trap($stream='php://stdin')
210
-    {
211
-        //Read data from snmptrapd from stdin
212
-        $input_stream=fopen($stream, 'r');
213
-        
214
-        if ($input_stream === false)
215
-        {
216
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
217
-            $this->logging->log("Error reading stdin !",ERROR,'');
218
-            return null; // note : exception thrown by logging
219
-        }
220
-        
221
-        // line 1 : host
222
-        $this->receivingHost=chop(fgets($input_stream));
223
-        if ($this->receivingHost === false)
224
-        {
225
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
226
-            $this->logging->log("Error reading Host !",ERROR,'');
227
-        }
228
-        // line 2 IP:port=>IP:port
229
-        $IP=chop(fgets($input_stream));
230
-        if ($IP === false)
231
-        {
232
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
233
-            $this->logging->log("Error reading IP !",ERROR,'');
234
-        }
235
-        $matches=array();
236
-        $ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
237
-        if ($ret_code===0 || $ret_code===false)
238
-        {
239
-            $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
240
-            $this->logging->log('Error parsing IP : '.$IP,ERROR,'');
241
-        }
242
-        else
243
-        {
244
-            $this->trapData['source_ip']=$matches[1];
245
-            $this->trapData['destination_ip']=$matches[3];
246
-            $this->trapData['source_port']=$matches[2];
247
-            $this->trapData['destination_port']=$matches[4];
248
-        }
249
-        
250
-        while (($vars=fgets($input_stream)) !==false)
251
-        {
252
-            $vars=chop($vars);
253
-            $ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
254
-            if ($ret_code===0 || $ret_code===false)
255
-            {
256
-                $this->logging->log('No match on trap data : '.$vars,WARN,'');
257
-                continue;
258
-            }
259
-            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'))
260
-            {
261
-                $this->trapData['trap_oid']=$matches[2];
262
-                continue;
263
-            }
264
-            if ( $this->useSnmpTrapAddess === TRUE &&  preg_match('/'.$this->snmpTrapAddressOID.'/', $matches[1]) == 1)
265
-            {
266
-                $this->logging->log('Found relayed trap from ' . $matches[2] . ' relayed by ' .$this->trapData['source_ip'],DEBUG);
267
-                if (preg_match('/^[0-9\.]+$/',$matches[2]) == 0 && preg_match('/^[0-9a-fA-F:]+$/',$matches[2]) == 0)
268
-                {
269
-                    $this->logging->log('Value of SnmpTrapAddess ('.$this->snmpTrapAddressOID.') is not IP : ' .$matches[2],WARN,'');
270
-                    continue;
271
-                }
272
-                $this->trapData['source_ip'] = $matches[2];
273
-                continue;
274
-            }
275
-            $object= new stdClass;
276
-            $object->oid =$matches[1];
277
-            $object->value = $matches[2];
278
-            array_push($this->trapDataExt,$object);
279
-        }
280
-        
281
-        if ($this->trapData['trap_oid']=='unknown')
282
-        {
283
-            $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trapData['source_ip']);
284
-            $this->logging->log('no trap oid found',ERROR,'');
285
-        }
286
-        
287
-        // Translate oids.
288
-        
289
-        $retArray=$this->translateOID($this->trapData['trap_oid']);
290
-        if ($retArray != null)
291
-        {
292
-            $this->trapData['trap_name']=$retArray['trap_name'];
293
-            $this->trapData['trap_name_mib']=$retArray['trap_name_mib'];
294
-        }
295
-        foreach ($this->trapDataExt as $key => $val)
296
-        {
297
-            $retArray=$this->translateOID($val->oid);
298
-            if ($retArray != null)
299
-            {
300
-                $this->trapDataExt[$key]->oid_name=$retArray['trap_name'];
301
-                $this->trapDataExt[$key]->oid_name_mib=$retArray['trap_name_mib'];
302
-            }
303
-        }
304
-        
305
-        
306
-        $this->trapData['status']= 'waiting';
307
-        
308
-        return $this->trapData;
309
-    }
204
+	/**
205
+	 * read data from stream
206
+	 *	@param $stream string input stream, defaults to "php://stdin"
207
+	 *	@return mixed array trap data or exception with error
208
+	 */
209
+	public function read_trap($stream='php://stdin')
210
+	{
211
+		//Read data from snmptrapd from stdin
212
+		$input_stream=fopen($stream, 'r');
213
+        
214
+		if ($input_stream === false)
215
+		{
216
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
217
+			$this->logging->log("Error reading stdin !",ERROR,'');
218
+			return null; // note : exception thrown by logging
219
+		}
220
+        
221
+		// line 1 : host
222
+		$this->receivingHost=chop(fgets($input_stream));
223
+		if ($this->receivingHost === false)
224
+		{
225
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
226
+			$this->logging->log("Error reading Host !",ERROR,'');
227
+		}
228
+		// line 2 IP:port=>IP:port
229
+		$IP=chop(fgets($input_stream));
230
+		if ($IP === false)
231
+		{
232
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
233
+			$this->logging->log("Error reading IP !",ERROR,'');
234
+		}
235
+		$matches=array();
236
+		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
237
+		if ($ret_code===0 || $ret_code===false)
238
+		{
239
+			$this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
240
+			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
241
+		}
242
+		else
243
+		{
244
+			$this->trapData['source_ip']=$matches[1];
245
+			$this->trapData['destination_ip']=$matches[3];
246
+			$this->trapData['source_port']=$matches[2];
247
+			$this->trapData['destination_port']=$matches[4];
248
+		}
249
+        
250
+		while (($vars=fgets($input_stream)) !==false)
251
+		{
252
+			$vars=chop($vars);
253
+			$ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
254
+			if ($ret_code===0 || $ret_code===false)
255
+			{
256
+				$this->logging->log('No match on trap data : '.$vars,WARN,'');
257
+				continue;
258
+			}
259
+			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'))
260
+			{
261
+				$this->trapData['trap_oid']=$matches[2];
262
+				continue;
263
+			}
264
+			if ( $this->useSnmpTrapAddess === TRUE &&  preg_match('/'.$this->snmpTrapAddressOID.'/', $matches[1]) == 1)
265
+			{
266
+				$this->logging->log('Found relayed trap from ' . $matches[2] . ' relayed by ' .$this->trapData['source_ip'],DEBUG);
267
+				if (preg_match('/^[0-9\.]+$/',$matches[2]) == 0 && preg_match('/^[0-9a-fA-F:]+$/',$matches[2]) == 0)
268
+				{
269
+					$this->logging->log('Value of SnmpTrapAddess ('.$this->snmpTrapAddressOID.') is not IP : ' .$matches[2],WARN,'');
270
+					continue;
271
+				}
272
+				$this->trapData['source_ip'] = $matches[2];
273
+				continue;
274
+			}
275
+			$object= new stdClass;
276
+			$object->oid =$matches[1];
277
+			$object->value = $matches[2];
278
+			array_push($this->trapDataExt,$object);
279
+		}
280
+        
281
+		if ($this->trapData['trap_oid']=='unknown')
282
+		{
283
+			$this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trapData['source_ip']);
284
+			$this->logging->log('no trap oid found',ERROR,'');
285
+		}
286
+        
287
+		// Translate oids.
288
+        
289
+		$retArray=$this->translateOID($this->trapData['trap_oid']);
290
+		if ($retArray != null)
291
+		{
292
+			$this->trapData['trap_name']=$retArray['trap_name'];
293
+			$this->trapData['trap_name_mib']=$retArray['trap_name_mib'];
294
+		}
295
+		foreach ($this->trapDataExt as $key => $val)
296
+		{
297
+			$retArray=$this->translateOID($val->oid);
298
+			if ($retArray != null)
299
+			{
300
+				$this->trapDataExt[$key]->oid_name=$retArray['trap_name'];
301
+				$this->trapDataExt[$key]->oid_name_mib=$retArray['trap_name_mib'];
302
+			}
303
+		}
304
+        
305
+        
306
+		$this->trapData['status']= 'waiting';
307
+        
308
+		return $this->trapData;
309
+	}
310 310
     
311
-    /**
312
-     * Translate oid into array(MIB,Name)
313
-     * @param $oid string oid to translate
314
-     * @return mixed : null if not found or array(MIB,Name)
315
-     */
316
-    public function translateOID($oid)
317
-    {
318
-        // try from database
319
-        $db_conn=$this->trapsDB->db_connect_trap();
320
-        
321
-        $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
322
-        $this->logging->log('SQL query : '.$sql,DEBUG );
323
-        if (($ret_code=$db_conn->query($sql)) === false) {
324
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
325
-        }
326
-        else {
327
-            if (($name=$ret_code->fetch()) !== false)
328
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
329
-        }
330
-        
331
-        // Also check if it is an instance of OID
332
-        $oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
333
-        
334
-        $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
335
-        $this->logging->log('SQL query : '.$sql,DEBUG );
336
-        if (($ret_code=$db_conn->query($sql)) === false) {
337
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
338
-        }
339
-        else {
340
-            if (($name=$ret_code->fetch()) !== false)
341
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
342
-        }
343
-        
344
-        // Try to get oid name from snmptranslate
345
-        $translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
346
-            ' '.$oid);
347
-        $matches=array();
348
-        $ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
349
-        if ($ret_code===0 || $ret_code === false) {
350
-            return NULL;
351
-        } else {
352
-            $this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
353
-            return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
354
-        }
355
-    }
311
+	/**
312
+	 * Translate oid into array(MIB,Name)
313
+	 * @param $oid string oid to translate
314
+	 * @return mixed : null if not found or array(MIB,Name)
315
+	 */
316
+	public function translateOID($oid)
317
+	{
318
+		// try from database
319
+		$db_conn=$this->trapsDB->db_connect_trap();
320
+        
321
+		$sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
322
+		$this->logging->log('SQL query : '.$sql,DEBUG );
323
+		if (($ret_code=$db_conn->query($sql)) === false) {
324
+			$this->logging->log('No result in query : ' . $sql,ERROR,'');
325
+		}
326
+		else {
327
+			if (($name=$ret_code->fetch()) !== false)
328
+				return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
329
+		}
330
+        
331
+		// Also check if it is an instance of OID
332
+		$oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
333
+        
334
+		$sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
335
+		$this->logging->log('SQL query : '.$sql,DEBUG );
336
+		if (($ret_code=$db_conn->query($sql)) === false) {
337
+			$this->logging->log('No result in query : ' . $sql,ERROR,'');
338
+		}
339
+		else {
340
+			if (($name=$ret_code->fetch()) !== false)
341
+				return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
342
+		}
343
+        
344
+		// Try to get oid name from snmptranslate
345
+		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
346
+			' '.$oid);
347
+		$matches=array();
348
+		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
349
+		if ($ret_code===0 || $ret_code === false) {
350
+			return NULL;
351
+		} else {
352
+			$this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
353
+			return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
354
+		}
355
+	}
356 356
     
357
-    /**
358
-     * Erase old trap records
359
-     *	@param integer $days : erase traps when more than $days old
360
-     *	@return integer : number of lines deleted
361
-     **/
362
-    public function eraseOldTraps($days=0)
363
-    {
364
-        if ($days==0)
365
-        {
366
-            if (($days=$this->getDBConfig('db_remove_days')) == null)
367
-            {
368
-                $this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
369
-                return;
370
-            }
371
-        }
372
-        $db_conn=$this->trapsDB->db_connect_trap();
373
-        $daysago = strtotime("-".$days." day");
374
-        $sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
375
-        if ($db_conn->query($sql) === false) {
376
-            $this->logging->log('Error erasing traps : '.$sql,ERROR,'');
377
-        }
378
-        $this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
379
-    }
357
+	/**
358
+	 * Erase old trap records
359
+	 *	@param integer $days : erase traps when more than $days old
360
+	 *	@return integer : number of lines deleted
361
+	 **/
362
+	public function eraseOldTraps($days=0)
363
+	{
364
+		if ($days==0)
365
+		{
366
+			if (($days=$this->getDBConfig('db_remove_days')) == null)
367
+			{
368
+				$this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
369
+				return;
370
+			}
371
+		}
372
+		$db_conn=$this->trapsDB->db_connect_trap();
373
+		$daysago = strtotime("-".$days." day");
374
+		$sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
375
+		if ($db_conn->query($sql) === false) {
376
+			$this->logging->log('Error erasing traps : '.$sql,ERROR,'');
377
+		}
378
+		$this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
379
+	}
380 380
     
381
-    /** Write error to received trap database
382
-     */
383
-    public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
384
-    {
385
-        
386
-        $db_conn=$this->trapsDB->db_connect_trap();
387
-        
388
-        // add date time
389
-        $insert_col ='date_received,status';
390
-        $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
391
-        
392
-        if ($sourceIP !=null)
393
-        {
394
-            $insert_col .=',source_ip';
395
-            $insert_val .=",'". $sourceIP ."'";
396
-        }
397
-        if ($trapoid !=null)
398
-        {
399
-            $insert_col .=',trap_oid';
400
-            $insert_val .=",'". $trapoid ."'";
401
-        }
402
-        $insert_col .=',status_detail';
403
-        $insert_val .=",'". $message ."'";
404
-        
405
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
406
-        
407
-        switch ($this->trapsDB->trapDBType)
408
-        {
409
-            case 'pgsql':
410
-                $sql .= ' RETURNING id;';
411
-                $this->logging->log('sql : '.$sql,INFO);
412
-                if (($ret_code=$db_conn->query($sql)) === false) {
413
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
414
-                }
415
-                $this->logging->log('SQL insertion OK',INFO );
416
-                // Get last id to insert oid/values in secondary table
417
-                if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
381
+	/** Write error to received trap database
382
+	 */
383
+	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
384
+	{
385
+        
386
+		$db_conn=$this->trapsDB->db_connect_trap();
387
+        
388
+		// add date time
389
+		$insert_col ='date_received,status';
390
+		$insert_val = "'" . date("Y-m-d H:i:s")."','error'";
391
+        
392
+		if ($sourceIP !=null)
393
+		{
394
+			$insert_col .=',source_ip';
395
+			$insert_val .=",'". $sourceIP ."'";
396
+		}
397
+		if ($trapoid !=null)
398
+		{
399
+			$insert_col .=',trap_oid';
400
+			$insert_val .=",'". $trapoid ."'";
401
+		}
402
+		$insert_col .=',status_detail';
403
+		$insert_val .=",'". $message ."'";
404
+        
405
+		$sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
406
+        
407
+		switch ($this->trapsDB->trapDBType)
408
+		{
409
+			case 'pgsql':
410
+				$sql .= ' RETURNING id;';
411
+				$this->logging->log('sql : '.$sql,INFO);
412
+				if (($ret_code=$db_conn->query($sql)) === false) {
413
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
414
+				}
415
+				$this->logging->log('SQL insertion OK',INFO );
416
+				// Get last id to insert oid/values in secondary table
417
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
418 418
                     
419
-                    $this->logging->log('Erreur recuperation id',1,'');
420
-                }
421
-                if (! isset($inserted_id_ret['id'])) {
422
-                    $this->logging->log('Error getting id',1,'');
423
-                }
424
-                $this->trapId=$inserted_id_ret['id'];
425
-                break;
426
-            case 'mysql':
427
-                $sql .= ';';
428
-                $this->logging->log('sql : '.$sql,INFO );
429
-                if ($db_conn->query($sql) === false) {
430
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
431
-                }
432
-                $this->logging->log('SQL insertion OK',INFO );
433
-                // Get last id to insert oid/values in secondary table
434
-                $sql='SELECT LAST_INSERT_ID();';
435
-                if (($ret_code=$db_conn->query($sql)) === false) {
436
-                    $this->logging->log('Erreur recuperation id',1,'');
437
-                }
419
+					$this->logging->log('Erreur recuperation id',1,'');
420
+				}
421
+				if (! isset($inserted_id_ret['id'])) {
422
+					$this->logging->log('Error getting id',1,'');
423
+				}
424
+				$this->trapId=$inserted_id_ret['id'];
425
+				break;
426
+			case 'mysql':
427
+				$sql .= ';';
428
+				$this->logging->log('sql : '.$sql,INFO );
429
+				if ($db_conn->query($sql) === false) {
430
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
431
+				}
432
+				$this->logging->log('SQL insertion OK',INFO );
433
+				// Get last id to insert oid/values in secondary table
434
+				$sql='SELECT LAST_INSERT_ID();';
435
+				if (($ret_code=$db_conn->query($sql)) === false) {
436
+					$this->logging->log('Erreur recuperation id',1,'');
437
+				}
438 438
                 
439
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
440
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
441
-                $this->trapId=$inserted_id;
442
-                break;
443
-            default:
444
-                $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
445
-        }
446
-        
447
-        $this->logging->log('id found: '. $this->trapId,INFO );
448
-    }
439
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
440
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
441
+				$this->trapId=$inserted_id;
442
+				break;
443
+			default:
444
+				$this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
445
+		}
446
+        
447
+		$this->logging->log('id found: '. $this->trapId,INFO );
448
+	}
449 449
     
450
-    /** Write trap data to trap database
451
-     */
452
-    public function writeTrapToDB()
453
-    {
454
-        
455
-        // If action is ignore -> don't send t DB
456
-        if ($this->trapToDb === false) return;
457
-        
458
-        
459
-        $db_conn=$this->trapsDB->db_connect_trap();
460
-        
461
-        $insert_col='';
462
-        $insert_val='';
463
-        // add date time
464
-        $this->trapData['date_received'] = date("Y-m-d H:i:s");
465
-        
466
-        $firstcol=1;
467
-        foreach ($this->trapData as $col => $val)
468
-        {
469
-            if ($firstcol==0)
470
-            {
471
-                $insert_col .=',';
472
-                $insert_val .=',';
473
-            }
474
-            $insert_col .= $col ;
475
-            $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
476
-            $firstcol=0;
477
-        }
478
-        
479
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
480
-        switch ($this->trapsDB->trapDBType)
481
-        {
482
-            case 'pgsql':
483
-                $sql .= ' RETURNING id;';
484
-                $this->logging->log('sql : '.$sql,INFO );
485
-                if (($ret_code=$db_conn->query($sql)) === false) {
486
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
487
-                }
488
-                $this->logging->log('SQL insertion OK',INFO );
489
-                // Get last id to insert oid/values in secondary table
490
-                if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
450
+	/** Write trap data to trap database
451
+	 */
452
+	public function writeTrapToDB()
453
+	{
454
+        
455
+		// If action is ignore -> don't send t DB
456
+		if ($this->trapToDb === false) return;
457
+        
458
+        
459
+		$db_conn=$this->trapsDB->db_connect_trap();
460
+        
461
+		$insert_col='';
462
+		$insert_val='';
463
+		// add date time
464
+		$this->trapData['date_received'] = date("Y-m-d H:i:s");
465
+        
466
+		$firstcol=1;
467
+		foreach ($this->trapData as $col => $val)
468
+		{
469
+			if ($firstcol==0)
470
+			{
471
+				$insert_col .=',';
472
+				$insert_val .=',';
473
+			}
474
+			$insert_col .= $col ;
475
+			$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
476
+			$firstcol=0;
477
+		}
478
+        
479
+		$sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
480
+		switch ($this->trapsDB->trapDBType)
481
+		{
482
+			case 'pgsql':
483
+				$sql .= ' RETURNING id;';
484
+				$this->logging->log('sql : '.$sql,INFO );
485
+				if (($ret_code=$db_conn->query($sql)) === false) {
486
+					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
487
+				}
488
+				$this->logging->log('SQL insertion OK',INFO );
489
+				// Get last id to insert oid/values in secondary table
490
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
491 491
                     
492
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
493
-                }
494
-                if (! isset($inserted_id_ret['id'])) {
495
-                    $this->logging->log('Error getting id',ERROR,'');
496
-                }
497
-                $this->trapId=$inserted_id_ret['id'];
498
-                break;
499
-            case 'mysql':
500
-                $sql .= ';';
501
-                $this->logging->log('sql : '.$sql,INFO );
502
-                if ($db_conn->query($sql) === false) {
503
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
504
-                }
505
-                $this->logging->log('SQL insertion OK',INFO );
506
-                // Get last id to insert oid/values in secondary table
507
-                $sql='SELECT LAST_INSERT_ID();';
508
-                if (($ret_code=$db_conn->query($sql)) === false) {
509
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
510
-                }
492
+					$this->logging->log('Erreur recuperation id',ERROR,'');
493
+				}
494
+				if (! isset($inserted_id_ret['id'])) {
495
+					$this->logging->log('Error getting id',ERROR,'');
496
+				}
497
+				$this->trapId=$inserted_id_ret['id'];
498
+				break;
499
+			case 'mysql':
500
+				$sql .= ';';
501
+				$this->logging->log('sql : '.$sql,INFO );
502
+				if ($db_conn->query($sql) === false) {
503
+					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
504
+				}
505
+				$this->logging->log('SQL insertion OK',INFO );
506
+				// Get last id to insert oid/values in secondary table
507
+				$sql='SELECT LAST_INSERT_ID();';
508
+				if (($ret_code=$db_conn->query($sql)) === false) {
509
+					$this->logging->log('Erreur recuperation id',ERROR,'');
510
+				}
511 511
                 
512
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
513
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
514
-                $this->trapId=$inserted_id;
515
-                break;
516
-            default:
517
-                $this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
518
-        }
519
-        $this->logging->log('id found: '.$this->trapId,INFO );
520
-        
521
-        // Fill trap extended data table
522
-        foreach ($this->trapDataExt as $value) {
523
-            // TODO : detect if trap value is encoded and decode it to UTF-8 for database
524
-            $firstcol=1;
525
-            $value->trap_id = $this->trapId;
526
-            $insert_col='';
527
-            $insert_val='';
528
-            foreach ($value as $col => $val)
529
-            {
530
-                if ($firstcol==0)
531
-                {
532
-                    $insert_col .=',';
533
-                    $insert_val .=',';
534
-                }
535
-                $insert_col .= $col;
536
-                $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
537
-                $firstcol=0;
538
-            }
512
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
513
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
514
+				$this->trapId=$inserted_id;
515
+				break;
516
+			default:
517
+				$this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
518
+		}
519
+		$this->logging->log('id found: '.$this->trapId,INFO );
520
+        
521
+		// Fill trap extended data table
522
+		foreach ($this->trapDataExt as $value) {
523
+			// TODO : detect if trap value is encoded and decode it to UTF-8 for database
524
+			$firstcol=1;
525
+			$value->trap_id = $this->trapId;
526
+			$insert_col='';
527
+			$insert_val='';
528
+			foreach ($value as $col => $val)
529
+			{
530
+				if ($firstcol==0)
531
+				{
532
+					$insert_col .=',';
533
+					$insert_val .=',';
534
+				}
535
+				$insert_col .= $col;
536
+				$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
537
+				$firstcol=0;
538
+			}
539 539
             
540
-            $sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
540
+			$sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
541 541
             
542
-            if ($db_conn->query($sql) === false) {
543
-                $this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
544
-            }
545
-        }
546
-    }
542
+			if ($db_conn->query($sql) === false) {
543
+				$this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
544
+			}
545
+		}
546
+	}
547 547
     
548
-    /** Get rules from rule database with ip and oid
549
-     *	@param $ip string ipv4 or ipv6
550
-     *	@param $oid string oid in numeric
551
-     *	@return mixed|boolean : PDO object or false
552
-     */
553
-    protected function getRules($ip,$oid)
554
-    {
555
-        $db_conn=$this->trapsDB->db_connect_trap();
556
-        // fetch rules based on IP in rule and OID
557
-        $sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
558
-        $this->logging->log('SQL query : '.$sql,DEBUG );
559
-        if (($ret_code=$db_conn->query($sql)) === false) {
560
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
561
-            return false;
562
-        }
563
-        $rules_all=$ret_code->fetchAll();
564
-        //echo "rule all :\n";print_r($rules_all);echo "\n";
565
-        $rules_ret=array();
566
-        $rule_ret_key=0;
567
-        foreach ($rules_all as $key => $rule)
568
-        {
569
-            if ($rule['ip4']==$ip || $rule['ip6']==$ip)
570
-            {
571
-                $rules_ret[$rule_ret_key]=$rules_all[$key];
572
-                //TODO : get host name by API (and check if correct in rule).
573
-                $rule_ret_key++;
574
-                continue;
575
-            }
548
+	/** Get rules from rule database with ip and oid
549
+	 *	@param $ip string ipv4 or ipv6
550
+	 *	@param $oid string oid in numeric
551
+	 *	@return mixed|boolean : PDO object or false
552
+	 */
553
+	protected function getRules($ip,$oid)
554
+	{
555
+		$db_conn=$this->trapsDB->db_connect_trap();
556
+		// fetch rules based on IP in rule and OID
557
+		$sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
558
+		$this->logging->log('SQL query : '.$sql,DEBUG );
559
+		if (($ret_code=$db_conn->query($sql)) === false) {
560
+			$this->logging->log('No result in query : ' . $sql,WARN,'');
561
+			return false;
562
+		}
563
+		$rules_all=$ret_code->fetchAll();
564
+		//echo "rule all :\n";print_r($rules_all);echo "\n";
565
+		$rules_ret=array();
566
+		$rule_ret_key=0;
567
+		foreach ($rules_all as $key => $rule)
568
+		{
569
+			if ($rule['ip4']==$ip || $rule['ip6']==$ip)
570
+			{
571
+				$rules_ret[$rule_ret_key]=$rules_all[$key];
572
+				//TODO : get host name by API (and check if correct in rule).
573
+				$rule_ret_key++;
574
+				continue;
575
+			}
576 576
 
577
-            if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
578
-            { // get ips of group members by oid
579
-                if ($this->apiUse === false)
580
-                {
581
-                    $db_conn2=$this->trapsDB->db_connect_ido();
582
-                    $sql="SELECT m.host_object_id, a.address, a.address6, b.name1 as name
577
+			if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
578
+			{ // get ips of group members by oid
579
+				if ($this->apiUse === false)
580
+				{
581
+					$db_conn2=$this->trapsDB->db_connect_ido();
582
+					$sql="SELECT m.host_object_id, a.address, a.address6, b.name1 as name
583 583
 						FROM icinga_objects as o
584 584
 						LEFT JOIN icinga_hostgroups as h ON o.object_id=h.hostgroup_object_id
585 585
 						LEFT JOIN icinga_hostgroup_members as m ON h.hostgroup_id=m.hostgroup_id
586 586
 						LEFT JOIN icinga_hosts as a ON a.host_object_id = m.host_object_id
587 587
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
588 588
 						WHERE o.name1='".$rule['host_group_name']."';";
589
-                    if (($ret_code2=$db_conn2->query($sql)) === false) {
590
-                        $this->logging->log('No result in query : ' . $sql,WARN,'');
591
-                        continue;
592
-                    }
593
-                    $grouphosts=$ret_code2->fetchAll();
594
-                }else{
595
-                    $api = $this->getAPI();
596
-                    $api->setCredentials($this->apiUsername, $this->apiPassword);
597
-                    $grouphosts=$api->getHostsIPByHostGroup($rule['host_group_name']);
598
-                }
599
-                //echo "rule grp :\n";print_r($grouphosts);echo "\n";
600
-                foreach ( $grouphosts as $host)
601
-                {
602
-                    if( is_object( $host ) ) $host=(array)$host;
603
-                    //echo $host['address']."\n";
604
-                    if ($host['address']==$ip || $host['address6']==$ip)
605
-                    {
606
-                        //echo "Rule added \n";
607
-                        $rules_ret[$rule_ret_key]=$rules_all[$key];
608
-                        $rules_ret[$rule_ret_key]['host_name']=$host['name'];
609
-                        $rule_ret_key++;
610
-                    }
611
-                }
612
-            }
589
+					if (($ret_code2=$db_conn2->query($sql)) === false) {
590
+						$this->logging->log('No result in query : ' . $sql,WARN,'');
591
+						continue;
592
+					}
593
+					$grouphosts=$ret_code2->fetchAll();
594
+				}else{
595
+					$api = $this->getAPI();
596
+					$api->setCredentials($this->apiUsername, $this->apiPassword);
597
+					$grouphosts=$api->getHostsIPByHostGroup($rule['host_group_name']);
598
+				}
599
+				//echo "rule grp :\n";print_r($grouphosts);echo "\n";
600
+				foreach ( $grouphosts as $host)
601
+				{
602
+					if( is_object( $host ) ) $host=(array)$host;
603
+					//echo $host['address']."\n";
604
+					if ($host['address']==$ip || $host['address6']==$ip)
605
+					{
606
+						//echo "Rule added \n";
607
+						$rules_ret[$rule_ret_key]=$rules_all[$key];
608
+						$rules_ret[$rule_ret_key]['host_name']=$host['name'];
609
+						$rule_ret_key++;
610
+					}
611
+				}
612
+			}
613 613
 
614
-        }
615
-        //echo "rule rest :\n";print_r($rules_ret);echo "\n";exit(0);
616
-        return $rules_ret;
617
-    }
614
+		}
615
+		//echo "rule rest :\n";print_r($rules_ret);echo "\n";exit(0);
616
+		return $rules_ret;
617
+	}
618 618
     
619
-    /** Add rule match to rule
620
-     *	@param id int : rule id
621
-     *   @param set int : value to set
622
-     */
623
-    protected function add_rule_match($id, $set)
624
-    {
625
-        $db_conn=$this->trapsDB->db_connect_trap();
626
-        $sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
627
-        if ($db_conn->query($sql) === false) {
628
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
629
-        }
630
-    }
619
+	/** Add rule match to rule
620
+	 *	@param id int : rule id
621
+	 *   @param set int : value to set
622
+	 */
623
+	protected function add_rule_match($id, $set)
624
+	{
625
+		$db_conn=$this->trapsDB->db_connect_trap();
626
+		$sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
627
+		if ($db_conn->query($sql) === false) {
628
+			$this->logging->log('Error in update query : ' . $sql,WARN,'');
629
+		}
630
+	}
631 631
     
632
-    /** Send SERVICE_CHECK_RESULT with icinga2cmd or API
633
-     *
634
-     * @param string $host
635
-     * @param string $service
636
-     * @param integer $state numerical staus
637
-     * @param string $display
638
-     * @returnn bool true is service check was sent without error
639
-     */
640
-    public function serviceCheckResult($host,$service,$state,$display)
641
-    {
642
-        if ($this->apiUse === false)
643
-        {
644
-            $send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
645
-                $host.';' .$service .';' . $state . ';'.$display;
646
-                $this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
632
+	/** Send SERVICE_CHECK_RESULT with icinga2cmd or API
633
+	 *
634
+	 * @param string $host
635
+	 * @param string $service
636
+	 * @param integer $state numerical staus
637
+	 * @param string $display
638
+	 * @returnn bool true is service check was sent without error
639
+	 */
640
+	public function serviceCheckResult($host,$service,$state,$display)
641
+	{
642
+		if ($this->apiUse === false)
643
+		{
644
+			$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
645
+				$host.';' .$service .';' . $state . ';'.$display;
646
+				$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
647 647
                 
648
-                // TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
649
-                exec('echo "'.$send.'" > ' .$this->icinga2cmd);
650
-                return true;
651
-        }
652
-        else
653
-        {
654
-            // Get perfdata if found
655
-            $matches=array();
656
-            if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
657
-            {
658
-                $display=$matches[1];
659
-                $perfdata=$matches[2];
660
-            }
661
-            else
662
-            {
663
-                $perfdata='';
664
-            }
648
+				// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
649
+				exec('echo "'.$send.'" > ' .$this->icinga2cmd);
650
+				return true;
651
+		}
652
+		else
653
+		{
654
+			// Get perfdata if found
655
+			$matches=array();
656
+			if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
657
+			{
658
+				$display=$matches[1];
659
+				$perfdata=$matches[2];
660
+			}
661
+			else
662
+			{
663
+				$perfdata='';
664
+			}
665 665
             
666
-            $api = $this->getAPI();
667
-            $api->setCredentials($this->apiUsername, $this->apiPassword);
668
-            list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
669
-            if ($retcode == false)
670
-            {
671
-                $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
672
-                return false;
673
-            }
674
-            else
675
-            {
676
-                $this->logging->log( "Sent result : " .$retmessage,INFO );
677
-                return true;
678
-            }
679
-        }
680
-    }
666
+			$api = $this->getAPI();
667
+			$api->setCredentials($this->apiUsername, $this->apiPassword);
668
+			list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
669
+			if ($retcode == false)
670
+			{
671
+				$this->logging->log( "Error sending result : " .$retmessage,WARN,'');
672
+				return false;
673
+			}
674
+			else
675
+			{
676
+				$this->logging->log( "Sent result : " .$retmessage,INFO );
677
+				return true;
678
+			}
679
+		}
680
+	}
681 681
     
682
-    public function getHostByIP($ip)
683
-    {
684
-        $api = $this->getAPI();
685
-        $api->setCredentials($this->apiUsername, $this->apiPassword);
686
-        return $api->getHostByIP($ip);
687
-    }
682
+	public function getHostByIP($ip)
683
+	{
684
+		$api = $this->getAPI();
685
+		$api->setCredentials($this->apiUsername, $this->apiPassword);
686
+		return $api->getHostByIP($ip);
687
+	}
688 688
     
689
-    /** Resolve display.
690
-     *	Changes _OID(<oid>) to value if found or text "<not in trap>"
691
-     *	@param $display string
692
-     *	@return string display
693
-     */
694
-    protected function applyDisplay($display)
695
-    {
696
-        $matches=array();
697
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$display,$matches) == 1)
698
-        {
699
-            $oid=$matches[1];
700
-            $found=0;
701
-            // Test and transform regexp
702
-            $oidR = $this->ruleClass->regexp_eval($oid);
689
+	/** Resolve display.
690
+	 *	Changes _OID(<oid>) to value if found or text "<not in trap>"
691
+	 *	@param $display string
692
+	 *	@return string display
693
+	 */
694
+	protected function applyDisplay($display)
695
+	{
696
+		$matches=array();
697
+		while (preg_match('/_OID\(([0-9\.\*]+)\)/',$display,$matches) == 1)
698
+		{
699
+			$oid=$matches[1];
700
+			$found=0;
701
+			// Test and transform regexp
702
+			$oidR = $this->ruleClass->regexp_eval($oid);
703 703
             
704
-            foreach($this->trapDataExt as $val)
705
-            {
706
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
707
-                {
708
-                    $val->value=preg_replace('/"/','',$val->value);
709
-                    $rep=0;
710
-                    $display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
711
-                    if ($rep==0)
712
-                    {
713
-                        $this->logging->log("Error in display",WARN,'');
714
-                        return $display;
715
-                    }
716
-                    $found=1;
717
-                    break;
718
-                }
719
-            }
720
-            if ($found==0)
721
-            {
722
-                $display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
723
-                if ($rep==0)
724
-                {
725
-                    $this->logging->log("Error in display",WARN,'');
726
-                    return $display;
727
-                }
728
-            }
729
-        }
730
-        return $display;
731
-    }
704
+			foreach($this->trapDataExt as $val)
705
+			{
706
+				if (preg_match("/^$oidR$/",$val->oid) == 1)
707
+				{
708
+					$val->value=preg_replace('/"/','',$val->value);
709
+					$rep=0;
710
+					$display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
711
+					if ($rep==0)
712
+					{
713
+						$this->logging->log("Error in display",WARN,'');
714
+						return $display;
715
+					}
716
+					$found=1;
717
+					break;
718
+				}
719
+			}
720
+			if ($found==0)
721
+			{
722
+				$display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
723
+				if ($rep==0)
724
+				{
725
+					$this->logging->log("Error in display",WARN,'');
726
+					return $display;
727
+				}
728
+			}
729
+		}
730
+		return $display;
731
+	}
732 732
     
733
-    /** Match rules for current trap and do action
734
-     */
735
-    public function applyRules()
736
-    {
737
-        $rules = $this->getRules($this->trapData['source_ip'],$this->trapData['trap_oid']);
738
-        
739
-        if ($rules===false || count($rules)==0)
740
-        {
741
-            $this->logging->log('No rules found for this trap',INFO );
742
-            $this->trapData['status']='unknown';
743
-            $this->trapToDb=true;
744
-            return;
745
-        }
746
-        //print_r($rules);
747
-        // Evaluate all rules in sequence
748
-        $this->trapAction=null;
749
-        foreach ($rules as $rule)
750
-        {
733
+	/** Match rules for current trap and do action
734
+	 */
735
+	public function applyRules()
736
+	{
737
+		$rules = $this->getRules($this->trapData['source_ip'],$this->trapData['trap_oid']);
738
+        
739
+		if ($rules===false || count($rules)==0)
740
+		{
741
+			$this->logging->log('No rules found for this trap',INFO );
742
+			$this->trapData['status']='unknown';
743
+			$this->trapToDb=true;
744
+			return;
745
+		}
746
+		//print_r($rules);
747
+		// Evaluate all rules in sequence
748
+		$this->trapAction=null;
749
+		foreach ($rules as $rule)
750
+		{
751 751
             
752
-            $host_name=$rule['host_name'];
753
-            $service_name=$rule['service_name'];
752
+			$host_name=$rule['host_name'];
753
+			$service_name=$rule['service_name'];
754 754
             
755
-            $display=$this->applyDisplay($rule['display']);
756
-            $this->trapAction = ($this->trapAction==null)? '' : $this->trapAction . ', ';
757
-            try
758
-            {
759
-                $this->logging->log('Rule to eval : '.$rule['rule'],INFO );
760
-                $evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt) ;
761
-                //->eval_rule($rule['rule']);
755
+			$display=$this->applyDisplay($rule['display']);
756
+			$this->trapAction = ($this->trapAction==null)? '' : $this->trapAction . ', ';
757
+			try
758
+			{
759
+				$this->logging->log('Rule to eval : '.$rule['rule'],INFO );
760
+				$evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt) ;
761
+				//->eval_rule($rule['rule']);
762 762
                 
763
-                if ($evalr == true)
764
-                {
765
-                    //$this->logging->log('rules OOK: '.print_r($rule),INFO );
766
-                    $action=$rule['action_match'];
767
-                    $this->logging->log('action OK : '.$action,INFO );
768
-                    if ($action >= 0)
769
-                    {
770
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
771
-                        {
772
-                            $this->trapAction.='Error sending status : check cmd/API';
773
-                        }
774
-                        else
775
-                        {
776
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
777
-                            $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
778
-                        }
779
-                    }
780
-                    else
781
-                    {
782
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
783
-                    }
784
-                    $this->trapToDb=($action==-2)?false:true;
785
-                }
786
-                else
787
-                {
788
-                    //$this->logging->log('rules KOO : '.print_r($rule),INFO );
763
+				if ($evalr == true)
764
+				{
765
+					//$this->logging->log('rules OOK: '.print_r($rule),INFO );
766
+					$action=$rule['action_match'];
767
+					$this->logging->log('action OK : '.$action,INFO );
768
+					if ($action >= 0)
769
+					{
770
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
771
+						{
772
+							$this->trapAction.='Error sending status : check cmd/API';
773
+						}
774
+						else
775
+						{
776
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
777
+							$this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
778
+						}
779
+					}
780
+					else
781
+					{
782
+						$this->add_rule_match($rule['id'],$rule['num_match']+1);
783
+					}
784
+					$this->trapToDb=($action==-2)?false:true;
785
+				}
786
+				else
787
+				{
788
+					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
789 789
                     
790
-                    $action=$rule['action_nomatch'];
791
-                    $this->logging->log('action NOK : '.$action,INFO );
792
-                    if ($action >= 0)
793
-                    {
794
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
795
-                        {
796
-                            $this->trapAction.='Error sending status : check cmd/API';
797
-                        }
798
-                        else
799
-                        {
800
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
801
-                            $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
802
-                        }
803
-                    }
804
-                    else
805
-                    {
806
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
807
-                    }
808
-                    $this->trapToDb=($action==-2)?false:true;
809
-                }
810
-                // Put name in source_name
811
-                if (!isset($this->trapData['source_name']))
812
-                {
813
-                    $this->trapData['source_name']=$rule['host_name'];
814
-                }
815
-                else
816
-                {
817
-                    if (!preg_match('/'.$rule['host_name'].'/',$this->trapData['source_name']))
818
-                    { // only add if not present
819
-                        $this->trapData['source_name'].=','.$rule['host_name'];
820
-                    }
821
-                }
822
-            }
823
-            catch (Exception $e)
824
-            {
825
-                $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
826
-                $this->trapAction.=' ERR : '.$e->getMessage();
827
-                $this->trapData['status']='error';
828
-            }
790
+					$action=$rule['action_nomatch'];
791
+					$this->logging->log('action NOK : '.$action,INFO );
792
+					if ($action >= 0)
793
+					{
794
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
795
+						{
796
+							$this->trapAction.='Error sending status : check cmd/API';
797
+						}
798
+						else
799
+						{
800
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
801
+							$this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
802
+						}
803
+					}
804
+					else
805
+					{
806
+						$this->add_rule_match($rule['id'],$rule['num_match']+1);
807
+					}
808
+					$this->trapToDb=($action==-2)?false:true;
809
+				}
810
+				// Put name in source_name
811
+				if (!isset($this->trapData['source_name']))
812
+				{
813
+					$this->trapData['source_name']=$rule['host_name'];
814
+				}
815
+				else
816
+				{
817
+					if (!preg_match('/'.$rule['host_name'].'/',$this->trapData['source_name']))
818
+					{ // only add if not present
819
+						$this->trapData['source_name'].=','.$rule['host_name'];
820
+					}
821
+				}
822
+			}
823
+			catch (Exception $e)
824
+			{
825
+				$this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
826
+				$this->trapAction.=' ERR : '.$e->getMessage();
827
+				$this->trapData['status']='error';
828
+			}
829 829
             
830
-        }
831
-        if ($this->trapData['status']=='error')
832
-        {
833
-            $this->trapToDb=true; // Always put errors in DB for the use can see
834
-        }
835
-        else
836
-        {
837
-            $this->trapData['status']='done';
838
-        }
839
-    }
830
+		}
831
+		if ($this->trapData['status']=='error')
832
+		{
833
+			$this->trapToDb=true; // Always put errors in DB for the use can see
834
+		}
835
+		else
836
+		{
837
+			$this->trapData['status']='done';
838
+		}
839
+	}
840 840
     
841
-    /** Add Time a action to rule
842
-     *	@param string $time : time to process to insert in SQL
843
-     */
844
-    public function add_rule_final($time)
845
-    {
846
-        $db_conn=$this->trapsDB->db_connect_trap();
847
-        if ($this->trapAction==null)
848
-        {
849
-            $this->trapAction='No action';
850
-        }
851
-        $sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trapAction."'  WHERE (id = '".$this->trapId."');";
852
-        if ($db_conn->query($sql) === false) {
853
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
854
-        }
855
-    }
841
+	/** Add Time a action to rule
842
+	 *	@param string $time : time to process to insert in SQL
843
+	 */
844
+	public function add_rule_final($time)
845
+	{
846
+		$db_conn=$this->trapsDB->db_connect_trap();
847
+		if ($this->trapAction==null)
848
+		{
849
+			$this->trapAction='No action';
850
+		}
851
+		$sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trapAction."'  WHERE (id = '".$this->trapId."');";
852
+		if ($db_conn->query($sql) === false) {
853
+			$this->logging->log('Error in update query : ' . $sql,WARN,'');
854
+		}
855
+	}
856 856
     
857
-    /*********** UTILITIES *********************/
857
+	/*********** UTILITIES *********************/
858 858
     
859
-    /** reset service to OK after time defined in rule
860
-     *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better
861
-     *	@return integer : not in use
862
-     **/
863
-    public function reset_services()
864
-    {
865
-        // Get all services not in 'ok' state
866
-        if ($this->apiUse === false)
867
-        {
868
-            $sql_query="SELECT s.service_object_id,
859
+	/** reset service to OK after time defined in rule
860
+	 *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better
861
+	 *	@return integer : not in use
862
+	 **/
863
+	public function reset_services()
864
+	{
865
+		// Get all services not in 'ok' state
866
+		if ($this->apiUse === false)
867
+		{
868
+			$sql_query="SELECT s.service_object_id,
869 869
                                 UNIX_TIMESTAMP(s.last_check) AS last_check,
870 870
                                 s.current_state as state,
871 871
                                 v.name1 as host_name,
@@ -873,49 +873,49 @@  discard block
 block discarded – undo
873 873
                                 FROM icinga_servicestatus AS s
874 874
                                 LEFT JOIN icinga_objects as v ON s.service_object_id=v.object_id
875 875
                                 WHERE s.current_state != 0;";
876
-            $db_conn=$this->trapsDB->db_connect_ido();
877
-            if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
878
-                $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
879
-                return 0;
880
-            }
881
-            $services=$services_db->fetchAll();
882
-        }else{
883
-            $api = $this->getAPI();
884
-            $api->setCredentials($this->apiUsername, $this->apiPassword);
885
-            $services=$api->getNOKservice();
886
-        }
887
-        
888
-        // Get all rules
889
-        $sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
890
-        $db_conn2=$this->trapsDB->db_connect_trap();
891
-        if (($rules_db=$db_conn2->query($sql_query)) === false) {
892
-            $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
893
-            return 0;
894
-        }
895
-        $rules=$rules_db->fetchAll();
896
-        
897
-        $now=date('U');
898
-        
899
-        $numreset=0;
900
-        foreach ($rules as $rule)
901
-        {
902
-            if( is_object( $services ) ) $services=(array)$services;
903
-            foreach ($services as $service)
904
-            {
905
-                if ($service['name'] == $rule['service_name'] &&
906
-                    $service['host_name'] == $rule['host_name'] &&
907
-                    ($service['last_check'] + $rule['revert_ok']) < $now)
908
-                {
909
-                    $this->serviceCheckResult($service['host_name'],$service['name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
910
-                    $numreset++;
911
-                }
912
-            }
913
-        }
914
-        echo "\n";
915
-        echo $numreset . " service(s) reset to OK\n";
916
-        return 0;
917
-        
918
-    }
876
+			$db_conn=$this->trapsDB->db_connect_ido();
877
+			if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
878
+				$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
879
+				return 0;
880
+			}
881
+			$services=$services_db->fetchAll();
882
+		}else{
883
+			$api = $this->getAPI();
884
+			$api->setCredentials($this->apiUsername, $this->apiPassword);
885
+			$services=$api->getNOKservice();
886
+		}
887
+        
888
+		// Get all rules
889
+		$sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
890
+		$db_conn2=$this->trapsDB->db_connect_trap();
891
+		if (($rules_db=$db_conn2->query($sql_query)) === false) {
892
+			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
893
+			return 0;
894
+		}
895
+		$rules=$rules_db->fetchAll();
896
+        
897
+		$now=date('U');
898
+        
899
+		$numreset=0;
900
+		foreach ($rules as $rule)
901
+		{
902
+			if( is_object( $services ) ) $services=(array)$services;
903
+			foreach ($services as $service)
904
+			{
905
+				if ($service['name'] == $rule['service_name'] &&
906
+					$service['host_name'] == $rule['host_name'] &&
907
+					($service['last_check'] + $rule['revert_ok']) < $now)
908
+				{
909
+					$this->serviceCheckResult($service['host_name'],$service['name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
910
+					$numreset++;
911
+				}
912
+			}
913
+		}
914
+		echo "\n";
915
+		echo $numreset . " service(s) reset to OK\n";
916
+		return 0;
917
+        
918
+	}
919 919
     
920 920
     
921 921
 }
Please login to merge, or discard this patch.
Spacing   +183 added lines, -183 removed lines patch added patch discarded remove patch
@@ -52,13 +52,13 @@  discard block
 block discarded – undo
52 52
     
53 53
     // Logs
54 54
     /** @var Logging Logging class. */
55
-    public $logging;    //< Logging class.
55
+    public $logging; //< Logging class.
56 56
     /** @var bool true if log was setup in constructor */
57
-    protected $logSetup;   //< bool true if log was setup in constructor
57
+    protected $logSetup; //< bool true if log was setup in constructor
58 58
     
59 59
     // Databases
60 60
     /** @var Database $trapsDB  Database class*/
61
-    public $trapsDB = null;
61
+    public $trapsDB=null;
62 62
     
63 63
     // Trap received data
64 64
     protected $receivingHost;
@@ -74,18 +74,18 @@  discard block
 block discarded – undo
74 74
     protected $trapToDb=true;
75 75
     
76 76
     /** @var Mib mib class */
77
-    public $mibClass = null;
77
+    public $mibClass=null;
78 78
     
79 79
     /** @var Rule rule class */
80
-    public $ruleClass = null;
80
+    public $ruleClass=null;
81 81
     
82 82
     /** @var Plugins plugins manager **/
83
-    public $pluginClass = null;
83
+    public $pluginClass=null;
84 84
     
85 85
     /** @var TrapApi $trapApiClass */
86
-    public $trapApiClass = null;
86
+    public $trapApiClass=null;
87 87
     
88
-    function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
88
+    function __construct($etcDir='/etc/icingaweb2', $baseLogLevel=null, $baseLogMode='syslog', $baseLogFile='')
89 89
     {
90 90
         // Paths of ini files
91 91
         $this->icingaweb2Etc=$etcDir;
@@ -93,10 +93,10 @@  discard block
 block discarded – undo
93 93
         $this->icingaweb2Ressources=$this->icingaweb2Etc."/resources.ini";
94 94
 
95 95
         // Setup logging
96
-        $this->logging = new Logging();
96
+        $this->logging=new Logging();
97 97
         if ($baseLogLevel != null)
98 98
         {
99
-            $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
99
+            $this->logging->setLogging($baseLogLevel, $baseLogMode, $baseLogFile);
100 100
             $this->logSetup=true;
101 101
         }
102 102
         else
@@ -108,17 +108,17 @@  discard block
 block discarded – undo
108 108
         
109 109
         // Create distributed API object
110 110
         
111
-        $this->trapApiClass = new TrapApi($this->logging);
111
+        $this->trapApiClass=new TrapApi($this->logging);
112 112
         
113 113
         // Get options from ini files
114
-        if (! is_file($this->trapModuleConfig))
114
+        if (!is_file($this->trapModuleConfig))
115 115
         {
116 116
             throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
117 117
         }
118
-        $trapConfig=parse_ini_file($this->trapModuleConfig,true);
118
+        $trapConfig=parse_ini_file($this->trapModuleConfig, true);
119 119
         if ($trapConfig == false)
120 120
         {
121
-            $this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
121
+            $this->logging->log("Error reading ini file : ".$this->trapModuleConfig, ERROR, 'syslog');
122 122
             throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
123 123
         }
124 124
         $this->getMainOptions($trapConfig); // Get main options from ini file
@@ -132,10 +132,10 @@  discard block
 block discarded – undo
132 132
         if ($this->apiUse === true) $this->getAPI(); // Setup API
133 133
         
134 134
         // Setup MIB
135
-        $this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
135
+        $this->mibClass=new Mib($this->logging, $this->trapsDB, $this->snmptranslate, $this->snmptranslate_dirs); // Create Mib class
136 136
         
137 137
         // Setup Rule
138
-        $this->ruleClass = new Rule($this); //< Create Rule class
138
+        $this->ruleClass=new Rule($this); //< Create Rule class
139 139
         
140 140
         $this->trapData=array(  // TODO : put this in a reset function (DAEMON_MODE)
141 141
             'source_ip'	=> 'unknown',
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
         
148 148
         // Setup Plugins
149 149
         //Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
150
-        $this->pluginClass = new Plugins($this);
150
+        $this->pluginClass=new Plugins($this);
151 151
             
152 152
             
153 153
     }
@@ -176,15 +176,15 @@  discard block
 block discarded – undo
176 176
      *	@param  string $destination file/syslog/display
177 177
      *	@return void
178 178
      **/
179
-    public function trapLog( $message, $level, $destination ='') // OBSOLETE
179
+    public function trapLog($message, $level, $destination='') // OBSOLETE
180 180
     {
181 181
         // TODO : replace ref with $this->logging->log
182 182
         $this->logging->log($message, $level, $destination);
183 183
     }
184 184
     
185
-    public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
185
+    public function setLogging($debugLvl, $outputType, $outputOption=null)  // OBSOLETE
186 186
     {
187
-        $this->logging->setLogging($debugLvl, $outputType,$outputOption);
187
+        $this->logging->setLogging($debugLvl, $outputType, $outputOption);
188 188
     }
189 189
     
190 190
     /**
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
     {
196 196
         if ($this->icinga2api == null)
197 197
         {
198
-            $this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
198
+            $this->icinga2api=new Icinga2API($this->apiHostname, $this->apiPort);
199 199
         }
200 200
         return $this->icinga2api;
201 201
     }
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
         if ($input_stream === false)
215 215
         {
216 216
             $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
217
-            $this->logging->log("Error reading stdin !",ERROR,'');
217
+            $this->logging->log("Error reading stdin !", ERROR, '');
218 218
             return null; // note : exception thrown by logging
219 219
         }
220 220
         
@@ -223,21 +223,21 @@  discard block
 block discarded – undo
223 223
         if ($this->receivingHost === false)
224 224
         {
225 225
             $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
226
-            $this->logging->log("Error reading Host !",ERROR,'');
226
+            $this->logging->log("Error reading Host !", ERROR, '');
227 227
         }
228 228
         // line 2 IP:port=>IP:port
229 229
         $IP=chop(fgets($input_stream));
230 230
         if ($IP === false)
231 231
         {
232 232
             $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
233
-            $this->logging->log("Error reading IP !",ERROR,'');
233
+            $this->logging->log("Error reading IP !", ERROR, '');
234 234
         }
235 235
         $matches=array();
236
-        $ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
237
-        if ($ret_code===0 || $ret_code===false)
236
+        $ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/', $IP, $matches);
237
+        if ($ret_code === 0 || $ret_code === false)
238 238
         {
239 239
             $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
240
-            $this->logging->log('Error parsing IP : '.$IP,ERROR,'');
240
+            $this->logging->log('Error parsing IP : '.$IP, ERROR, '');
241 241
         }
242 242
         else
243 243
         {
@@ -247,41 +247,41 @@  discard block
 block discarded – undo
247 247
             $this->trapData['destination_port']=$matches[4];
248 248
         }
249 249
         
250
-        while (($vars=fgets($input_stream)) !==false)
250
+        while (($vars=fgets($input_stream)) !== false)
251 251
         {
252 252
             $vars=chop($vars);
253
-            $ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
254
-            if ($ret_code===0 || $ret_code===false)
253
+            $ret_code=preg_match('/^([^ ]+) (.*)$/', $vars, $matches);
254
+            if ($ret_code === 0 || $ret_code === false)
255 255
             {
256
-                $this->logging->log('No match on trap data : '.$vars,WARN,'');
256
+                $this->logging->log('No match on trap data : '.$vars, WARN, '');
257 257
                 continue;
258 258
             }
259
-            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'))
259
+            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'))
260 260
             {
261 261
                 $this->trapData['trap_oid']=$matches[2];
262 262
                 continue;
263 263
             }
264
-            if ( $this->useSnmpTrapAddess === TRUE &&  preg_match('/'.$this->snmpTrapAddressOID.'/', $matches[1]) == 1)
264
+            if ($this->useSnmpTrapAddess === TRUE && preg_match('/'.$this->snmpTrapAddressOID.'/', $matches[1]) == 1)
265 265
             {
266
-                $this->logging->log('Found relayed trap from ' . $matches[2] . ' relayed by ' .$this->trapData['source_ip'],DEBUG);
267
-                if (preg_match('/^[0-9\.]+$/',$matches[2]) == 0 && preg_match('/^[0-9a-fA-F:]+$/',$matches[2]) == 0)
266
+                $this->logging->log('Found relayed trap from '.$matches[2].' relayed by '.$this->trapData['source_ip'], DEBUG);
267
+                if (preg_match('/^[0-9\.]+$/', $matches[2]) == 0 && preg_match('/^[0-9a-fA-F:]+$/', $matches[2]) == 0)
268 268
                 {
269
-                    $this->logging->log('Value of SnmpTrapAddess ('.$this->snmpTrapAddressOID.') is not IP : ' .$matches[2],WARN,'');
269
+                    $this->logging->log('Value of SnmpTrapAddess ('.$this->snmpTrapAddressOID.') is not IP : '.$matches[2], WARN, '');
270 270
                     continue;
271 271
                 }
272
-                $this->trapData['source_ip'] = $matches[2];
272
+                $this->trapData['source_ip']=$matches[2];
273 273
                 continue;
274 274
             }
275
-            $object= new stdClass;
276
-            $object->oid =$matches[1];
277
-            $object->value = $matches[2];
278
-            array_push($this->trapDataExt,$object);
275
+            $object=new stdClass;
276
+            $object->oid=$matches[1];
277
+            $object->value=$matches[2];
278
+            array_push($this->trapDataExt, $object);
279 279
         }
280 280
         
281
-        if ($this->trapData['trap_oid']=='unknown')
281
+        if ($this->trapData['trap_oid'] == 'unknown')
282 282
         {
283
-            $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trapData['source_ip']);
284
-            $this->logging->log('no trap oid found',ERROR,'');
283
+            $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)", $this->trapData['source_ip']);
284
+            $this->logging->log('no trap oid found', ERROR, '');
285 285
         }
286 286
         
287 287
         // Translate oids.
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
         }
304 304
         
305 305
         
306
-        $this->trapData['status']= 'waiting';
306
+        $this->trapData['status']='waiting';
307 307
         
308 308
         return $this->trapData;
309 309
     }
@@ -319,38 +319,38 @@  discard block
 block discarded – undo
319 319
         $db_conn=$this->trapsDB->db_connect_trap();
320 320
         
321 321
         $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
322
-        $this->logging->log('SQL query : '.$sql,DEBUG );
322
+        $this->logging->log('SQL query : '.$sql, DEBUG);
323 323
         if (($ret_code=$db_conn->query($sql)) === false) {
324
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
324
+            $this->logging->log('No result in query : '.$sql, ERROR, '');
325 325
         }
326 326
         else {
327 327
             if (($name=$ret_code->fetch()) !== false)
328
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
328
+                return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
329 329
         }
330 330
         
331 331
         // Also check if it is an instance of OID
332
-        $oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
332
+        $oid_instance=preg_replace('/\.[0-9]+$/', '', $oid);
333 333
         
334 334
         $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
335
-        $this->logging->log('SQL query : '.$sql,DEBUG );
335
+        $this->logging->log('SQL query : '.$sql, DEBUG);
336 336
         if (($ret_code=$db_conn->query($sql)) === false) {
337
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
337
+            $this->logging->log('No result in query : '.$sql, ERROR, '');
338 338
         }
339 339
         else {
340 340
             if (($name=$ret_code->fetch()) !== false)
341
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
341
+                return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
342 342
         }
343 343
         
344 344
         // Try to get oid name from snmptranslate
345
-        $translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
345
+        $translate=exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
346 346
             ' '.$oid);
347 347
         $matches=array();
348
-        $ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
349
-        if ($ret_code===0 || $ret_code === false) {
348
+        $ret_code=preg_match('/(.*)::(.*)/', $translate, $matches);
349
+        if ($ret_code === 0 || $ret_code === false) {
350 350
             return NULL;
351 351
         } else {
352
-            $this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
353
-            return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
352
+            $this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid, INFO);
353
+            return array('trap_name_mib'=>$matches[1], 'trap_name'=>$matches[2]);
354 354
         }
355 355
     }
356 356
     
@@ -361,90 +361,90 @@  discard block
 block discarded – undo
361 361
      **/
362 362
     public function eraseOldTraps($days=0)
363 363
     {
364
-        if ($days==0)
364
+        if ($days == 0)
365 365
         {
366 366
             if (($days=$this->getDBConfig('db_remove_days')) == null)
367 367
             {
368
-                $this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
368
+                $this->logging->log('No days specified & no db value : no tap erase', WARN, '');
369 369
                 return;
370 370
             }
371 371
         }
372 372
         $db_conn=$this->trapsDB->db_connect_trap();
373
-        $daysago = strtotime("-".$days." day");
374
-        $sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
373
+        $daysago=strtotime("-".$days." day");
374
+        $sql='delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s", $daysago).'\';';
375 375
         if ($db_conn->query($sql) === false) {
376
-            $this->logging->log('Error erasing traps : '.$sql,ERROR,'');
376
+            $this->logging->log('Error erasing traps : '.$sql, ERROR, '');
377 377
         }
378
-        $this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
378
+        $this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql, INFO);
379 379
     }
380 380
     
381 381
     /** Write error to received trap database
382 382
      */
383
-    public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
383
+    public function writeTrapErrorToDB($message, $sourceIP=null, $trapoid=null)
384 384
     {
385 385
         
386 386
         $db_conn=$this->trapsDB->db_connect_trap();
387 387
         
388 388
         // add date time
389
-        $insert_col ='date_received,status';
390
-        $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
389
+        $insert_col='date_received,status';
390
+        $insert_val="'".date("Y-m-d H:i:s")."','error'";
391 391
         
392
-        if ($sourceIP !=null)
392
+        if ($sourceIP != null)
393 393
         {
394
-            $insert_col .=',source_ip';
395
-            $insert_val .=",'". $sourceIP ."'";
394
+            $insert_col.=',source_ip';
395
+            $insert_val.=",'".$sourceIP."'";
396 396
         }
397
-        if ($trapoid !=null)
397
+        if ($trapoid != null)
398 398
         {
399
-            $insert_col .=',trap_oid';
400
-            $insert_val .=",'". $trapoid ."'";
399
+            $insert_col.=',trap_oid';
400
+            $insert_val.=",'".$trapoid."'";
401 401
         }
402
-        $insert_col .=',status_detail';
403
-        $insert_val .=",'". $message ."'";
402
+        $insert_col.=',status_detail';
403
+        $insert_val.=",'".$message."'";
404 404
         
405
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
405
+        $sql='INSERT INTO '.$this->dbPrefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
406 406
         
407 407
         switch ($this->trapsDB->trapDBType)
408 408
         {
409 409
             case 'pgsql':
410
-                $sql .= ' RETURNING id;';
411
-                $this->logging->log('sql : '.$sql,INFO);
410
+                $sql.=' RETURNING id;';
411
+                $this->logging->log('sql : '.$sql, INFO);
412 412
                 if (($ret_code=$db_conn->query($sql)) === false) {
413
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
413
+                    $this->logging->log('Error SQL insert : '.$sql, 1, '');
414 414
                 }
415
-                $this->logging->log('SQL insertion OK',INFO );
415
+                $this->logging->log('SQL insertion OK', INFO);
416 416
                 // Get last id to insert oid/values in secondary table
417 417
                 if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
418 418
                     
419
-                    $this->logging->log('Erreur recuperation id',1,'');
419
+                    $this->logging->log('Erreur recuperation id', 1, '');
420 420
                 }
421
-                if (! isset($inserted_id_ret['id'])) {
422
-                    $this->logging->log('Error getting id',1,'');
421
+                if (!isset($inserted_id_ret['id'])) {
422
+                    $this->logging->log('Error getting id', 1, '');
423 423
                 }
424 424
                 $this->trapId=$inserted_id_ret['id'];
425 425
                 break;
426 426
             case 'mysql':
427
-                $sql .= ';';
428
-                $this->logging->log('sql : '.$sql,INFO );
427
+                $sql.=';';
428
+                $this->logging->log('sql : '.$sql, INFO);
429 429
                 if ($db_conn->query($sql) === false) {
430
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
430
+                    $this->logging->log('Error SQL insert : '.$sql, 1, '');
431 431
                 }
432
-                $this->logging->log('SQL insertion OK',INFO );
432
+                $this->logging->log('SQL insertion OK', INFO);
433 433
                 // Get last id to insert oid/values in secondary table
434 434
                 $sql='SELECT LAST_INSERT_ID();';
435 435
                 if (($ret_code=$db_conn->query($sql)) === false) {
436
-                    $this->logging->log('Erreur recuperation id',1,'');
436
+                    $this->logging->log('Erreur recuperation id', 1, '');
437 437
                 }
438 438
                 
439 439
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
440
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
440
+                if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
441 441
                 $this->trapId=$inserted_id;
442 442
                 break;
443 443
             default:
444
-                $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
444
+                $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType, 1, '');
445 445
         }
446 446
         
447
-        $this->logging->log('id found: '. $this->trapId,INFO );
447
+        $this->logging->log('id found: '.$this->trapId, INFO);
448 448
     }
449 449
     
450 450
     /** Write trap data to trap database
@@ -461,86 +461,86 @@  discard block
 block discarded – undo
461 461
         $insert_col='';
462 462
         $insert_val='';
463 463
         // add date time
464
-        $this->trapData['date_received'] = date("Y-m-d H:i:s");
464
+        $this->trapData['date_received']=date("Y-m-d H:i:s");
465 465
         
466 466
         $firstcol=1;
467 467
         foreach ($this->trapData as $col => $val)
468 468
         {
469
-            if ($firstcol==0)
469
+            if ($firstcol == 0)
470 470
             {
471
-                $insert_col .=',';
472
-                $insert_val .=',';
471
+                $insert_col.=',';
472
+                $insert_val.=',';
473 473
             }
474
-            $insert_col .= $col ;
475
-            $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
474
+            $insert_col.=$col;
475
+            $insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
476 476
             $firstcol=0;
477 477
         }
478 478
         
479
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
479
+        $sql='INSERT INTO '.$this->dbPrefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
480 480
         switch ($this->trapsDB->trapDBType)
481 481
         {
482 482
             case 'pgsql':
483
-                $sql .= ' RETURNING id;';
484
-                $this->logging->log('sql : '.$sql,INFO );
483
+                $sql.=' RETURNING id;';
484
+                $this->logging->log('sql : '.$sql, INFO);
485 485
                 if (($ret_code=$db_conn->query($sql)) === false) {
486
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
486
+                    $this->logging->log('Error SQL insert : '.$sql, ERROR, '');
487 487
                 }
488
-                $this->logging->log('SQL insertion OK',INFO );
488
+                $this->logging->log('SQL insertion OK', INFO);
489 489
                 // Get last id to insert oid/values in secondary table
490 490
                 if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
491 491
                     
492
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
492
+                    $this->logging->log('Erreur recuperation id', ERROR, '');
493 493
                 }
494
-                if (! isset($inserted_id_ret['id'])) {
495
-                    $this->logging->log('Error getting id',ERROR,'');
494
+                if (!isset($inserted_id_ret['id'])) {
495
+                    $this->logging->log('Error getting id', ERROR, '');
496 496
                 }
497 497
                 $this->trapId=$inserted_id_ret['id'];
498 498
                 break;
499 499
             case 'mysql':
500
-                $sql .= ';';
501
-                $this->logging->log('sql : '.$sql,INFO );
500
+                $sql.=';';
501
+                $this->logging->log('sql : '.$sql, INFO);
502 502
                 if ($db_conn->query($sql) === false) {
503
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
503
+                    $this->logging->log('Error SQL insert : '.$sql, ERROR, '');
504 504
                 }
505
-                $this->logging->log('SQL insertion OK',INFO );
505
+                $this->logging->log('SQL insertion OK', INFO);
506 506
                 // Get last id to insert oid/values in secondary table
507 507
                 $sql='SELECT LAST_INSERT_ID();';
508 508
                 if (($ret_code=$db_conn->query($sql)) === false) {
509
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
509
+                    $this->logging->log('Erreur recuperation id', ERROR, '');
510 510
                 }
511 511
                 
512 512
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
513
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
513
+                if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
514 514
                 $this->trapId=$inserted_id;
515 515
                 break;
516 516
             default:
517
-                $this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
517
+                $this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType, ERROR, '');
518 518
         }
519
-        $this->logging->log('id found: '.$this->trapId,INFO );
519
+        $this->logging->log('id found: '.$this->trapId, INFO);
520 520
         
521 521
         // Fill trap extended data table
522 522
         foreach ($this->trapDataExt as $value) {
523 523
             // TODO : detect if trap value is encoded and decode it to UTF-8 for database
524 524
             $firstcol=1;
525
-            $value->trap_id = $this->trapId;
525
+            $value->trap_id=$this->trapId;
526 526
             $insert_col='';
527 527
             $insert_val='';
528 528
             foreach ($value as $col => $val)
529 529
             {
530
-                if ($firstcol==0)
530
+                if ($firstcol == 0)
531 531
                 {
532
-                    $insert_col .=',';
533
-                    $insert_val .=',';
532
+                    $insert_col.=',';
533
+                    $insert_val.=',';
534 534
                 }
535
-                $insert_col .= $col;
536
-                $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
535
+                $insert_col.=$col;
536
+                $insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
537 537
                 $firstcol=0;
538 538
             }
539 539
             
540
-            $sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
540
+            $sql='INSERT INTO '.$this->dbPrefix.'received_data ('.$insert_col.') VALUES ('.$insert_val.');';
541 541
             
542 542
             if ($db_conn->query($sql) === false) {
543
-                $this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
543
+                $this->logging->log('Erreur insertion data : '.$sql, WARN, '');
544 544
             }
545 545
         }
546 546
     }
@@ -550,14 +550,14 @@  discard block
 block discarded – undo
550 550
      *	@param $oid string oid in numeric
551 551
      *	@return mixed|boolean : PDO object or false
552 552
      */
553
-    protected function getRules($ip,$oid)
553
+    protected function getRules($ip, $oid)
554 554
     {
555 555
         $db_conn=$this->trapsDB->db_connect_trap();
556 556
         // fetch rules based on IP in rule and OID
557 557
         $sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
558
-        $this->logging->log('SQL query : '.$sql,DEBUG );
558
+        $this->logging->log('SQL query : '.$sql, DEBUG);
559 559
         if (($ret_code=$db_conn->query($sql)) === false) {
560
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
560
+            $this->logging->log('No result in query : '.$sql, WARN, '');
561 561
             return false;
562 562
         }
563 563
         $rules_all=$ret_code->fetchAll();
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
         $rule_ret_key=0;
567 567
         foreach ($rules_all as $key => $rule)
568 568
         {
569
-            if ($rule['ip4']==$ip || $rule['ip6']==$ip)
569
+            if ($rule['ip4'] == $ip || $rule['ip6'] == $ip)
570 570
             {
571 571
                 $rules_ret[$rule_ret_key]=$rules_all[$key];
572 572
                 //TODO : get host name by API (and check if correct in rule).
@@ -574,7 +574,7 @@  discard block
 block discarded – undo
574 574
                 continue;
575 575
             }
576 576
 
577
-            if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
577
+            if (isset($rule['host_group_name']) && $rule['host_group_name'] != null)
578 578
             { // get ips of group members by oid
579 579
                 if ($this->apiUse === false)
580 580
                 {
@@ -587,21 +587,21 @@  discard block
 block discarded – undo
587 587
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
588 588
 						WHERE o.name1='".$rule['host_group_name']."';";
589 589
                     if (($ret_code2=$db_conn2->query($sql)) === false) {
590
-                        $this->logging->log('No result in query : ' . $sql,WARN,'');
590
+                        $this->logging->log('No result in query : '.$sql, WARN, '');
591 591
                         continue;
592 592
                     }
593 593
                     $grouphosts=$ret_code2->fetchAll();
594
-                }else{
595
-                    $api = $this->getAPI();
594
+                } else {
595
+                    $api=$this->getAPI();
596 596
                     $api->setCredentials($this->apiUsername, $this->apiPassword);
597 597
                     $grouphosts=$api->getHostsIPByHostGroup($rule['host_group_name']);
598 598
                 }
599 599
                 //echo "rule grp :\n";print_r($grouphosts);echo "\n";
600
-                foreach ( $grouphosts as $host)
600
+                foreach ($grouphosts as $host)
601 601
                 {
602
-                    if( is_object( $host ) ) $host=(array)$host;
602
+                    if (is_object($host)) $host=(array) $host;
603 603
                     //echo $host['address']."\n";
604
-                    if ($host['address']==$ip || $host['address6']==$ip)
604
+                    if ($host['address'] == $ip || $host['address6'] == $ip)
605 605
                     {
606 606
                         //echo "Rule added \n";
607 607
                         $rules_ret[$rule_ret_key]=$rules_all[$key];
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
         $db_conn=$this->trapsDB->db_connect_trap();
626 626
         $sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
627 627
         if ($db_conn->query($sql) === false) {
628
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
628
+            $this->logging->log('Error in update query : '.$sql, WARN, '');
629 629
         }
630 630
     }
631 631
     
@@ -637,23 +637,23 @@  discard block
 block discarded – undo
637 637
      * @param string $display
638 638
      * @returnn bool true is service check was sent without error
639 639
      */
640
-    public function serviceCheckResult($host,$service,$state,$display)
640
+    public function serviceCheckResult($host, $service, $state, $display)
641 641
     {
642 642
         if ($this->apiUse === false)
643 643
         {
644
-            $send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
645
-                $host.';' .$service .';' . $state . ';'.$display;
646
-                $this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
644
+            $send='['.date('U').'] PROCESS_SERVICE_CHECK_RESULT;'.
645
+                $host.';'.$service.';'.$state.';'.$display;
646
+                $this->logging->log($send." : to : ".$this->icinga2cmd, INFO);
647 647
                 
648 648
                 // TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
649
-                exec('echo "'.$send.'" > ' .$this->icinga2cmd);
649
+                exec('echo "'.$send.'" > '.$this->icinga2cmd);
650 650
                 return true;
651 651
         }
652 652
         else
653 653
         {
654 654
             // Get perfdata if found
655 655
             $matches=array();
656
-            if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
656
+            if (preg_match('/(.*)\|(.*)/', $display, $matches) == 1)
657 657
             {
658 658
                 $display=$matches[1];
659 659
                 $perfdata=$matches[2];
@@ -663,17 +663,17 @@  discard block
 block discarded – undo
663 663
                 $perfdata='';
664 664
             }
665 665
             
666
-            $api = $this->getAPI();
666
+            $api=$this->getAPI();
667 667
             $api->setCredentials($this->apiUsername, $this->apiPassword);
668
-            list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
668
+            list($retcode, $retmessage)=$api->serviceCheckResult($host, $service, $state, $display, $perfdata);
669 669
             if ($retcode == false)
670 670
             {
671
-                $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
671
+                $this->logging->log("Error sending result : ".$retmessage, WARN, '');
672 672
                 return false;
673 673
             }
674 674
             else
675 675
             {
676
-                $this->logging->log( "Sent result : " .$retmessage,INFO );
676
+                $this->logging->log("Sent result : ".$retmessage, INFO);
677 677
                 return true;
678 678
             }
679 679
         }
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
     
682 682
     public function getHostByIP($ip)
683 683
     {
684
-        $api = $this->getAPI();
684
+        $api=$this->getAPI();
685 685
         $api->setCredentials($this->apiUsername, $this->apiPassword);
686 686
         return $api->getHostByIP($ip);
687 687
     }
@@ -694,35 +694,35 @@  discard block
 block discarded – undo
694 694
     protected function applyDisplay($display)
695 695
     {
696 696
         $matches=array();
697
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$display,$matches) == 1)
697
+        while (preg_match('/_OID\(([0-9\.\*]+)\)/', $display, $matches) == 1)
698 698
         {
699 699
             $oid=$matches[1];
700 700
             $found=0;
701 701
             // Test and transform regexp
702
-            $oidR = $this->ruleClass->regexp_eval($oid);
702
+            $oidR=$this->ruleClass->regexp_eval($oid);
703 703
             
704
-            foreach($this->trapDataExt as $val)
704
+            foreach ($this->trapDataExt as $val)
705 705
             {
706
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
706
+                if (preg_match("/^$oidR$/", $val->oid) == 1)
707 707
                 {
708
-                    $val->value=preg_replace('/"/','',$val->value);
708
+                    $val->value=preg_replace('/"/', '', $val->value);
709 709
                     $rep=0;
710
-                    $display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
711
-                    if ($rep==0)
710
+                    $display=preg_replace('/_OID\('.$oid.'\)/', $val->value, $display, -1, $rep);
711
+                    if ($rep == 0)
712 712
                     {
713
-                        $this->logging->log("Error in display",WARN,'');
713
+                        $this->logging->log("Error in display", WARN, '');
714 714
                         return $display;
715 715
                     }
716 716
                     $found=1;
717 717
                     break;
718 718
                 }
719 719
             }
720
-            if ($found==0)
720
+            if ($found == 0)
721 721
             {
722
-                $display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
723
-                if ($rep==0)
722
+                $display=preg_replace('/_OID\('.$oid.'\)/', '<not in trap>', $display, -1, $rep);
723
+                if ($rep == 0)
724 724
                 {
725
-                    $this->logging->log("Error in display",WARN,'');
725
+                    $this->logging->log("Error in display", WARN, '');
726 726
                     return $display;
727 727
                 }
728 728
             }
@@ -734,11 +734,11 @@  discard block
 block discarded – undo
734 734
      */
735 735
     public function applyRules()
736 736
     {
737
-        $rules = $this->getRules($this->trapData['source_ip'],$this->trapData['trap_oid']);
737
+        $rules=$this->getRules($this->trapData['source_ip'], $this->trapData['trap_oid']);
738 738
         
739
-        if ($rules===false || count($rules)==0)
739
+        if ($rules === false || count($rules) == 0)
740 740
         {
741
-            $this->logging->log('No rules found for this trap',INFO );
741
+            $this->logging->log('No rules found for this trap', INFO);
742 742
             $this->trapData['status']='unknown';
743 743
             $this->trapToDb=true;
744 744
             return;
@@ -753,59 +753,59 @@  discard block
 block discarded – undo
753 753
             $service_name=$rule['service_name'];
754 754
             
755 755
             $display=$this->applyDisplay($rule['display']);
756
-            $this->trapAction = ($this->trapAction==null)? '' : $this->trapAction . ', ';
756
+            $this->trapAction=($this->trapAction == null) ? '' : $this->trapAction.', ';
757 757
             try
758 758
             {
759
-                $this->logging->log('Rule to eval : '.$rule['rule'],INFO );
760
-                $evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt) ;
759
+                $this->logging->log('Rule to eval : '.$rule['rule'], INFO);
760
+                $evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt);
761 761
                 //->eval_rule($rule['rule']);
762 762
                 
763 763
                 if ($evalr == true)
764 764
                 {
765 765
                     //$this->logging->log('rules OOK: '.print_r($rule),INFO );
766 766
                     $action=$rule['action_match'];
767
-                    $this->logging->log('action OK : '.$action,INFO );
767
+                    $this->logging->log('action OK : '.$action, INFO);
768 768
                     if ($action >= 0)
769 769
                     {
770
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
770
+                        if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
771 771
                         {
772 772
                             $this->trapAction.='Error sending status : check cmd/API';
773 773
                         }
774 774
                         else
775 775
                         {
776
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
776
+                            $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
777 777
                             $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
778 778
                         }
779 779
                     }
780 780
                     else
781 781
                     {
782
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
782
+                        $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
783 783
                     }
784
-                    $this->trapToDb=($action==-2)?false:true;
784
+                    $this->trapToDb=($action == -2) ?false:true;
785 785
                 }
786 786
                 else
787 787
                 {
788 788
                     //$this->logging->log('rules KOO : '.print_r($rule),INFO );
789 789
                     
790 790
                     $action=$rule['action_nomatch'];
791
-                    $this->logging->log('action NOK : '.$action,INFO );
791
+                    $this->logging->log('action NOK : '.$action, INFO);
792 792
                     if ($action >= 0)
793 793
                     {
794
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
794
+                        if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
795 795
                         {
796 796
                             $this->trapAction.='Error sending status : check cmd/API';
797 797
                         }
798 798
                         else
799 799
                         {
800
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
800
+                            $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
801 801
                             $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
802 802
                         }
803 803
                     }
804 804
                     else
805 805
                     {
806
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
806
+                        $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
807 807
                     }
808
-                    $this->trapToDb=($action==-2)?false:true;
808
+                    $this->trapToDb=($action == -2) ?false:true;
809 809
                 }
810 810
                 // Put name in source_name
811 811
                 if (!isset($this->trapData['source_name']))
@@ -814,7 +814,7 @@  discard block
 block discarded – undo
814 814
                 }
815 815
                 else
816 816
                 {
817
-                    if (!preg_match('/'.$rule['host_name'].'/',$this->trapData['source_name']))
817
+                    if (!preg_match('/'.$rule['host_name'].'/', $this->trapData['source_name']))
818 818
                     { // only add if not present
819 819
                         $this->trapData['source_name'].=','.$rule['host_name'];
820 820
                     }
@@ -822,13 +822,13 @@  discard block
 block discarded – undo
822 822
             }
823 823
             catch (Exception $e)
824 824
             {
825
-                $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
825
+                $this->logging->log('Error in rule eval : '.$e->getMessage(), WARN, '');
826 826
                 $this->trapAction.=' ERR : '.$e->getMessage();
827 827
                 $this->trapData['status']='error';
828 828
             }
829 829
             
830 830
         }
831
-        if ($this->trapData['status']=='error')
831
+        if ($this->trapData['status'] == 'error')
832 832
         {
833 833
             $this->trapToDb=true; // Always put errors in DB for the use can see
834 834
         }
@@ -844,13 +844,13 @@  discard block
 block discarded – undo
844 844
     public function add_rule_final($time)
845 845
     {
846 846
         $db_conn=$this->trapsDB->db_connect_trap();
847
-        if ($this->trapAction==null)
847
+        if ($this->trapAction == null)
848 848
         {
849 849
             $this->trapAction='No action';
850 850
         }
851 851
         $sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trapAction."'  WHERE (id = '".$this->trapId."');";
852 852
         if ($db_conn->query($sql) === false) {
853
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
853
+            $this->logging->log('Error in update query : '.$sql, WARN, '');
854 854
         }
855 855
     }
856 856
     
@@ -875,12 +875,12 @@  discard block
 block discarded – undo
875 875
                                 WHERE s.current_state != 0;";
876 876
             $db_conn=$this->trapsDB->db_connect_ido();
877 877
             if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
878
-                $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
878
+                $this->logging->log('No result in query : '.$sql_query, ERROR, '');
879 879
                 return 0;
880 880
             }
881 881
             $services=$services_db->fetchAll();
882
-        }else{
883
-            $api = $this->getAPI();
882
+        } else {
883
+            $api=$this->getAPI();
884 884
             $api->setCredentials($this->apiUsername, $this->apiPassword);
885 885
             $services=$api->getNOKservice();
886 886
         }
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
         $sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
890 890
         $db_conn2=$this->trapsDB->db_connect_trap();
891 891
         if (($rules_db=$db_conn2->query($sql_query)) === false) {
892
-            $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
892
+            $this->logging->log('No result in query : '.$sql_query, ERROR, '');
893 893
             return 0;
894 894
         }
895 895
         $rules=$rules_db->fetchAll();
@@ -899,20 +899,20 @@  discard block
 block discarded – undo
899 899
         $numreset=0;
900 900
         foreach ($rules as $rule)
901 901
         {
902
-            if( is_object( $services ) ) $services=(array)$services;
902
+            if (is_object($services)) $services=(array) $services;
903 903
             foreach ($services as $service)
904 904
             {
905 905
                 if ($service['name'] == $rule['service_name'] &&
906 906
                     $service['host_name'] == $rule['host_name'] &&
907 907
                     ($service['last_check'] + $rule['revert_ok']) < $now)
908 908
                 {
909
-                    $this->serviceCheckResult($service['host_name'],$service['name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
909
+                    $this->serviceCheckResult($service['host_name'], $service['name'], 0, 'Reset service to OK after '.$rule['revert_ok'].' seconds');
910 910
                     $numreset++;
911 911
                 }
912 912
             }
913 913
         }
914 914
         echo "\n";
915
-        echo $numreset . " service(s) reset to OK\n";
915
+        echo $numreset." service(s) reset to OK\n";
916 916
         return 0;
917 917
         
918 918
     }
Please login to merge, or discard this patch.
Braces   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -98,8 +98,7 @@  discard block
 block discarded – undo
98 98
         {
99 99
             $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
100 100
             $this->logSetup=true;
101
-        }
102
-        else
101
+        } else
103 102
         {
104 103
             $this->logSetup=false;
105 104
         }
@@ -129,7 +128,10 @@  discard block
 block discarded – undo
129 128
         $this->getDatabaseOptions(); // Get options in database
130 129
         
131 130
         // Setup API
132
-        if ($this->apiUse === true) $this->getAPI(); // Setup API
131
+        if ($this->apiUse === true) {
132
+        	$this->getAPI();
133
+        }
134
+        // Setup API
133 135
         
134 136
         // Setup MIB
135 137
         $this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
@@ -238,8 +240,7 @@  discard block
 block discarded – undo
238 240
         {
239 241
             $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
240 242
             $this->logging->log('Error parsing IP : '.$IP,ERROR,'');
241
-        }
242
-        else
243
+        } else
243 244
         {
244 245
             $this->trapData['source_ip']=$matches[1];
245 246
             $this->trapData['destination_ip']=$matches[3];
@@ -322,10 +323,10 @@  discard block
 block discarded – undo
322 323
         $this->logging->log('SQL query : '.$sql,DEBUG );
323 324
         if (($ret_code=$db_conn->query($sql)) === false) {
324 325
             $this->logging->log('No result in query : ' . $sql,ERROR,'');
325
-        }
326
-        else {
327
-            if (($name=$ret_code->fetch()) !== false)
328
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
326
+        } else {
327
+            if (($name=$ret_code->fetch()) !== false) {
328
+                            return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
329
+            }
329 330
         }
330 331
         
331 332
         // Also check if it is an instance of OID
@@ -335,10 +336,10 @@  discard block
 block discarded – undo
335 336
         $this->logging->log('SQL query : '.$sql,DEBUG );
336 337
         if (($ret_code=$db_conn->query($sql)) === false) {
337 338
             $this->logging->log('No result in query : ' . $sql,ERROR,'');
338
-        }
339
-        else {
340
-            if (($name=$ret_code->fetch()) !== false)
341
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
339
+        } else {
340
+            if (($name=$ret_code->fetch()) !== false) {
341
+                            return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
342
+            }
342 343
         }
343 344
         
344 345
         // Try to get oid name from snmptranslate
@@ -437,7 +438,9 @@  discard block
 block discarded – undo
437 438
                 }
438 439
                 
439 440
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
440
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
441
+                if ($inserted_id==false) {
442
+                	throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
443
+                }
441 444
                 $this->trapId=$inserted_id;
442 445
                 break;
443 446
             default:
@@ -453,7 +456,9 @@  discard block
 block discarded – undo
453 456
     {
454 457
         
455 458
         // If action is ignore -> don't send t DB
456
-        if ($this->trapToDb === false) return;
459
+        if ($this->trapToDb === false) {
460
+        	return;
461
+        }
457 462
         
458 463
         
459 464
         $db_conn=$this->trapsDB->db_connect_trap();
@@ -510,7 +515,9 @@  discard block
 block discarded – undo
510 515
                 }
511 516
                 
512 517
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
513
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
518
+                if ($inserted_id==false) {
519
+                	throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
520
+                }
514 521
                 $this->trapId=$inserted_id;
515 522
                 break;
516 523
             default:
@@ -591,7 +598,7 @@  discard block
 block discarded – undo
591 598
                         continue;
592 599
                     }
593 600
                     $grouphosts=$ret_code2->fetchAll();
594
-                }else{
601
+                } else{
595 602
                     $api = $this->getAPI();
596 603
                     $api->setCredentials($this->apiUsername, $this->apiPassword);
597 604
                     $grouphosts=$api->getHostsIPByHostGroup($rule['host_group_name']);
@@ -599,7 +606,9 @@  discard block
 block discarded – undo
599 606
                 //echo "rule grp :\n";print_r($grouphosts);echo "\n";
600 607
                 foreach ( $grouphosts as $host)
601 608
                 {
602
-                    if( is_object( $host ) ) $host=(array)$host;
609
+                    if( is_object( $host ) ) {
610
+                    	$host=(array)$host;
611
+                    }
603 612
                     //echo $host['address']."\n";
604 613
                     if ($host['address']==$ip || $host['address6']==$ip)
605 614
                     {
@@ -648,8 +657,7 @@  discard block
 block discarded – undo
648 657
                 // TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
649 658
                 exec('echo "'.$send.'" > ' .$this->icinga2cmd);
650 659
                 return true;
651
-        }
652
-        else
660
+        } else
653 661
         {
654 662
             // Get perfdata if found
655 663
             $matches=array();
@@ -657,8 +665,7 @@  discard block
 block discarded – undo
657 665
             {
658 666
                 $display=$matches[1];
659 667
                 $perfdata=$matches[2];
660
-            }
661
-            else
668
+            } else
662 669
             {
663 670
                 $perfdata='';
664 671
             }
@@ -670,8 +677,7 @@  discard block
 block discarded – undo
670 677
             {
671 678
                 $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
672 679
                 return false;
673
-            }
674
-            else
680
+            } else
675 681
             {
676 682
                 $this->logging->log( "Sent result : " .$retmessage,INFO );
677 683
                 return true;
@@ -770,20 +776,17 @@  discard block
 block discarded – undo
770 776
                         if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
771 777
                         {
772 778
                             $this->trapAction.='Error sending status : check cmd/API';
773
-                        }
774
-                        else
779
+                        } else
775 780
                         {
776 781
                             $this->add_rule_match($rule['id'],$rule['num_match']+1);
777 782
                             $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
778 783
                         }
779
-                    }
780
-                    else
784
+                    } else
781 785
                     {
782 786
                         $this->add_rule_match($rule['id'],$rule['num_match']+1);
783 787
                     }
784 788
                     $this->trapToDb=($action==-2)?false:true;
785
-                }
786
-                else
789
+                } else
787 790
                 {
788 791
                     //$this->logging->log('rules KOO : '.print_r($rule),INFO );
789 792
                     
@@ -794,14 +797,12 @@  discard block
 block discarded – undo
794 797
                         if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
795 798
                         {
796 799
                             $this->trapAction.='Error sending status : check cmd/API';
797
-                        }
798
-                        else
800
+                        } else
799 801
                         {
800 802
                             $this->add_rule_match($rule['id'],$rule['num_match']+1);
801 803
                             $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
802 804
                         }
803
-                    }
804
-                    else
805
+                    } else
805 806
                     {
806 807
                         $this->add_rule_match($rule['id'],$rule['num_match']+1);
807 808
                     }
@@ -811,16 +812,14 @@  discard block
 block discarded – undo
811 812
                 if (!isset($this->trapData['source_name']))
812 813
                 {
813 814
                     $this->trapData['source_name']=$rule['host_name'];
814
-                }
815
-                else
815
+                } else
816 816
                 {
817 817
                     if (!preg_match('/'.$rule['host_name'].'/',$this->trapData['source_name']))
818 818
                     { // only add if not present
819 819
                         $this->trapData['source_name'].=','.$rule['host_name'];
820 820
                     }
821 821
                 }
822
-            }
823
-            catch (Exception $e)
822
+            } catch (Exception $e)
824 823
             {
825 824
                 $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
826 825
                 $this->trapAction.=' ERR : '.$e->getMessage();
@@ -831,8 +830,7 @@  discard block
 block discarded – undo
831 830
         if ($this->trapData['status']=='error')
832 831
         {
833 832
             $this->trapToDb=true; // Always put errors in DB for the use can see
834
-        }
835
-        else
833
+        } else
836 834
         {
837 835
             $this->trapData['status']='done';
838 836
         }
@@ -879,7 +877,7 @@  discard block
 block discarded – undo
879 877
                 return 0;
880 878
             }
881 879
             $services=$services_db->fetchAll();
882
-        }else{
880
+        } else{
883 881
             $api = $this->getAPI();
884 882
             $api->setCredentials($this->apiUsername, $this->apiPassword);
885 883
             $services=$api->getNOKservice();
@@ -899,7 +897,9 @@  discard block
 block discarded – undo
899 897
         $numreset=0;
900 898
         foreach ($rules as $rule)
901 899
         {
902
-            if( is_object( $services ) ) $services=(array)$services;
900
+            if( is_object( $services ) ) {
901
+            	$services=(array)$services;
902
+            }
903 903
             foreach ($services as $service)
904 904
             {
905 905
                 if ($service['name'] == $rule['service_name'] &&
Please login to merge, or discard this patch.