Passed
Branch master (782f23)
by Patrick
02:09
created
application/controllers/HelperController.php 1 patch
Spacing   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -18,14 +18,14 @@  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
 
25 25
 		$hosts=$this->getUIDatabase()->getHostByIP($hostFilter);
26 26
 		foreach ($hosts as $val)
27 27
 		{
28
-			array_push($retHosts['hosts'],$val->name);
28
+			array_push($retHosts['hosts'], $val->name);
29 29
 		}
30 30
 		
31 31
 		$this->_helper->json($retHosts);
@@ -38,14 +38,14 @@  discard block
 block discarded – undo
38 38
 	{
39 39
 		$postData=$this->getRequest()->getPost();
40 40
 		
41
-		$hostFilter = $this->checkPostVar($postData, 'hostFilter', '.*');
41
+		$hostFilter=$this->checkPostVar($postData, 'hostFilter', '.*');
42 42
 		
43
-		$retHosts=array('status'=>'OK','hosts' => array());
43
+		$retHosts=array('status'=>'OK', 'hosts' => array());
44 44
 
45 45
 		$hosts=$this->getUIDatabase()->getHostGroupByName($hostFilter);
46 46
 		foreach ($hosts as $val)
47 47
 		{
48
-			array_push($retHosts['hosts'],$val->name);
48
+			array_push($retHosts['hosts'], $val->name);
49 49
 		}
50 50
 		
51 51
 		$this->_helper->json($retHosts);
@@ -68,31 +68,31 @@  discard block
 block discarded – undo
68 68
 		}
69 69
 		else
70 70
 		{
71
-			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
71
+			$this->_helper->json(array('status'=>'No Hosts', 'hostid' => -1));
72 72
 			return;
73 73
 		}
74 74
 		
75 75
 		$hostArray=$this->getUIDatabase()->getHostByName($host);
76 76
 		if (count($hostArray) > 1)
77 77
 		{	
78
-			$this->_helper->json(array('status'=>'More than one host matches','hostid' => -1));
78
+			$this->_helper->json(array('status'=>'More than one host matches', 'hostid' => -1));
79 79
 			return;
80 80
 		}
81 81
 		else if (count($hostArray) == 0)
82 82
 		{
83
-			$this->_helper->json(array('status'=>'No host matches','hostid' => -1));
83
+			$this->_helper->json(array('status'=>'No host matches', 'hostid' => -1));
84 84
 			return;
85 85
 		}
86 86
 		$services=$this->getUIDatabase()->getServicesByHostid($hostArray[0]->id);
87 87
 		if (count($services) < 1)
88 88
 		{
89
-			$this->_helper->json(array('status'=>'No services found for host','hostid' => $hostArray[0]->id));
89
+			$this->_helper->json(array('status'=>'No services found for host', 'hostid' => $hostArray[0]->id));
90 90
 			return;
91 91
 		}
92
-		$retServices=array('status'=>'OK','services' => array(),'hostid' => $hostArray[0]->id);
92
+		$retServices=array('status'=>'OK', 'services' => array(), 'hostid' => $hostArray[0]->id);
93 93
 		foreach ($services as $val)
94 94
 		{
95
-			array_push($retServices['services'],array($val->id , $val->name));
95
+			array_push($retServices['services'], array($val->id, $val->name));
96 96
 		}
97 97
 		$this->_helper->json($retServices);
98 98
 	}
@@ -107,26 +107,26 @@  discard block
 block discarded – undo
107 107
 	{
108 108
 		$postData=$this->getRequest()->getPost();
109 109
 		
110
-		$host = $this->checkPostVar($postData, 'host', '.+');
110
+		$host=$this->checkPostVar($postData, 'host', '.+');
111 111
 		
112 112
 		$hostArray=$this->getUIDatabase()->getHostGroupByName($host);
113 113
 		if (count($hostArray) > 1)
114 114
 		{	
115
-			$this->_helper->json(array('status'=>'More than one hostgroup matches','hostid' => -1));
115
+			$this->_helper->json(array('status'=>'More than one hostgroup matches', 'hostid' => -1));
116 116
 			return;
117 117
 		}
118 118
 		else if (count($hostArray) == 0)
119 119
 		{
120
-			$this->_helper->json(array('status'=>'No hostgroup matches','hostid' => -1));
120
+			$this->_helper->json(array('status'=>'No hostgroup matches', 'hostid' => -1));
121 121
 			return;
122 122
 		}
123 123
 		$services=$this->getUIDatabase()->getServicesByHostGroupid($hostArray[0]->id);
124 124
 		if (count($services) < 1)
125 125
 		{
126
-			$this->_helper->json(array('status'=>'No services found for hostgroup','hostid' => $hostArray[0]->id));
126
+			$this->_helper->json(array('status'=>'No services found for hostgroup', 'hostid' => $hostArray[0]->id));
127 127
 			return;
128 128
 		}
129
-		$retServices=array('status'=>'OK','services' => $services,'hostid' => $hostArray[0]->id);
129
+		$retServices=array('status'=>'OK', 'services' => $services, 'hostid' => $hostArray[0]->id);
130 130
 		
131 131
 		$this->_helper->json($retServices);
132 132
 	}
@@ -140,12 +140,12 @@  discard block
 block discarded – undo
140 140
 	{
141 141
 		$postData=$this->getRequest()->getPost();
142 142
 		
143
-		$mib = $this->checkPostVar($postData, 'mib', '.*');
143
+		$mib=$this->checkPostVar($postData, 'mib', '.*');
144 144
 
145 145
 		try
146 146
 		{
147 147
 			$traplist=$this->getMIB()->getTrapList($mib);
148
-			$retTraps=array('status'=>'OK','traps' => $traplist);
148
+			$retTraps=array('status'=>'OK', 'traps' => $traplist);
149 149
 		} 
150 150
 		catch (Exception $e) 
151 151
 		{ 
@@ -163,12 +163,12 @@  discard block
 block discarded – undo
163 163
 	{
164 164
 		$postData=$this->getRequest()->getPost();
165 165
 		
166
-		$trap = $this->checkPostVar($postData, 'trap', '.*');
166
+		$trap=$this->checkPostVar($postData, 'trap', '.*');
167 167
 		
168 168
 		try
169 169
 		{
170 170
 			$objectlist=$this->getMIB()->getObjectList($trap);
171
-			$retObjects=array('status'=>'OK','objects' => $objectlist);
171
+			$retObjects=array('status'=>'OK', 'objects' => $objectlist);
172 172
 		} 
173 173
 		catch (Exception $e) 
174 174
 		{ 
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 	{
203 203
 		$postData=$this->getRequest()->getPost();
204 204
 		
205
-		$oid = $this->checkPostVar($postData, 'oid', '.*');
205
+		$oid=$this->checkPostVar($postData, 'oid', '.*');
206 206
 		
207 207
 		// Try to get oid name from snmptranslate
208 208
 		if (($object=$this->getMIB()->translateOID($oid)) == null)
@@ -235,20 +235,20 @@  discard block
 block discarded – undo
235 235
 		
236 236
 		$postData=$this->getRequest()->getPost();
237 237
 		
238
-		$days = $this->checkPostVar($postData, 'days', '^[0-9]+$');
238
+		$days=$this->checkPostVar($postData, 'days', '^[0-9]+$');
239 239
 		$days=intval($days);
240 240
 
241
-		$action = $this->checkPostVar($postData, 'action', 'save|execute');
241
+		$action=$this->checkPostVar($postData, 'action', 'save|execute');
242 242
 		
243 243
 		if ($action == 'save')
244 244
 		{
245 245
 			try
246 246
 			{
247
-			    $this->getUIDatabase()->setDBConfigValue('db_remove_days',$days);
247
+			    $this->getUIDatabase()->setDBConfigValue('db_remove_days', $days);
248 248
 			}
249 249
 			catch (Exception $e)
250 250
 			{
251
-				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
251
+				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage()));
252 252
 				return;
253 253
 			}
254 254
 			$this->_helper->json(array('status'=>'OK'));
@@ -258,16 +258,16 @@  discard block
 block discarded – undo
258 258
 		{
259 259
 			try
260 260
 			{
261
-				require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
261
+				require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
262 262
 				$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
263 263
 				$debug_level=4;
264
-				$trap = new Trap($icingaweb2_etc);
265
-				$trap->setLogging($debug_level,'syslog');
264
+				$trap=new Trap($icingaweb2_etc);
265
+				$trap->setLogging($debug_level, 'syslog');
266 266
 				$trap->eraseOldTraps($days);
267 267
 			}
268 268
 			catch (Exception $e)
269 269
 			{
270
-				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage() ));
270
+				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage()));
271 271
 				return;
272 272
 			}			
273 273
 			$this->_helper->json(array('status'=>'OK'));
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 	{
286 286
 		$postData=$this->getRequest()->getPost();
287 287
 		
288
-		$destination = $this->checkPostVar($postData, 'destination', '.*');
288
+		$destination=$this->checkPostVar($postData, 'destination', '.*');
289 289
 		$logDest=$this->getModuleConfig()->getLogDestinations();
290 290
 		if (!isset($logDest[$destination]))
291 291
 		{
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
 		if (isset($postData['file']))
297 297
 		{ 
298 298
 			$file=$postData['file'];
299
-			$fileHandler=@fopen($file,'w');
299
+			$fileHandler=@fopen($file, 'w');
300 300
 			if ($fileHandler == false)
301 301
 			{   // File os note writabe / cannot create
302 302
 			    $this->_helper->json(array('status'=>'File not writable :  '.$file));
@@ -316,17 +316,17 @@  discard block
 block discarded – undo
316 316
 			}
317 317
 		}
318 318
 
319
-		$level = $this->checkPostVar($postData, 'level', '[0-9]');
319
+		$level=$this->checkPostVar($postData, 'level', '[0-9]');
320 320
 				
321 321
 		try
322 322
 		{
323
-		    $this->getUIDatabase()->setDBConfigValue('log_destination',$destination);
324
-		    $this->getUIDatabase()->setDBConfigValue('log_file',$file);
325
-		    $this->getUIDatabase()->setDBConfigValue('log_level',$level);
323
+		    $this->getUIDatabase()->setDBConfigValue('log_destination', $destination);
324
+		    $this->getUIDatabase()->setDBConfigValue('log_file', $file);
325
+		    $this->getUIDatabase()->setDBConfigValue('log_level', $level);
326 326
 		}
327 327
 		catch (Exception $e)
328 328
 		{
329
-			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
329
+			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage()));
330 330
 			return;
331 331
 		}
332 332
 		$this->_helper->json(array('status'=>'OK'));
@@ -344,29 +344,29 @@  discard block
 block discarded – undo
344 344
 	    
345 345
 	    $postData=$this->getRequest()->getPost();
346 346
 	   
347
-	    $rule = $this->checkPostVar($postData, 'rule', '.*');
347
+	    $rule=$this->checkPostVar($postData, 'rule', '.*');
348 348
 
349
-	    $action = $this->checkPostVar($postData, 'action', 'evaluate');
349
+	    $action=$this->checkPostVar($postData, 'action', 'evaluate');
350 350
 
351 351
 	    if ($action == 'evaluate')
352 352
 	    {
353 353
 	        try
354 354
 	        {
355
-	            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
355
+	            require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
356 356
 	            $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
357
-	            $trap = new Trap($icingaweb2_etc);
357
+	            $trap=new Trap($icingaweb2_etc);
358 358
 	            // Cleanup spaces before eval
359 359
 	            $rule=$trap->ruleClass->eval_cleanup($rule);
360 360
 	            // Eval
361 361
 	            $item=0;
362
-	            $rule=$trap->ruleClass->evaluation($rule,$item);
362
+	            $rule=$trap->ruleClass->evaluation($rule, $item);
363 363
 	        }
364 364
 	        catch (Exception $e)
365 365
 	        {
366
-	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
366
+	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage()));
367 367
 	            return;
368 368
 	        }
369
-	        $return=($rule==true)?'true':'false';
369
+	        $return=($rule == true) ? 'true' : 'false';
370 370
 	        $this->_helper->json(array('status'=>'OK', 'message' => $return));
371 371
 	    }
372 372
 	    
@@ -381,15 +381,15 @@  discard block
 block discarded – undo
381 381
 	{
382 382
 	    $postData=$this->getRequest()->getPost();
383 383
 	    
384
-	    $pluginName = $this->checkPostVar($postData, 'name', '.*');
384
+	    $pluginName=$this->checkPostVar($postData, 'name', '.*');
385 385
 	    
386
-	    $action = $this->checkPostVar($postData, 'action', 'enable|disable');
386
+	    $action=$this->checkPostVar($postData, 'action', 'enable|disable');
387 387
 	    
388 388
         try
389 389
         {
390
-            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
390
+            require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
391 391
             $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
392
-            $trap = new Trap($icingaweb2_etc);
392
+            $trap=new Trap($icingaweb2_etc);
393 393
             // Enable plugin.
394 394
             $action=($action == 'enable') ? true : false;
395 395
             $retVal=$trap->pluginClass->enablePlugin($pluginName, $action);
@@ -397,7 +397,7 @@  discard block
 block discarded – undo
397 397
         }
398 398
         catch (Exception $e)
399 399
         {
400
-            $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
400
+            $this->_helper->json(array('status'=>'Action error : '.$e->getMessage()));
401 401
             return;
402 402
         }
403 403
         if ($retVal === true)
@@ -419,45 +419,45 @@  discard block
 block discarded – undo
419 419
 	{
420 420
 	    $postData=$this->getRequest()->getPost();
421 421
 	    
422
-	    $functionString = $this->checkPostVar($postData, 'function', '.*');
422
+	    $functionString=$this->checkPostVar($postData, 'function', '.*');
423 423
 	    
424 424
 	    $this->checkPostVar($postData, 'action', 'evaluate');
425 425
 	    
426 426
 	    // Only one action possible for now, no tests on action.
427 427
 	    try
428 428
 	    {
429
-	        require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
429
+	        require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
430 430
 	        $icingaweb2Etc=$this->Config()->get('config', 'icingaweb2_etc');
431
-	        $trap = new Trap($icingaweb2Etc);
431
+	        $trap=new Trap($icingaweb2Etc);
432 432
 	        // load all plugins in case tested function is not enabled.
433 433
 	        $trap->pluginClass->registerAllPlugins(false);
434 434
 	        // Clean all spaces
435
-	        $functionString = $trap->ruleClass->eval_cleanup($functionString);
435
+	        $functionString=$trap->ruleClass->eval_cleanup($functionString);
436 436
 	        // Eval functions
437
-	        $result = $trap->pluginClass->evaluateFunctionString($functionString);	        
437
+	        $result=$trap->pluginClass->evaluateFunctionString($functionString);	        
438 438
 	    }
439 439
 	    catch (Exception $e)
440 440
 	    {
441
-	        $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
441
+	        $this->_helper->json(array('status'=>'Action error : '.$e->getMessage()));
442 442
 	        return;
443 443
 	    }
444 444
 	    
445
-        $result = ($result === true)?'True':'False';
446
-        $this->_helper->json(array('status'=>'OK','message' => $result));
445
+        $result=($result === true) ? 'True' : 'False';
446
+        $this->_helper->json(array('status'=>'OK', 'message' => $result));
447 447
 	}
448 448
 
449 449
     /**************   Utilities **********************/
450 450
 
451
-	private function checkPostVar(array $postData,string $postVar, string $validRegexp) : string
451
+	private function checkPostVar(array $postData, string $postVar, string $validRegexp) : string
452 452
 	{
453 453
 	    if (!isset ($postData[$postVar]))
454 454
 	    {
455
-	        $this->_helper->json(array('status'=>'No ' . $postVar));
455
+	        $this->_helper->json(array('status'=>'No '.$postVar));
456 456
 	        return '';
457 457
 	    }
458 458
 	    if (preg_match('/'.$validRegexp.'/', $postData[$postVar]) != 1)
459 459
 	    {
460
-	        $this->_helper->json(array('status'=>'Unknown ' . $postVar . ' value '.$postData[$postVar]));
460
+	        $this->_helper->json(array('status'=>'Unknown '.$postVar.' value '.$postData[$postVar]));
461 461
 	        return '';
462 462
 	    }
463 463
 	    return $postData[$postVar];
Please login to merge, or discard this patch.
application/controllers/HandlerController.php 3 patches
Indentation   +250 added lines, -251 removed lines patch added patch discarded remove patch
@@ -11,13 +11,12 @@  discard block
 block discarded – undo
11 11
 
12 12
 //use Icinga\Web\Form as Form;
13 13
 /** Rules management
14
-
15
-*/
14
+ */
16 15
 class HandlerController extends TrapsController
17 16
 {
18 17
 
19 18
 	/** index : list existing rules 
20
-	*/
19
+	 */
21 20
 	public function indexAction()
22 21
 	{	
23 22
 		$this->checkReadPermission();
@@ -41,22 +40,22 @@  discard block
 block discarded – undo
41 40
 	 */
42 41
 	public function testruleAction()
43 42
 	{
44
-	    $this->checkReadPermission();
45
-	    $this->getTabs()->add('get',array(
46
-	        'active'	=> true,
47
-	        'label'		=> $this->translate('Test Rule'),
48
-	        'url'		=> Url::fromRequest()
49
-	    ));
43
+		$this->checkReadPermission();
44
+		$this->getTabs()->add('get',array(
45
+			'active'	=> true,
46
+			'label'		=> $this->translate('Test Rule'),
47
+			'url'		=> Url::fromRequest()
48
+		));
50 49
 	    
51 50
 
52
-	    if ($this->params->get('rule') !== null) 
53
-	    {
54
-	        $this->view->rule= $this->params->get('rule');
55
-	    }
56
-	    else
57
-	    {
58
-	        $this->view->rule='';
59
-	    }
51
+		if ($this->params->get('rule') !== null) 
52
+		{
53
+			$this->view->rule= $this->params->get('rule');
54
+		}
55
+		else
56
+		{
57
+			$this->view->rule='';
58
+		}
60 59
 	}
61 60
 	
62 61
 	/**
@@ -64,31 +63,31 @@  discard block
 block discarded – undo
64 63
 	 */
65 64
 	private function add_setup_vars()
66 65
 	{
67
-	    // variables to send to view
68
-	    $this->view->hostlist=array(); // host list to input datalist
69
-	    $this->view->hostname=''; // Host name in input text
70
-	    $this->view->serviceGet=false; // Set to true to get list of service if only one host set
71
-	    $this->view->serviceSet=null; // Select service in services select (must have serviceGet=true).
72
-	    $this->view->mainoid=''; // Trap OID
73
-	    $this->view->mib=''; // Trap mib
74
-	    $this->view->name=''; // Trap name
75
-	    $this->view->trapListForMIB=array(); // Trap list if mib exists for trap
76
-	    $this->view->objectList=array(); // objects sent with trap
77
-	    $this->view->display=''; // Initial display
78
-	    $this->view->rule=''; // rule display
79
-	    $this->view->revertOK=''; // revert OK in seconds
80
-	    $this->view->hostid=-1; // normally set by javascript serviceGet()
81
-	    $this->view->ruleid=-1; // Rule id in DB for update & delete
82
-	    $this->view->setToUpdate=false; // set form as update form
83
-	    $this->view->setRuleMatch=-1; // set action on rule match (default nothing)
84
-	    $this->view->setRuleNoMatch=-1; // set action on rule no match (default nothing)
66
+		// variables to send to view
67
+		$this->view->hostlist=array(); // host list to input datalist
68
+		$this->view->hostname=''; // Host name in input text
69
+		$this->view->serviceGet=false; // Set to true to get list of service if only one host set
70
+		$this->view->serviceSet=null; // Select service in services select (must have serviceGet=true).
71
+		$this->view->mainoid=''; // Trap OID
72
+		$this->view->mib=''; // Trap mib
73
+		$this->view->name=''; // Trap name
74
+		$this->view->trapListForMIB=array(); // Trap list if mib exists for trap
75
+		$this->view->objectList=array(); // objects sent with trap
76
+		$this->view->display=''; // Initial display
77
+		$this->view->rule=''; // rule display
78
+		$this->view->revertOK=''; // revert OK in seconds
79
+		$this->view->hostid=-1; // normally set by javascript serviceGet()
80
+		$this->view->ruleid=-1; // Rule id in DB for update & delete
81
+		$this->view->setToUpdate=false; // set form as update form
82
+		$this->view->setRuleMatch=-1; // set action on rule match (default nothing)
83
+		$this->view->setRuleNoMatch=-1; // set action on rule no match (default nothing)
85 84
 	    
86
-	    $this->view->selectGroup=false; // Select by group if true
87
-	    $this->view->hostgroupid=-1; // host group id
88
-	    $this->view->serviceGroupGet=false; // Get list of service for group (set serviceSet to select one)
85
+		$this->view->selectGroup=false; // Select by group if true
86
+		$this->view->hostgroupid=-1; // host group id
87
+		$this->view->serviceGroupGet=false; // Get list of service for group (set serviceSet to select one)
89 88
 	    
90
-	    $this->view->modifier=null;
91
-	    $this->view->modified=null;
89
+		$this->view->modifier=null;
90
+		$this->view->modified=null;
92 91
 	}
93 92
 	
94 93
 	/**
@@ -97,102 +96,102 @@  discard block
 block discarded – undo
97 96
 	 */
98 97
 	private function add_from_existing($trapid)
99 98
 	{
100
-	    /********** Setup from existing trap ***************/
101
-	    // Get the full trap info
102
-	    $trapDetail=$this->getTrapDetail($trapid);
99
+		/********** Setup from existing trap ***************/
100
+		// Get the full trap info
101
+		$trapDetail=$this->getTrapDetail($trapid);
103 102
 	    
104
-	    $hostfilter=$trapDetail->source_ip;
103
+		$hostfilter=$trapDetail->source_ip;
105 104
 	    
106
-	    // Get host
107
-	    try
108
-	    {
109
-	        $hosts=$this->getUIDatabase()->getHostByIP($hostfilter);
110
-	    }
111
-	    catch (Exception $e)
112
-	    {
113
-	        $this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
114
-	    }
105
+		// Get host
106
+		try
107
+		{
108
+			$hosts=$this->getUIDatabase()->getHostByIP($hostfilter);
109
+		}
110
+		catch (Exception $e)
111
+		{
112
+			$this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
113
+		}
115 114
 	    
116 115
 	    
117
-	    // if one unique host found -> put id text input
118
-	    if (count($hosts)==1) {
119
-	        $this->view->hostname=$hosts[0]->name;
120
-	        //$hostid=$hosts[0]->id;
121
-	        // Tell JS to get services when page is loaded
122
-	        $this->view->serviceGet=true;
116
+		// if one unique host found -> put id text input
117
+		if (count($hosts)==1) {
118
+			$this->view->hostname=$hosts[0]->name;
119
+			//$hostid=$hosts[0]->id;
120
+			// Tell JS to get services when page is loaded
121
+			$this->view->serviceGet=true;
123 122
 	        
124
-	    }
125
-	    else
126
-	    {
127
-	        foreach($hosts as $key=>$val)
128
-	        {
129
-	            array_push($this->view->hostlist,$hosts[$key]->name);
130
-	        }
131
-	    }
123
+		}
124
+		else
125
+		{
126
+			foreach($hosts as $key=>$val)
127
+			{
128
+				array_push($this->view->hostlist,$hosts[$key]->name);
129
+			}
130
+		}
132 131
 	    
133
-	    // set up trap oid and objects received by the trap
132
+		// set up trap oid and objects received by the trap
134 133
 	    
135
-	    $this->view->mainoid=$trapDetail->trap_oid;
136
-	    if ($trapDetail->trap_name_mib != null)
137
-	    {
138
-	        $this->view->mib=$trapDetail->trap_name_mib;
139
-	        $this->view->name=$trapDetail->trap_name;
140
-	        $this->view->trapListForMIB=$this->getMIB()
141
-	        ->getTrapList($trapDetail->trap_name_mib);
142
-	    }
134
+		$this->view->mainoid=$trapDetail->trap_oid;
135
+		if ($trapDetail->trap_name_mib != null)
136
+		{
137
+			$this->view->mib=$trapDetail->trap_name_mib;
138
+			$this->view->name=$trapDetail->trap_name;
139
+			$this->view->trapListForMIB=$this->getMIB()
140
+			->getTrapList($trapDetail->trap_name_mib);
141
+		}
143 142
 	    
144
-	    // Get all objects that can be in trap from MIB
145
-	    $allObjects=$this->getMIB()->getObjectList($trapDetail->trap_oid);
146
-	    // Get all objects in current Trap
147
-	    $currentTrapObjects=$this->getTrapobjects($trapid);
148
-	    $oid_index=1;
149
-	    foreach ($currentTrapObjects as $key => $val)
150
-	    {
151
-	        $currentObjectType='Unknown';
152
-	        $currentObjectTypeEnum='Unknown';
153
-	        if (isset($allObjects[$val->oid]['type']))
154
-	        {
155
-	            $currentObjectType=$allObjects[$val->oid]['type'];
156
-	            $currentObjectTypeEnum=$allObjects[$val->oid]['type_enum'];
157
-	        }
158
-	        $currentObject=array(
159
-	            $oid_index,
160
-	            $val->oid,
161
-	            $val->oid_name_mib,
162
-	            $val->oid_name,
163
-	            $val->value,
164
-	            $currentObjectType,
165
-	            $currentObjectTypeEnum
166
-	        );
167
-	        $oid_index++;
168
-	        array_push($this->view->objectList,$currentObject);
169
-	        // set currrent object to null in allObjects
170
-	        if (isset($allObjects[$val->oid]))
171
-	        {
172
-	            $allObjects[$val->oid]=null;
173
-	        }
174
-	    }
175
-	    if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
176
-	    {
177
-	        foreach ($allObjects as $key => $val)
178
-	        {
179
-	            if ($val==null) { continue; }
180
-	            array_push($this->view->objectList, array(
181
-	                $oid_index,
182
-	                $key,
183
-	                $allObjects[$key]['mib'],
184
-	                $allObjects[$key]['name'],
185
-	                '',
186
-	                $allObjects[$key]['type'],
187
-	                $allObjects[$key]['type_enum']
188
-	            ));
189
-	            $oid_index++;
190
-	        }
191
-	    }
143
+		// Get all objects that can be in trap from MIB
144
+		$allObjects=$this->getMIB()->getObjectList($trapDetail->trap_oid);
145
+		// Get all objects in current Trap
146
+		$currentTrapObjects=$this->getTrapobjects($trapid);
147
+		$oid_index=1;
148
+		foreach ($currentTrapObjects as $key => $val)
149
+		{
150
+			$currentObjectType='Unknown';
151
+			$currentObjectTypeEnum='Unknown';
152
+			if (isset($allObjects[$val->oid]['type']))
153
+			{
154
+				$currentObjectType=$allObjects[$val->oid]['type'];
155
+				$currentObjectTypeEnum=$allObjects[$val->oid]['type_enum'];
156
+			}
157
+			$currentObject=array(
158
+				$oid_index,
159
+				$val->oid,
160
+				$val->oid_name_mib,
161
+				$val->oid_name,
162
+				$val->value,
163
+				$currentObjectType,
164
+				$currentObjectTypeEnum
165
+			);
166
+			$oid_index++;
167
+			array_push($this->view->objectList,$currentObject);
168
+			// set currrent object to null in allObjects
169
+			if (isset($allObjects[$val->oid]))
170
+			{
171
+				$allObjects[$val->oid]=null;
172
+			}
173
+		}
174
+		if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
175
+		{
176
+			foreach ($allObjects as $key => $val)
177
+			{
178
+				if ($val==null) { continue; }
179
+				array_push($this->view->objectList, array(
180
+					$oid_index,
181
+					$key,
182
+					$allObjects[$key]['mib'],
183
+					$allObjects[$key]['name'],
184
+					'',
185
+					$allObjects[$key]['type'],
186
+					$allObjects[$key]['type_enum']
187
+				));
188
+				$oid_index++;
189
+			}
190
+		}
192 191
 	    
193
-	    // Add a simple display
194
-	    $this->view->display='Trap '.$trapDetail->trap_name.' received';
195
-	    $this->view->create_basic_rule=true;
192
+		// Add a simple display
193
+		$this->view->display='Trap '.$trapDetail->trap_name.' received';
194
+		$this->view->create_basic_rule=true;
196 195
 	}
197 196
 
198 197
 	/**
@@ -201,29 +200,29 @@  discard block
 block discarded – undo
201 200
 	 */
202 201
 	private function add_check_host_exists($ruleDetail)
203 202
 	{
204
-	    // Check if hostname still exists
205
-	    $host_get=$this->getUIDatabase()->getHostByName($this->view->hostname);
203
+		// Check if hostname still exists
204
+		$host_get=$this->getUIDatabase()->getHostByName($this->view->hostname);
206 205
 	    
207
-	    if (count($host_get)==0)
208
-	    {
209
-	        $this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
210
-	        $this->view->serviceGet=false;
211
-	    }
212
-	    else
213
-	    {
214
-	        // Tell JS to get services when page is loaded
215
-	        $this->view->serviceGet=true;
216
-	        // get service id for form to set :
217
-	        $serviceID=$this->getUIDatabase()->getServiceIDByName($this->view->hostname,$ruleDetail->service_name);
218
-	        if (count($serviceID) ==0)
219
-	        {
220
-	            $this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
221
-	        }
222
-	        else
223
-	        {
224
-	            $this->view->serviceSet=$serviceID[0]->id;
225
-	        }
226
-	    }
206
+		if (count($host_get)==0)
207
+		{
208
+			$this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
209
+			$this->view->serviceGet=false;
210
+		}
211
+		else
212
+		{
213
+			// Tell JS to get services when page is loaded
214
+			$this->view->serviceGet=true;
215
+			// get service id for form to set :
216
+			$serviceID=$this->getUIDatabase()->getServiceIDByName($this->view->hostname,$ruleDetail->service_name);
217
+			if (count($serviceID) ==0)
218
+			{
219
+				$this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
220
+			}
221
+			else
222
+			{
223
+				$this->view->serviceSet=$serviceID[0]->id;
224
+			}
225
+		}
227 226
 	}
228 227
 
229 228
 	/**
@@ -232,33 +231,33 @@  discard block
 block discarded – undo
232 231
 	 */
233 232
 	private function add_check_hostgroup_exists($ruleDetail)
234 233
 	{
235
-	    // Check if groupe exists
236
-	    $group_get=$this->getUIDatabase()->getHostGroupByName($this->view->hostgroupname);
237
-	    if (count($group_get)==0)
238
-	    {
239
-	        $this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
240
-	        $this->view->serviceGroupGet=false;
241
-	    }
242
-	    else
243
-	    {
244
-	        $grpServices=$this->getUIDatabase()->getServicesByHostGroupid($group_get[0]->id);
245
-	        $foundGrpService=0;
246
-	        foreach ($grpServices as $grpService)
247
-	        {
248
-	            if ($grpService[0] == $ruleDetail->service_name)
249
-	            {
250
-	                $foundGrpService=1;
251
-	                $this->view->serviceSet=$ruleDetail->service_name;
252
-	            }
253
-	        }
234
+		// Check if groupe exists
235
+		$group_get=$this->getUIDatabase()->getHostGroupByName($this->view->hostgroupname);
236
+		if (count($group_get)==0)
237
+		{
238
+			$this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
239
+			$this->view->serviceGroupGet=false;
240
+		}
241
+		else
242
+		{
243
+			$grpServices=$this->getUIDatabase()->getServicesByHostGroupid($group_get[0]->id);
244
+			$foundGrpService=0;
245
+			foreach ($grpServices as $grpService)
246
+			{
247
+				if ($grpService[0] == $ruleDetail->service_name)
248
+				{
249
+					$foundGrpService=1;
250
+					$this->view->serviceSet=$ruleDetail->service_name;
251
+				}
252
+			}
254 253
 	        
255
-	        // Tell JS to get services when page is loaded
256
-	        $this->view->serviceGroupGet=true;
257
-	        if ($foundGrpService==0)
258
-	        {
259
-	            $this->view->warning_message.=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
260
-	        }
261
-	    }
254
+			// Tell JS to get services when page is loaded
255
+			$this->view->serviceGroupGet=true;
256
+			if ($foundGrpService==0)
257
+			{
258
+				$this->view->warning_message.=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
259
+			}
260
+		}
262 261
 	}
263 262
 	
264 263
 	/**
@@ -270,52 +269,52 @@  discard block
 block discarded – undo
270 269
 	 */
271 270
 	private function add_create_trap_object_list(&$display, &$rule)
272 271
 	{
273
-	    $curObjectList=array();
274
-	    $index=1;
275
-	    // check in display & rule for : OID(<oid>)
276
-	    $matches=array();
277
-	    while ( preg_match('/_OID\(([\.0-9\*]+)\)/',$display,$matches) ||
278
-	        preg_match('/_OID\(([\.0-9\*]+)\)/',$rule,$matches))
279
-	    {
280
-	        $curOid=$matches[1];
272
+		$curObjectList=array();
273
+		$index=1;
274
+		// check in display & rule for : OID(<oid>)
275
+		$matches=array();
276
+		while ( preg_match('/_OID\(([\.0-9\*]+)\)/',$display,$matches) ||
277
+			preg_match('/_OID\(([\.0-9\*]+)\)/',$rule,$matches))
278
+		{
279
+			$curOid=$matches[1];
281 280
 	        
282
-	        if ( (preg_match('/\*/',$curOid) == 0 ) 
283
-	            && ($object=$this->getMIB()->translateOID($curOid)) != null)
284
-	        {
285
-	            array_push($curObjectList, array(
286
-	                $index,
287
-	                $curOid,
288
-	                $object['mib'],
289
-	                $object['name'],
290
-	                '',
291
-	                $object['type'],
292
-	                $object['type_enum']
293
-	            ));
294
-	        }
295
-	        else
296
-	        {
297
-	            array_push($curObjectList, array(
298
-	                $index,
299
-	                $curOid,
300
-	                'not found',
301
-	                'not found',
302
-	                '',
303
-	                'not found',
304
-	                'not found'
305
-	            ));
306
-	        }
307
-	        $curOid = preg_replace('/\*/','\*',$curOid);
308
-	        $display=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$display);
309
-	        $rule=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$rule);
310
-	        $index++;
311
-	    }
312
-	    return $curObjectList;
281
+			if ( (preg_match('/\*/',$curOid) == 0 ) 
282
+				&& ($object=$this->getMIB()->translateOID($curOid)) != null)
283
+			{
284
+				array_push($curObjectList, array(
285
+					$index,
286
+					$curOid,
287
+					$object['mib'],
288
+					$object['name'],
289
+					'',
290
+					$object['type'],
291
+					$object['type_enum']
292
+				));
293
+			}
294
+			else
295
+			{
296
+				array_push($curObjectList, array(
297
+					$index,
298
+					$curOid,
299
+					'not found',
300
+					'not found',
301
+					'',
302
+					'not found',
303
+					'not found'
304
+				));
305
+			}
306
+			$curOid = preg_replace('/\*/','\*',$curOid);
307
+			$display=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$display);
308
+			$rule=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$rule);
309
+			$index++;
310
+		}
311
+		return $curObjectList;
313 312
 	}
314 313
 	
315 314
 	/** Add a handler  
316
-	*	Get params fromid : setup from existing trap (id of trap table)
317
-	*	Get param ruleid : edit from existing handler (id of rule table)
318
-	*/
315
+	 *	Get params fromid : setup from existing trap (id of trap table)
316
+	 *	Get param ruleid : edit from existing handler (id of rule table)
317
+	 */
319 318
 	public function addAction()
320 319
 	{
321 320
 		$this->checkConfigPermission();
@@ -334,8 +333,8 @@  discard block
 block discarded – undo
334 333
 		//$this->view->trapvalues=false; // Set to true to display 'value' colum in objects
335 334
 		
336 335
 		if (($trapid = $this->params->get('fromid')) !== null) {
337
-		    /********** Setup from existing trap ***************/
338
-            $this->add_from_existing($trapid);
336
+			/********** Setup from existing trap ***************/
337
+			$this->add_from_existing($trapid);
339 338
 			return;
340 339
 		}
341 340
 		
@@ -360,14 +359,14 @@  discard block
 block discarded – undo
360 359
 			$this->view->warning_message='';
361 360
 			if ($this->view->hostname != null)
362 361
 			{
363
-			    $this->view->selectGroup=false;
364
-			    // Check if hostname still exists
365
-			    $this->add_check_host_exists($ruleDetail);
362
+				$this->view->selectGroup=false;
363
+				// Check if hostname still exists
364
+				$this->add_check_host_exists($ruleDetail);
366 365
 			}
367 366
 			else
368 367
 			{
369
-			    $this->view->selectGroup=true;
370
-			    $this->add_check_hostgroup_exists($ruleDetail); //  Check if groupe exists				
368
+				$this->view->selectGroup=true;
369
+				$this->add_check_hostgroup_exists($ruleDetail); //  Check if groupe exists				
371 370
 			}
372 371
 			
373 372
 			$this->view->mainoid=$ruleDetail->trap_oid;
@@ -395,9 +394,9 @@  discard block
 block discarded – undo
395 394
 	}
396 395
 	
397 396
 	/** Validate form and output message to user  
398
-	*	@param in postdata 
399
-	* 	@return string status : OK / <Message>
400
-	**/
397
+	 *	@param in postdata 
398
+	 * 	@return string status : OK / <Message>
399
+	 **/
401 400
 	protected function handlerformAction()
402 401
 	{
403 402
 		$postData=$this->getRequest()->getPost();
@@ -428,7 +427,7 @@  discard block
 block discarded – undo
428 427
 		{
429 428
 			try
430 429
 			{
431
-			    $this->getUIDatabase()->deleteRule($postData[$params['db_rule']['post']]);
430
+				$this->getUIDatabase()->deleteRule($postData[$params['db_rule']['post']]);
432 431
 			}
433 432
 			catch (Exception $e)
434 433
 			{
@@ -438,7 +437,7 @@  discard block
 block discarded – undo
438 437
 			//$this->Module()->
439 438
 			$this->_helper->json(array(
440 439
 				'status'=>'OK',
441
-			    'redirect'=>'trapdirector/handler'
440
+				'redirect'=>'trapdirector/handler'
442 441
 			      
443 442
 			));
444 443
 		}		
@@ -465,7 +464,7 @@  discard block
 block discarded – undo
465 464
 			$isHostGroup=($params['hostgroup']['val'] == 1)?true:false;
466 465
 			if (! $isHostGroup ) 
467 466
 			{  // checks if selection by host 
468
-			    $hostAddr=$this->getUIDatabase()->getHostInfoByID($params['hostid']['val']);
467
+				$hostAddr=$this->getUIDatabase()->getHostInfoByID($params['hostid']['val']);
469 468
 				$params['ip4']['val']=$hostAddr->ip4;
470 469
 				$params['ip6']['val']=$hostAddr->ip6;
471 470
 				$checkHostName=$hostAddr->name;
@@ -476,8 +475,8 @@  discard block
 block discarded – undo
476 475
 				}
477 476
 				if (!is_numeric($params['serviceid']['val']))
478 477
 				{
479
-				    $this->_helper->json(array('status'=>"Invalid service id ". $params['serviceid']['val']));
480
-				    return;
478
+					$this->_helper->json(array('status'=>"Invalid service id ". $params['serviceid']['val']));
479
+					return;
481 480
 				}
482 481
 				$serviceName=$this->getUIDatabase()->getObjectNameByid($params['serviceid']['val']);
483 482
 				if ($params['service_name']['val'] != $serviceName->name2)
@@ -488,7 +487,7 @@  discard block
 block discarded – undo
488 487
 			}
489 488
 			else
490 489
 			{
491
-			    $object=$this->getUIDatabase()->getObjectNameByid($params['hostid']['val']);
490
+				$object=$this->getUIDatabase()->getObjectNameByid($params['hostid']['val']);
492 491
 				if ($params['host_name']['val'] != $object->name1)
493 492
 				{
494 493
 					$this->_helper->json(array('status'=>"Invalid object group id : Please re enter service"));
@@ -509,11 +508,11 @@  discard block
 block discarded – undo
509 508
 			// echo '<br>';	print_r($dbparams);echo '<br>';
510 509
 			if ($params['db_rule']['val'] == -1 ) 
511 510
 			{
512
-			    $ruleID=$this->getUIDatabase()->addHandlerRule($dbparams);
511
+				$ruleID=$this->getUIDatabase()->addHandlerRule($dbparams);
513 512
 			}
514 513
 			else
515 514
 			{
516
-			    $this->getUIDatabase()->updateHandlerRule($dbparams,$params['db_rule']['val']);
515
+				$this->getUIDatabase()->updateHandlerRule($dbparams,$params['db_rule']['val']);
517 516
 				$ruleID=$params['db_rule']['val'];
518 517
 			}
519 518
 		}
@@ -527,9 +526,9 @@  discard block
 block discarded – undo
527 526
 	}
528 527
 
529 528
 	/** Get trap detail by trapid. 
530
-	*	@param integer $trapid : id of trap in received table
531
-	*	@return array (objects)
532
-	*/
529
+	 *	@param integer $trapid : id of trap in received table
530
+	 *	@return array (objects)
531
+	 */
533 532
 	protected function getTrapDetail($trapid) 
534 533
 	{
535 534
 		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
@@ -545,14 +544,14 @@  discard block
 block discarded – undo
545 544
 		}
546 545
 		try
547 546
 		{		
548
-		    $query = $dbConn->select()
547
+			$query = $dbConn->select()
549 548
 				->from($this->getModuleConfig()->getTrapTableName(),$elmts)
550 549
 				->where('id=?',$trapid);
551 550
 				$trapDetail=$dbConn->fetchRow($query);
552 551
 			if ( $trapDetail == null ) 
553 552
 			{
554
-			    $trapDetail = 'NULL';
555
-			    throw new Exception('No traps was found with id = '.$trapid);
553
+				$trapDetail = 'NULL';
554
+				throw new Exception('No traps was found with id = '.$trapid);
556 555
 			}
557 556
 		}
558 557
 		catch (Exception $e)
@@ -566,9 +565,9 @@  discard block
 block discarded – undo
566 565
 	}
567 566
 
568 567
 	/** Get trap objects
569
-	*	@param integer $trapid : trap id
570
-	* 	@return array : full column in db of trap id
571
-	*/
568
+	 *	@param integer $trapid : trap id
569
+	 * 	@return array : full column in db of trap id
570
+	 */
572 571
 	protected function getTrapobjects($trapid)
573 572
 	{	
574 573
 		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
@@ -584,7 +583,7 @@  discard block
 block discarded – undo
584 583
 		}
585 584
 		try
586 585
 		{		
587
-		    $query = $dbConn->select()
586
+			$query = $dbConn->select()
588 587
 				->from($this->moduleConfig->getTrapDataTableName(),$data_elmts)
589 588
 				->where('trap_id=?',$trapid);
590 589
 				$trapDetail=$dbConn->fetchAll($query);
@@ -600,10 +599,10 @@  discard block
 block discarded – undo
600 599
 	}
601 600
 
602 601
 	/** Get rule detail by ruleid.
603
-	*	@param integer $ruleid int id of rule in rule table
604
-	*	@return object|array : column objects in db 
605
-	*
606
-	*/
602
+	 *	@param integer $ruleid int id of rule in rule table
603
+	 *	@return object|array : column objects in db 
604
+	 *
605
+	 */
607 606
 	protected function getRuleDetail($ruleid) 
608 607
 	{
609 608
 		if (!preg_match('/^[0-9]+$/',$ruleid)) { throw new Exception('Invalid id');  }
@@ -614,7 +613,7 @@  discard block
 block discarded – undo
614 613
 		// ***************  Get main data
615 614
 		try
616 615
 		{		
617
-		    $query = $dbConn->select()
616
+			$query = $dbConn->select()
618 617
 				->from($this->getModuleConfig()->getTrapRuleName(),$queryArray)
619 618
 				->where('id=?',$ruleid);
620 619
 			$ruleDetail=$dbConn->fetchRow($query);
@@ -631,7 +630,7 @@  discard block
 block discarded – undo
631 630
 	}
632 631
 
633 632
 	/** Setup tabs for rules 
634
-	*/
633
+	 */
635 634
 	protected function prepareTabs()
636 635
 	{
637 636
 		return $this->getTabs()->add('status', array(
Please login to merge, or discard this patch.
Spacing   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -23,16 +23,16 @@  discard block
 block discarded – undo
23 23
 		$this->checkReadPermission();
24 24
 		$this->prepareTabs()->activate('status');
25 25
 
26
-		$dbConn = $this->getUIDatabase()->getDb();
26
+		$dbConn=$this->getUIDatabase()->getDb();
27 27
 		if ($dbConn === null) throw new \ErrorException('uncatched db error');
28 28
 		
29 29
 		$this->getHandlerListTable()->setConnection($dbConn);
30 30
 		$this->getHandlerListTable()->setMibloader($this->getMIB());
31 31
 		// Apply pagination limits 
32
-		$this->view->table=$this->applyPaginationLimits($this->getHandlerListTable(),$this->getModuleConfig()->itemListDisplay());		
32
+		$this->view->table=$this->applyPaginationLimits($this->getHandlerListTable(), $this->getModuleConfig()->itemListDisplay());		
33 33
 		
34 34
 		// Set Filter
35
-		$this->view->filterEditor = $this->getHandlerListTable()->getFilterEditor($this->getRequest());		
35
+		$this->view->filterEditor=$this->getHandlerListTable()->getFilterEditor($this->getRequest());		
36 36
 	
37 37
 		//$this->displayExitError('Handler/indexAction','Not implemented');
38 38
 	}
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
 	public function testruleAction()
43 43
 	{
44 44
 	    $this->checkReadPermission();
45
-	    $this->getTabs()->add('get',array(
45
+	    $this->getTabs()->add('get', array(
46 46
 	        'active'	=> true,
47 47
 	        'label'		=> $this->translate('Test Rule'),
48 48
 	        'url'		=> Url::fromRequest()
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 
52 52
 	    if ($this->params->get('rule') !== null) 
53 53
 	    {
54
-	        $this->view->rule= $this->params->get('rule');
54
+	        $this->view->rule=$this->params->get('rule');
55 55
 	    }
56 56
 	    else
57 57
 	    {
@@ -110,12 +110,12 @@  discard block
 block discarded – undo
110 110
 	    }
111 111
 	    catch (Exception $e)
112 112
 	    {
113
-	        $this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
113
+	        $this->displayExitError('Add handler : get host by IP/Name ', $e->getMessage());
114 114
 	    }
115 115
 	    
116 116
 	    
117 117
 	    // if one unique host found -> put id text input
118
-	    if (count($hosts)==1) {
118
+	    if (count($hosts) == 1) {
119 119
 	        $this->view->hostname=$hosts[0]->name;
120 120
 	        //$hostid=$hosts[0]->id;
121 121
 	        // Tell JS to get services when page is loaded
@@ -124,9 +124,9 @@  discard block
 block discarded – undo
124 124
 	    }
125 125
 	    else
126 126
 	    {
127
-	        foreach($hosts as $key=>$val)
127
+	        foreach ($hosts as $key=>$val)
128 128
 	        {
129
-	            array_push($this->view->hostlist,$hosts[$key]->name);
129
+	            array_push($this->view->hostlist, $hosts[$key]->name);
130 130
 	        }
131 131
 	    }
132 132
 	    
@@ -165,18 +165,18 @@  discard block
 block discarded – undo
165 165
 	            $currentObjectTypeEnum
166 166
 	        );
167 167
 	        $oid_index++;
168
-	        array_push($this->view->objectList,$currentObject);
168
+	        array_push($this->view->objectList, $currentObject);
169 169
 	        // set currrent object to null in allObjects
170 170
 	        if (isset($allObjects[$val->oid]))
171 171
 	        {
172 172
 	            $allObjects[$val->oid]=null;
173 173
 	        }
174 174
 	    }
175
-	    if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
175
+	    if ($allObjects != null) // in case trap doesn't have objects or is not resolved
176 176
 	    {
177 177
 	        foreach ($allObjects as $key => $val)
178 178
 	        {
179
-	            if ($val==null) { continue; }
179
+	            if ($val == null) { continue; }
180 180
 	            array_push($this->view->objectList, array(
181 181
 	                $oid_index,
182 182
 	                $key,
@@ -204,9 +204,9 @@  discard block
 block discarded – undo
204 204
 	    // Check if hostname still exists
205 205
 	    $host_get=$this->getUIDatabase()->getHostByName($this->view->hostname);
206 206
 	    
207
-	    if (count($host_get)==0)
207
+	    if (count($host_get) == 0)
208 208
 	    {
209
-	        $this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
209
+	        $this->view->warning_message='Host '.$this->view->hostname.' doesn\'t exists anymore';
210 210
 	        $this->view->serviceGet=false;
211 211
 	    }
212 212
 	    else
@@ -214,10 +214,10 @@  discard block
 block discarded – undo
214 214
 	        // Tell JS to get services when page is loaded
215 215
 	        $this->view->serviceGet=true;
216 216
 	        // get service id for form to set :
217
-	        $serviceID=$this->getUIDatabase()->getServiceIDByName($this->view->hostname,$ruleDetail->service_name);
218
-	        if (count($serviceID) ==0)
217
+	        $serviceID=$this->getUIDatabase()->getServiceIDByName($this->view->hostname, $ruleDetail->service_name);
218
+	        if (count($serviceID) == 0)
219 219
 	        {
220
-	            $this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
220
+	            $this->view->warning_message=' Service '.$ruleDetail->service_name.' doesn\'t exists anymore';
221 221
 	        }
222 222
 	        else
223 223
 	        {
@@ -234,9 +234,9 @@  discard block
 block discarded – undo
234 234
 	{
235 235
 	    // Check if groupe exists
236 236
 	    $group_get=$this->getUIDatabase()->getHostGroupByName($this->view->hostgroupname);
237
-	    if (count($group_get)==0)
237
+	    if (count($group_get) == 0)
238 238
 	    {
239
-	        $this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
239
+	        $this->view->warning_message='HostGroup '.$this->view->hostgroupname.' doesn\'t exists anymore';
240 240
 	        $this->view->serviceGroupGet=false;
241 241
 	    }
242 242
 	    else
@@ -254,9 +254,9 @@  discard block
 block discarded – undo
254 254
 	        
255 255
 	        // Tell JS to get services when page is loaded
256 256
 	        $this->view->serviceGroupGet=true;
257
-	        if ($foundGrpService==0)
257
+	        if ($foundGrpService == 0)
258 258
 	        {
259
-	            $this->view->warning_message.=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
259
+	            $this->view->warning_message.=' Service '.$ruleDetail->service_name.' doesn\'t exists anymore';
260 260
 	        }
261 261
 	    }
262 262
 	}
@@ -274,12 +274,12 @@  discard block
 block discarded – undo
274 274
 	    $index=1;
275 275
 	    // check in display & rule for : OID(<oid>)
276 276
 	    $matches=array();
277
-	    while ( preg_match('/_OID\(([\.0-9\*]+)\)/',$display,$matches) ||
278
-	        preg_match('/_OID\(([\.0-9\*]+)\)/',$rule,$matches))
277
+	    while (preg_match('/_OID\(([\.0-9\*]+)\)/', $display, $matches) ||
278
+	        preg_match('/_OID\(([\.0-9\*]+)\)/', $rule, $matches))
279 279
 	    {
280 280
 	        $curOid=$matches[1];
281 281
 	        
282
-	        if ( (preg_match('/\*/',$curOid) == 0 ) 
282
+	        if ((preg_match('/\*/', $curOid) == 0) 
283 283
 	            && ($object=$this->getMIB()->translateOID($curOid)) != null)
284 284
 	        {
285 285
 	            array_push($curObjectList, array(
@@ -304,9 +304,9 @@  discard block
 block discarded – undo
304 304
 	                'not found'
305 305
 	            ));
306 306
 	        }
307
-	        $curOid = preg_replace('/\*/','\*',$curOid);
308
-	        $display=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$display);
309
-	        $rule=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$rule);
307
+	        $curOid=preg_replace('/\*/', '\*', $curOid);
308
+	        $display=preg_replace('/_OID\('.$curOid.'\)/', '\$'.$index.'\$', $display);
309
+	        $rule=preg_replace('/_OID\('.$curOid.'\)/', '\$'.$index.'\$', $rule);
310 310
 	        $index++;
311 311
 	    }
312 312
 	    return $curObjectList;
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
 	{
321 321
 		$this->checkConfigPermission();
322 322
 		// set up tab
323
-		$this->getTabs()->add('get',array(
323
+		$this->getTabs()->add('get', array(
324 324
 			'active'	=> true,
325 325
 			'label'		=> $this->translate('Add handler'),
326 326
 			'url'		=> Url::fromRequest()
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 		
334 334
 		//$this->view->trapvalues=false; // Set to true to display 'value' colum in objects
335 335
 		
336
-		if (($trapid = $this->params->get('fromid')) !== null) {
336
+		if (($trapid=$this->params->get('fromid')) !== null) {
337 337
 		    /********** Setup from existing trap ***************/
338 338
             $this->add_from_existing($trapid);
339 339
 			return;
@@ -353,7 +353,7 @@  discard block
 block discarded – undo
353 353
 			$this->view->setRuleMatch=$ruleDetail->action_match;
354 354
 			$this->view->setRuleNoMatch=$ruleDetail->action_nomatch;
355 355
 			$this->view->hostgroupname=$ruleDetail->host_group_name;
356
-			$this->view->modified=gmdate("Y-m-d\TH:i:s\Z",$ruleDetail->modified);
356
+			$this->view->modified=gmdate("Y-m-d\TH:i:s\Z", $ruleDetail->modified);
357 357
 			$this->view->modifier=$ruleDetail->modifier;
358 358
 			
359 359
 			// Warning message if host/service don't exists anymore
@@ -405,26 +405,26 @@  discard block
 block discarded – undo
405 405
 	
406 406
 		$params=array(
407 407
 			// id (also db) => 	array('post' => post id, 'val' => default val, 'db' => send to table)
408
-			'hostgroup'		=>	array('post' => 'hostgroup','db'=>false),
409
-			'db_rule'		=>	array('post' => 'db_rule','db'=>false),
410
-			'hostid'		=>	array('post' => 'hostid','db'=>false),
411
-			'host_name'		=>	array('post' => 'hostname','val' => null,'db'=>true),
412
-			'host_group_name'=>	array('post' => null,'val' => null,'db'=>true),
413
-			'serviceid'		=>	array('post' => 'serviceid','db'=>false),
414
-			'service_name'	=>	array('post' => 'serviceName','db'=>true),
415
-			'trap_oid'		=>	array('post' => 'oid','db'=>true),
416
-			'revert_ok'		=>	array('post' => 'revertOK','val' => 0,'db'=>true),
417
-			'display'		=>	array('post' => 'display','val' => '','db'=>true),
418
-			'rule'			=>	array('post' => 'rule','val' => '','db'=>true),			
419
-			'action_match'	=>	array('post' => 'ruleMatch','val' => -1,'db'=>true),
420
-			'action_nomatch'=>	array('post' => 'ruleNoMatch','val' => -1,'db'=>true),					
421
-			'ip4'			=>	array('post' => null,'val' => null,'db'=>true),
422
-			'ip6'			=>	array('post' => null,'val' => null,'db'=>true),
423
-			'action_form'	=>	array('post' => 'action_form','db'=>false)
408
+			'hostgroup'		=>	array('post' => 'hostgroup', 'db'=>false),
409
+			'db_rule'		=>	array('post' => 'db_rule', 'db'=>false),
410
+			'hostid'		=>	array('post' => 'hostid', 'db'=>false),
411
+			'host_name'		=>	array('post' => 'hostname', 'val' => null, 'db'=>true),
412
+			'host_group_name'=>	array('post' => null, 'val' => null, 'db'=>true),
413
+			'serviceid'		=>	array('post' => 'serviceid', 'db'=>false),
414
+			'service_name'	=>	array('post' => 'serviceName', 'db'=>true),
415
+			'trap_oid'		=>	array('post' => 'oid', 'db'=>true),
416
+			'revert_ok'		=>	array('post' => 'revertOK', 'val' => 0, 'db'=>true),
417
+			'display'		=>	array('post' => 'display', 'val' => '', 'db'=>true),
418
+			'rule'			=>	array('post' => 'rule', 'val' => '', 'db'=>true),			
419
+			'action_match'	=>	array('post' => 'ruleMatch', 'val' => -1, 'db'=>true),
420
+			'action_nomatch'=>	array('post' => 'ruleNoMatch', 'val' => -1, 'db'=>true),					
421
+			'ip4'			=>	array('post' => null, 'val' => null, 'db'=>true),
422
+			'ip6'			=>	array('post' => null, 'val' => null, 'db'=>true),
423
+			'action_form'	=>	array('post' => 'action_form', 'db'=>false)
424 424
 		);
425 425
 		
426 426
 		if (isset($postData[$params['action_form']['post']]) 
427
-			&& $postData[$params['action_form']['post']] == 'delete' )
427
+			&& $postData[$params['action_form']['post']] == 'delete')
428 428
 		{
429 429
 			try
430 430
 			{
@@ -444,16 +444,16 @@  discard block
 block discarded – undo
444 444
 		}		
445 445
 		foreach (array_keys($params) as $key)
446 446
 		{
447
-			if ($params[$key]['post']==null) continue; // data not sent in post vars
448
-			if (! isset($postData[$params[$key]['post']]))
447
+			if ($params[$key]['post'] == null) continue; // data not sent in post vars
448
+			if (!isset($postData[$params[$key]['post']]))
449 449
 			{
450 450
 				// should not happen as the js checks data
451
-				$this->_helper->json(array('status'=>'No ' . $key));
451
+				$this->_helper->json(array('status'=>'No '.$key));
452 452
 			}
453 453
 			else
454 454
 			{
455 455
 				$data=$postData[$params[$key]['post']];
456
-				if ($data!=null && $data !="")
456
+				if ($data != null && $data != "")
457 457
 				{
458 458
 					$params[$key]['val']=$postData[$params[$key]['post']];
459 459
 				}
@@ -462,8 +462,8 @@  discard block
 block discarded – undo
462 462
 
463 463
 		try 
464 464
 		{
465
-			$isHostGroup=($params['hostgroup']['val'] == 1)?true:false;
466
-			if (! $isHostGroup ) 
465
+			$isHostGroup=($params['hostgroup']['val'] == 1) ?true:false;
466
+			if (!$isHostGroup) 
467 467
 			{  // checks if selection by host 
468 468
 			    $hostAddr=$this->getUIDatabase()->getHostInfoByID($params['hostid']['val']);
469 469
 				$params['ip4']['val']=$hostAddr->ip4;
@@ -476,7 +476,7 @@  discard block
 block discarded – undo
476 476
 				}
477 477
 				if (!is_numeric($params['serviceid']['val']))
478 478
 				{
479
-				    $this->_helper->json(array('status'=>"Invalid service id ". $params['serviceid']['val']));
479
+				    $this->_helper->json(array('status'=>"Invalid service id ".$params['serviceid']['val']));
480 480
 				    return;
481 481
 				}
482 482
 				$serviceName=$this->getUIDatabase()->getObjectNameByid($params['serviceid']['val']);
@@ -495,25 +495,25 @@  discard block
 block discarded – undo
495 495
 					return;					
496 496
 				}
497 497
 				// Put param in correct column (group_name)
498
-				$params['host_group_name']['val'] = $params['host_name']['val'];
498
+				$params['host_group_name']['val']=$params['host_name']['val'];
499 499
 				$params['host_name']['val']=null;
500 500
 			}
501 501
 			$dbparams=array();
502 502
 			foreach ($params as $key=>$val)
503 503
 			{
504
-				if ($val['db']==true )
504
+				if ($val['db'] == true)
505 505
 				{
506
-					$dbparams[$key] = $val['val'];
506
+					$dbparams[$key]=$val['val'];
507 507
 				}
508 508
 			}
509 509
 			// echo '<br>';	print_r($dbparams);echo '<br>';
510
-			if ($params['db_rule']['val'] == -1 ) 
510
+			if ($params['db_rule']['val'] == -1) 
511 511
 			{
512 512
 			    $ruleID=$this->getUIDatabase()->addHandlerRule($dbparams);
513 513
 			}
514 514
 			else
515 515
 			{
516
-			    $this->getUIDatabase()->updateHandlerRule($dbparams,$params['db_rule']['val']);
516
+			    $this->getUIDatabase()->updateHandlerRule($dbparams, $params['db_rule']['val']);
517 517
 				$ruleID=$params['db_rule']['val'];
518 518
 			}
519 519
 		}
@@ -532,10 +532,10 @@  discard block
 block discarded – undo
532 532
 	*/
533 533
 	protected function getTrapDetail($trapid) 
534 534
 	{
535
-		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
535
+		if (!preg_match('/^[0-9]+$/', $trapid)) { throw new Exception('Invalid id'); }
536 536
 		$queryArray=$this->getModuleConfig()->trapDetailQuery();
537 537
 		
538
-		$dbConn = $this->getUIDatabase()->getDbConn();
538
+		$dbConn=$this->getUIDatabase()->getDbConn();
539 539
 		if ($dbConn === null) throw new \ErrorException('uncatched db error');
540 540
 		// ***************  Get main data
541 541
 		// extract columns and titles;
@@ -545,19 +545,19 @@  discard block
 block discarded – undo
545 545
 		}
546 546
 		try
547 547
 		{		
548
-		    $query = $dbConn->select()
549
-				->from($this->getModuleConfig()->getTrapTableName(),$elmts)
550
-				->where('id=?',$trapid);
548
+		    $query=$dbConn->select()
549
+				->from($this->getModuleConfig()->getTrapTableName(), $elmts)
550
+				->where('id=?', $trapid);
551 551
 				$trapDetail=$dbConn->fetchRow($query);
552
-			if ( $trapDetail == null ) 
552
+			if ($trapDetail == null) 
553 553
 			{
554
-			    $trapDetail = 'NULL';
554
+			    $trapDetail='NULL';
555 555
 			    throw new Exception('No traps was found with id = '.$trapid);
556 556
 			}
557 557
 		}
558 558
 		catch (Exception $e)
559 559
 		{
560
-			$this->displayExitError('Add handler : get trap detail returning : '.print_r($trapDetail,true),$e->getMessage());
560
+			$this->displayExitError('Add handler : get trap detail returning : '.print_r($trapDetail, true), $e->getMessage());
561 561
 			return;
562 562
 		}
563 563
 
@@ -571,10 +571,10 @@  discard block
 block discarded – undo
571 571
 	*/
572 572
 	protected function getTrapobjects($trapid)
573 573
 	{	
574
-		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
574
+		if (!preg_match('/^[0-9]+$/', $trapid)) { throw new Exception('Invalid id'); }
575 575
 		$queryArrayData=$this->getModuleConfig()->trapDataDetailQuery();
576 576
 		
577
-		$dbConn = $this->getUIDatabase()->getDbConn();
577
+		$dbConn=$this->getUIDatabase()->getDbConn();
578 578
 		if ($dbConn === null) throw new \ErrorException('uncatched db error');
579 579
 		// ***************  Get object data
580 580
 		// extract columns and titles;
@@ -584,15 +584,15 @@  discard block
 block discarded – undo
584 584
 		}
585 585
 		try
586 586
 		{		
587
-		    $query = $dbConn->select()
588
-				->from($this->moduleConfig->getTrapDataTableName(),$data_elmts)
589
-				->where('trap_id=?',$trapid);
587
+		    $query=$dbConn->select()
588
+				->from($this->moduleConfig->getTrapDataTableName(), $data_elmts)
589
+				->where('trap_id=?', $trapid);
590 590
 				$trapDetail=$dbConn->fetchAll($query);
591 591
 			// if ( $trapDetail == null ) throw new Exception('No traps was found with id = '.$trapid);
592 592
 		}
593 593
 		catch (Exception $e)
594 594
 		{
595
-			$this->displayExitError('Add handler : get trap data detail : ',$e->getMessage());
595
+			$this->displayExitError('Add handler : get trap data detail : ', $e->getMessage());
596 596
 			return array();
597 597
 		}
598 598
 
@@ -606,24 +606,24 @@  discard block
 block discarded – undo
606 606
 	*/
607 607
 	protected function getRuleDetail($ruleid) 
608 608
 	{
609
-		if (!preg_match('/^[0-9]+$/',$ruleid)) { throw new Exception('Invalid id');  }
609
+		if (!preg_match('/^[0-9]+$/', $ruleid)) { throw new Exception('Invalid id'); }
610 610
 		$queryArray=$this->getModuleConfig()->ruleDetailQuery();
611 611
 		
612
-		$dbConn = $this->getUIDatabase()->getDbConn();
612
+		$dbConn=$this->getUIDatabase()->getDbConn();
613 613
 		if ($dbConn === null) throw new \ErrorException('uncatched db error');
614 614
 		// ***************  Get main data
615 615
 		try
616 616
 		{		
617
-		    $query = $dbConn->select()
618
-				->from($this->getModuleConfig()->getTrapRuleName(),$queryArray)
619
-				->where('id=?',$ruleid);
617
+		    $query=$dbConn->select()
618
+				->from($this->getModuleConfig()->getTrapRuleName(), $queryArray)
619
+				->where('id=?', $ruleid);
620 620
 			$ruleDetail=$dbConn->fetchRow($query);
621
-			if ( $ruleDetail == null ) throw new Exception('No rule was found with id = '.$ruleid);
621
+			if ($ruleDetail == null) throw new Exception('No rule was found with id = '.$ruleid);
622 622
 		}
623 623
 		catch (Exception $e)
624 624
 		{
625
-			$this->displayExitError('Update handler : get rule detail',$e->getMessage());
626
-			throw new Exception('Error : ' . $e->getMessage());
625
+			$this->displayExitError('Update handler : get rule detail', $e->getMessage());
626
+			throw new Exception('Error : '.$e->getMessage());
627 627
 		}
628 628
 
629 629
 		return $ruleDetail;
@@ -636,7 +636,7 @@  discard block
 block discarded – undo
636 636
 	{
637 637
 		return $this->getTabs()->add('status', array(
638 638
 			'label' => $this->translate('Traps'),
639
-			'url'   => $this->getModuleConfig()->urlPath() . '/handler')
639
+			'url'   => $this->getModuleConfig()->urlPath().'/handler')
640 640
 		);
641 641
 	} 
642 642
 	
Please login to merge, or discard this patch.
Braces   +44 added lines, -42 removed lines patch added patch discarded remove patch
@@ -24,7 +24,9 @@  discard block
 block discarded – undo
24 24
 		$this->prepareTabs()->activate('status');
25 25
 
26 26
 		$dbConn = $this->getUIDatabase()->getDb();
27
-		if ($dbConn === null) throw new \ErrorException('uncatched db error');
27
+		if ($dbConn === null) {
28
+			throw new \ErrorException('uncatched db error');
29
+		}
28 30
 		
29 31
 		$this->getHandlerListTable()->setConnection($dbConn);
30 32
 		$this->getHandlerListTable()->setMibloader($this->getMIB());
@@ -52,8 +54,7 @@  discard block
 block discarded – undo
52 54
 	    if ($this->params->get('rule') !== null) 
53 55
 	    {
54 56
 	        $this->view->rule= $this->params->get('rule');
55
-	    }
56
-	    else
57
+	    } else
57 58
 	    {
58 59
 	        $this->view->rule='';
59 60
 	    }
@@ -107,8 +108,7 @@  discard block
 block discarded – undo
107 108
 	    try
108 109
 	    {
109 110
 	        $hosts=$this->getUIDatabase()->getHostByIP($hostfilter);
110
-	    }
111
-	    catch (Exception $e)
111
+	    } catch (Exception $e)
112 112
 	    {
113 113
 	        $this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
114 114
 	    }
@@ -121,8 +121,7 @@  discard block
 block discarded – undo
121 121
 	        // Tell JS to get services when page is loaded
122 122
 	        $this->view->serviceGet=true;
123 123
 	        
124
-	    }
125
-	    else
124
+	    } else
126 125
 	    {
127 126
 	        foreach($hosts as $key=>$val)
128 127
 	        {
@@ -172,11 +171,14 @@  discard block
 block discarded – undo
172 171
 	            $allObjects[$val->oid]=null;
173 172
 	        }
174 173
 	    }
175
-	    if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
174
+	    if ($allObjects!=null) {
175
+	    	// in case trap doesn't have objects or is not resolved
176 176
 	    {
177 177
 	        foreach ($allObjects as $key => $val)
178 178
 	        {
179
-	            if ($val==null) { continue; }
179
+	            if ($val==null) { continue;
180
+	    }
181
+	    }
180 182
 	            array_push($this->view->objectList, array(
181 183
 	                $oid_index,
182 184
 	                $key,
@@ -208,8 +210,7 @@  discard block
 block discarded – undo
208 210
 	    {
209 211
 	        $this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
210 212
 	        $this->view->serviceGet=false;
211
-	    }
212
-	    else
213
+	    } else
213 214
 	    {
214 215
 	        // Tell JS to get services when page is loaded
215 216
 	        $this->view->serviceGet=true;
@@ -218,8 +219,7 @@  discard block
 block discarded – undo
218 219
 	        if (count($serviceID) ==0)
219 220
 	        {
220 221
 	            $this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
221
-	        }
222
-	        else
222
+	        } else
223 223
 	        {
224 224
 	            $this->view->serviceSet=$serviceID[0]->id;
225 225
 	        }
@@ -238,8 +238,7 @@  discard block
 block discarded – undo
238 238
 	    {
239 239
 	        $this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
240 240
 	        $this->view->serviceGroupGet=false;
241
-	    }
242
-	    else
241
+	    } else
243 242
 	    {
244 243
 	        $grpServices=$this->getUIDatabase()->getServicesByHostGroupid($group_get[0]->id);
245 244
 	        $foundGrpService=0;
@@ -291,8 +290,7 @@  discard block
 block discarded – undo
291 290
 	                $object['type'],
292 291
 	                $object['type_enum']
293 292
 	            ));
294
-	        }
295
-	        else
293
+	        } else
296 294
 	        {
297 295
 	            array_push($curObjectList, array(
298 296
 	                $index,
@@ -363,8 +361,7 @@  discard block
 block discarded – undo
363 361
 			    $this->view->selectGroup=false;
364 362
 			    // Check if hostname still exists
365 363
 			    $this->add_check_host_exists($ruleDetail);
366
-			}
367
-			else
364
+			} else
368 365
 			{
369 366
 			    $this->view->selectGroup=true;
370 367
 			    $this->add_check_hostgroup_exists($ruleDetail); //  Check if groupe exists				
@@ -372,9 +369,11 @@  discard block
 block discarded – undo
372 369
 			
373 370
 			$this->view->mainoid=$ruleDetail->trap_oid;
374 371
 			$oidName=$this->getMIB()->translateOID($ruleDetail->trap_oid);
375
-			if ($oidName != null)  // oid is found in mibs
372
+			if ($oidName != null) {
373
+				// oid is found in mibs
376 374
 			{
377
-				$this->view->mib=$oidName['mib']; 
375
+				$this->view->mib=$oidName['mib'];
376
+			}
378 377
 				$this->view->name=$oidName['name'];
379 378
 				$this->view->trapListForMIB=$this->getMIB()
380 379
 					->getTrapList($oidName['mib']);				
@@ -429,8 +428,7 @@  discard block
 block discarded – undo
429 428
 			try
430 429
 			{
431 430
 			    $this->getUIDatabase()->deleteRule($postData[$params['db_rule']['post']]);
432
-			}
433
-			catch (Exception $e)
431
+			} catch (Exception $e)
434 432
 			{
435 433
 				$this->_helper->json(array('status'=>$e->getMessage()));
436 434
 				return;
@@ -444,13 +442,15 @@  discard block
 block discarded – undo
444 442
 		}		
445 443
 		foreach (array_keys($params) as $key)
446 444
 		{
447
-			if ($params[$key]['post']==null) continue; // data not sent in post vars
445
+			if ($params[$key]['post']==null) {
446
+				continue;
447
+			}
448
+			// data not sent in post vars
448 449
 			if (! isset($postData[$params[$key]['post']]))
449 450
 			{
450 451
 				// should not happen as the js checks data
451 452
 				$this->_helper->json(array('status'=>'No ' . $key));
452
-			}
453
-			else
453
+			} else
454 454
 			{
455 455
 				$data=$postData[$params[$key]['post']];
456 456
 				if ($data!=null && $data !="")
@@ -485,8 +485,7 @@  discard block
 block discarded – undo
485 485
 					$this->_helper->json(array('status'=>"Invalid service id : Please re enter service"));
486 486
 					return;
487 487
 				}
488
-			}
489
-			else
488
+			} else
490 489
 			{
491 490
 			    $object=$this->getUIDatabase()->getObjectNameByid($params['hostid']['val']);
492 491
 				if ($params['host_name']['val'] != $object->name1)
@@ -510,14 +509,12 @@  discard block
 block discarded – undo
510 509
 			if ($params['db_rule']['val'] == -1 ) 
511 510
 			{
512 511
 			    $ruleID=$this->getUIDatabase()->addHandlerRule($dbparams);
513
-			}
514
-			else
512
+			} else
515 513
 			{
516 514
 			    $this->getUIDatabase()->updateHandlerRule($dbparams,$params['db_rule']['val']);
517 515
 				$ruleID=$params['db_rule']['val'];
518 516
 			}
519
-		}
520
-		catch (Exception $e)
517
+		} catch (Exception $e)
521 518
 		{
522 519
 			$this->_helper->json(array('status'=>$e->getMessage()));
523 520
 			return;
@@ -536,7 +533,9 @@  discard block
 block discarded – undo
536 533
 		$queryArray=$this->getModuleConfig()->trapDetailQuery();
537 534
 		
538 535
 		$dbConn = $this->getUIDatabase()->getDbConn();
539
-		if ($dbConn === null) throw new \ErrorException('uncatched db error');
536
+		if ($dbConn === null) {
537
+			throw new \ErrorException('uncatched db error');
538
+		}
540 539
 		// ***************  Get main data
541 540
 		// extract columns and titles;
542 541
 		$elmts=NULL;
@@ -554,8 +553,7 @@  discard block
 block discarded – undo
554 553
 			    $trapDetail = 'NULL';
555 554
 			    throw new Exception('No traps was found with id = '.$trapid);
556 555
 			}
557
-		}
558
-		catch (Exception $e)
556
+		} catch (Exception $e)
559 557
 		{
560 558
 			$this->displayExitError('Add handler : get trap detail returning : '.print_r($trapDetail,true),$e->getMessage());
561 559
 			return;
@@ -575,7 +573,9 @@  discard block
 block discarded – undo
575 573
 		$queryArrayData=$this->getModuleConfig()->trapDataDetailQuery();
576 574
 		
577 575
 		$dbConn = $this->getUIDatabase()->getDbConn();
578
-		if ($dbConn === null) throw new \ErrorException('uncatched db error');
576
+		if ($dbConn === null) {
577
+			throw new \ErrorException('uncatched db error');
578
+		}
579 579
 		// ***************  Get object data
580 580
 		// extract columns and titles;
581 581
 		$data_elmts=NULL;
@@ -589,8 +589,7 @@  discard block
 block discarded – undo
589 589
 				->where('trap_id=?',$trapid);
590 590
 				$trapDetail=$dbConn->fetchAll($query);
591 591
 			// if ( $trapDetail == null ) throw new Exception('No traps was found with id = '.$trapid);
592
-		}
593
-		catch (Exception $e)
592
+		} catch (Exception $e)
594 593
 		{
595 594
 			$this->displayExitError('Add handler : get trap data detail : ',$e->getMessage());
596 595
 			return array();
@@ -610,7 +609,9 @@  discard block
 block discarded – undo
610 609
 		$queryArray=$this->getModuleConfig()->ruleDetailQuery();
611 610
 		
612 611
 		$dbConn = $this->getUIDatabase()->getDbConn();
613
-		if ($dbConn === null) throw new \ErrorException('uncatched db error');
612
+		if ($dbConn === null) {
613
+			throw new \ErrorException('uncatched db error');
614
+		}
614 615
 		// ***************  Get main data
615 616
 		try
616 617
 		{		
@@ -618,9 +619,10 @@  discard block
 block discarded – undo
618 619
 				->from($this->getModuleConfig()->getTrapRuleName(),$queryArray)
619 620
 				->where('id=?',$ruleid);
620 621
 			$ruleDetail=$dbConn->fetchRow($query);
621
-			if ( $ruleDetail == null ) throw new Exception('No rule was found with id = '.$ruleid);
622
-		}
623
-		catch (Exception $e)
622
+			if ( $ruleDetail == null ) {
623
+				throw new Exception('No rule was found with id = '.$ruleid);
624
+			}
625
+		} catch (Exception $e)
624 626
 		{
625 627
 			$this->displayExitError('Update handler : get rule detail',$e->getMessage());
626 628
 			throw new Exception('Error : ' . $e->getMessage());
Please login to merge, or discard this patch.
tests/expr_test.php 3 patches
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@
 block discarded – undo
20 20
   $inputStream=fopen('php://stdin', 'r');
21 21
   if ($inputStream === false)
22 22
   {
23
-      exit(1);
23
+	  exit(1);
24 24
   }
25 25
   $rule=chop(fgets($inputStream));
26 26
 } else
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -5,18 +5,18 @@  discard block
 block discarded – undo
5 5
 
6 6
 require_once 'bin/trap_class.php';
7 7
 
8
-$options = getopt("r:d:");
8
+$options=getopt("r:d:");
9 9
 
10
-$icingaweb2Etc=(array_key_exists('d',$options))?$options['d']:"/etc/icingaweb2";
10
+$icingaweb2Etc=(array_key_exists('d', $options)) ? $options['d'] : "/etc/icingaweb2";
11 11
 
12
-$debugLevel=4;// 0=No output 1=critical 2=warning 3=trace 4=ALL
12
+$debugLevel=4; // 0=No output 1=critical 2=warning 3=trace 4=ALL
13 13
 
14
-$trap = new trap($icingaweb2Etc);
15
-$trap->setLogging($debugLevel,'display');
14
+$trap=new trap($icingaweb2Etc);
15
+$trap->setLogging($debugLevel, 'display');
16 16
 
17
-$input=array_key_exists('r',$options);
17
+$input=array_key_exists('r', $options);
18 18
 
19
-if (! $input) {
19
+if (!$input) {
20 20
   $inputStream=fopen('php://stdin', 'r');
21 21
   if ($inputStream === false)
22 22
   {
@@ -31,10 +31,10 @@  discard block
 block discarded – undo
31 31
   $rule=$trap->ruleClass->eval_cleanup($rule);
32 32
   //echo 'After cleanup : #'.$rule."#\n";
33 33
   $item=0;
34
-  $val = $trap->ruleClass->evaluation($rule,$item);
35
-  if ($val==true) { printf( "true"); } else { printf( "false");}
34
+  $val=$trap->ruleClass->evaluation($rule, $item);
35
+  if ($val == true) { printf("true"); } else { printf("false"); }
36 36
   printf("\n");
37 37
 }
38
-catch (Exception $e) { printf("%s\n",$e->getMessage()); exit(1);}
38
+catch (Exception $e) { printf("%s\n", $e->getMessage()); exit(1); }
39 39
 
40 40
 exit(0);
Please login to merge, or discard this patch.
Braces   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -23,8 +23,9 @@  discard block
 block discarded – undo
23 23
       exit(1);
24 24
   }
25 25
   $rule=chop(fgets($inputStream));
26
-} else
26
+} else {
27 27
   $rule=$options['r'];
28
+}
28 29
 
29 30
 try
30 31
 {
@@ -34,7 +35,6 @@  discard block
 block discarded – undo
34 35
   $val = $trap->ruleClass->evaluation($rule,$item);
35 36
   if ($val==true) { printf( "true"); } else { printf( "false");}
36 37
   printf("\n");
37
-}
38
-catch (Exception $e) { printf("%s\n",$e->getMessage()); exit(1);}
38
+} catch (Exception $e) { printf("%s\n",$e->getMessage()); exit(1);}
39 39
 
40 40
 exit(0);
Please login to merge, or discard this patch.
library/Trapdirector/Icinga2Api.php 2 patches
Indentation   +332 added lines, -332 removed lines patch added patch discarded remove patch
@@ -8,363 +8,363 @@
 block discarded – undo
8 8
 
9 9
 class Icinga2API 
10 10
 {
11
-    protected $version = 'v1';      //< icinga2 api version
11
+	protected $version = 'v1';      //< icinga2 api version
12 12
     
13
-    protected $host;                //< icinga2 host name or IP
14
-    protected $port;                //< icinga2 api port
13
+	protected $host;                //< icinga2 host name or IP
14
+	protected $port;                //< icinga2 api port
15 15
     
16
-    protected $user;                //< user name
17
-    protected $pass;                //< user password
18
-    protected $usercert;            //< user key for certificate auth (NOT IMPLEMENTED)
19
-    protected $authmethod='pass';   //< Authentication : 'pass' or 'cert'
16
+	protected $user;                //< user name
17
+	protected $pass;                //< user password
18
+	protected $usercert;            //< user key for certificate auth (NOT IMPLEMENTED)
19
+	protected $authmethod='pass';   //< Authentication : 'pass' or 'cert'
20 20
 
21
-    protected $curl;
22
-    // http://php.net/manual/de/function.json-last-error.php#119985
23
-    protected $errorReference = [
24
-        JSON_ERROR_NONE => 'No error has occurred.',
25
-        JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
26
-        JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
27
-        JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded.',
28
-        JSON_ERROR_SYNTAX => 'Syntax error.',
29
-        JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded.',
30
-        JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded.',
31
-        JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
32
-        JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
33
-    ];
34
-    const JSON_UNKNOWN_ERROR = 'Unknown error.';
21
+	protected $curl;
22
+	// http://php.net/manual/de/function.json-last-error.php#119985
23
+	protected $errorReference = [
24
+		JSON_ERROR_NONE => 'No error has occurred.',
25
+		JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
26
+		JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
27
+		JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded.',
28
+		JSON_ERROR_SYNTAX => 'Syntax error.',
29
+		JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded.',
30
+		JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded.',
31
+		JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
32
+		JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
33
+	];
34
+	const JSON_UNKNOWN_ERROR = 'Unknown error.';
35 35
     
36
-    /**
37
-     * Creates Icinga2API object
38
-     * 
39
-     * @param string $host host name or IP
40
-     * @param number $port API port
41
-     */
42
-    public function __construct($host, $port = 5665)
43
-    {
44
-        $this->host=$host;
45
-        $this->port=$port;
46
-    }
47
-    /**
48
-     * Set user & pass
49
-     * @param string $user
50
-     * @param string $pass
51
-     */
52
-    public function setCredentials($user,$pass)
53
-    {
54
-        $this->user=$user;
55
-        $this->pass=$pass;
56
-        $this->authmethod='pass';
57
-    }
36
+	/**
37
+	 * Creates Icinga2API object
38
+	 * 
39
+	 * @param string $host host name or IP
40
+	 * @param number $port API port
41
+	 */
42
+	public function __construct($host, $port = 5665)
43
+	{
44
+		$this->host=$host;
45
+		$this->port=$port;
46
+	}
47
+	/**
48
+	 * Set user & pass
49
+	 * @param string $user
50
+	 * @param string $pass
51
+	 */
52
+	public function setCredentials($user,$pass)
53
+	{
54
+		$this->user=$user;
55
+		$this->pass=$pass;
56
+		$this->authmethod='pass';
57
+	}
58 58
     
59
-    /**
60
-     * Set user & certificate (NOT IMPLEMENTED @throws RuntimeException)
61
-     * @param string $user
62
-     * @param string $usercert
63
-     */
64
-    public function setCredentialskey($user,$usercert)
65
-    {
66
-        $this->user=$user;
67
-        $this->usercert=$usercert;
68
-        $this->authmethod='cert';
69
-        throw new RuntimeException('Certificate auth not implemented');
70
-    }
59
+	/**
60
+	 * Set user & certificate (NOT IMPLEMENTED @throws RuntimeException)
61
+	 * @param string $user
62
+	 * @param string $usercert
63
+	 */
64
+	public function setCredentialskey($user,$usercert)
65
+	{
66
+		$this->user=$user;
67
+		$this->usercert=$usercert;
68
+		$this->authmethod='cert';
69
+		throw new RuntimeException('Certificate auth not implemented');
70
+	}
71 71
 
72
-    public function test(array $permissions)
73
-    {
74
-       try
75
-        {
76
-            $result=$this->request('GET', "", NULL, NULL);
77
-        } 
78
-        catch (Exception $e)
79
-        {
80
-            return array(true, 'Error with API : '.$e->getMessage());
81
-        }
82
-        //var_dump($result);
83
-        $permOk=1;
84
-        $permMissing='';
85
-        if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
86
-        {
72
+	public function test(array $permissions)
73
+	{
74
+	   try
75
+		{
76
+			$result=$this->request('GET', "", NULL, NULL);
77
+		} 
78
+		catch (Exception $e)
79
+		{
80
+			return array(true, 'Error with API : '.$e->getMessage());
81
+		}
82
+		//var_dump($result);
83
+		$permOk=1;
84
+		$permMissing='';
85
+		if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
86
+		{
87 87
             
88
-            foreach ( $permissions as $mustPermission)
89
-            {
90
-                $curPermOK=0;
91
-                foreach ( $result->results[0]->permissions as $curPermission)
92
-                {
93
-                    $curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
94
-                    if (preg_match('#'.$curPermission.'#',$mustPermission))
95
-                    {
96
-                        $curPermOK=1;
97
-                        break;
98
-                    }
99
-                }
100
-                if ($curPermOK == 0)
101
-                {
102
-                    $permOk=0;
103
-                    $permMissing=$mustPermission;
104
-                    break;
105
-                }
106
-            }
107
-            if ($permOk == 0)
108
-            {
109
-                return array(true,'API connection OK, but missing permission : '.$permMissing);
110
-            }
111
-            return array(false,'API connection OK');
88
+			foreach ( $permissions as $mustPermission)
89
+			{
90
+				$curPermOK=0;
91
+				foreach ( $result->results[0]->permissions as $curPermission)
92
+				{
93
+					$curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
94
+					if (preg_match('#'.$curPermission.'#',$mustPermission))
95
+					{
96
+						$curPermOK=1;
97
+						break;
98
+					}
99
+				}
100
+				if ($curPermOK == 0)
101
+				{
102
+					$permOk=0;
103
+					$permMissing=$mustPermission;
104
+					break;
105
+				}
106
+			}
107
+			if ($permOk == 0)
108
+			{
109
+				return array(true,'API connection OK, but missing permission : '.$permMissing);
110
+			}
111
+			return array(false,'API connection OK');
112 112
             
113
-        }
114
-        return array(true,'API connection OK, but cannot get permissions');
115
-    }
113
+		}
114
+		return array(true,'API connection OK, but cannot get permissions');
115
+	}
116 116
     
117 117
     
118
-    protected function url($url) {
119
-        return sprintf('https://%s:%d/%s/%s', $this->host, $this->port, $this->version, $url);
120
-    }
118
+	protected function url($url) {
119
+		return sprintf('https://%s:%d/%s/%s', $this->host, $this->port, $this->version, $url);
120
+	}
121 121
     
122
-    /**
123
-     * Create or return curl ressource
124
-     * @throws Exception
125
-     * @return resource
126
-     */
127
-    protected function curl() {
128
-        if ($this->curl === null) {
129
-            $this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
130
-            if ($this->curl === false) {
131
-                throw new Exception('CURL INIT ERROR');
132
-            }
133
-        }
134
-        return $this->curl;
135
-    }
122
+	/**
123
+	 * Create or return curl ressource
124
+	 * @throws Exception
125
+	 * @return resource
126
+	 */
127
+	protected function curl() {
128
+		if ($this->curl === null) {
129
+			$this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
130
+			if ($this->curl === false) {
131
+				throw new Exception('CURL INIT ERROR');
132
+			}
133
+		}
134
+		return $this->curl;
135
+	}
136 136
 
137
-    /**
138
-     * Send a passive service check
139
-     * @param string $host : host name 
140
-     * @param string $service : service name
141
-     * @param int $state : state of service
142
-     * @param string $display : service passive check output
143
-     * @param string $perfdata : performance data as string
144
-     * @return array (status = true (oK) or false (nok), string message)
145
-     */
146
-    public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
147
-    {
148
-        //Send a POST request to the URL endpoint /v1/actions/process-check-result
149
-        //actions/process-check-result?service=example.localdomain!passive-ping6
150
-        $url='actions/process-check-result';
151
-        $body=array(
152
-            "filter"        => 'service.name=="'.$service.'" && service.host_name=="'.$host.'"',
153
-            'type'          => 'Service',
154
-            "exit_status"   => $state,
155
-            "plugin_output" => $display,
156
-            "performance_data" => $perfdata
157
-        );
158
-        try 
159
-        {
160
-            $result=$this->request('POST', $url, null, $body);
161
-        } catch (Exception $e) 
162
-        {
163
-            return array(false, $e->getMessage());
164
-        }
165
-        if (property_exists($result,'error') )
166
-        {
167
-            if (property_exists($result,'status'))
168
-            {
169
-                $message=$result->status;
170
-            }
171
-            else 
172
-            {
173
-                $message="Unkown status";
174
-            }
175
-            return array(false , 'Ret code ' .$result->error.' : '.$message);
176
-        }
177
-        if (property_exists($result, 'results'))
178
-        {
179
-            if (isset($result->results[0]))
180
-            {
181
-                return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
182
-            }
183
-            else
184
-            {
185
-                return array(false,'Service not found');
186
-            }
137
+	/**
138
+	 * Send a passive service check
139
+	 * @param string $host : host name 
140
+	 * @param string $service : service name
141
+	 * @param int $state : state of service
142
+	 * @param string $display : service passive check output
143
+	 * @param string $perfdata : performance data as string
144
+	 * @return array (status = true (oK) or false (nok), string message)
145
+	 */
146
+	public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
147
+	{
148
+		//Send a POST request to the URL endpoint /v1/actions/process-check-result
149
+		//actions/process-check-result?service=example.localdomain!passive-ping6
150
+		$url='actions/process-check-result';
151
+		$body=array(
152
+			"filter"        => 'service.name=="'.$service.'" && service.host_name=="'.$host.'"',
153
+			'type'          => 'Service',
154
+			"exit_status"   => $state,
155
+			"plugin_output" => $display,
156
+			"performance_data" => $perfdata
157
+		);
158
+		try 
159
+		{
160
+			$result=$this->request('POST', $url, null, $body);
161
+		} catch (Exception $e) 
162
+		{
163
+			return array(false, $e->getMessage());
164
+		}
165
+		if (property_exists($result,'error') )
166
+		{
167
+			if (property_exists($result,'status'))
168
+			{
169
+				$message=$result->status;
170
+			}
171
+			else 
172
+			{
173
+				$message="Unkown status";
174
+			}
175
+			return array(false , 'Ret code ' .$result->error.' : '.$message);
176
+		}
177
+		if (property_exists($result, 'results'))
178
+		{
179
+			if (isset($result->results[0]))
180
+			{
181
+				return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
182
+			}
183
+			else
184
+			{
185
+				return array(false,'Service not found');
186
+			}
187 187
             
188
-        }
189
-        return array(false,'Unkown result, open issue with this : '.print_r($result,true));
190
-    }
188
+		}
189
+		return array(false,'Unkown result, open issue with this : '.print_r($result,true));
190
+	}
191 191
  
192
-    /**
193
-     * return array of host by IP (4 or 6)
194
-     * @param string $ip
195
-     * @throws Exception
196
-     * @return array objects : array('__name','name','display_name')
197
-     */
198
-    public function getHostByIP($ip) 
199
-    {
200
-        /*
192
+	/**
193
+	 * return array of host by IP (4 or 6)
194
+	 * @param string $ip
195
+	 * @throws Exception
196
+	 * @return array objects : array('__name','name','display_name')
197
+	 */
198
+	public function getHostByIP($ip) 
199
+	{
200
+		/*
201 201
          *  curl -k -s -u  trapdirector:trapdirector -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts' 
202 202
          *  -d '{"filter":"host.group==\"test_trap\"","attrs": ["address" ,"address6"]}'
203 203
             
204 204
             {"results":[{"attrs":{"__name":"Icinga host","address":"127.0.0.1","display_name":"Icinga host","name":"Icinga host"},"joins":{},"meta":{},"name":"Icinga host","type":"Host"}]}
205 205
          */
206 206
         
207
-        $url='objects/hosts';
208
-        $body=array(
209
-            "filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
210
-            "attrs"         => array('__name','name','display_name')
211
-        );
212
-        try
213
-        {
214
-            $result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
215
-        } catch (Exception $e)
216
-        {
217
-            throw new Exception($e->getMessage());
218
-        }
207
+		$url='objects/hosts';
208
+		$body=array(
209
+			"filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
210
+			"attrs"         => array('__name','name','display_name')
211
+		);
212
+		try
213
+		{
214
+			$result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
215
+		} catch (Exception $e)
216
+		{
217
+			throw new Exception($e->getMessage());
218
+		}
219 219
         
220
-        if (property_exists($result,'error') )
221
-        {
222
-            if (property_exists($result,'status'))
223
-            {
224
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
225
-            }
226
-            else
227
-            {
228
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
229
-            }
230
-        }
231
-        if (property_exists($result, 'results'))
232
-        {
233
-            $numHost=0;
234
-            $hostArray=array();
235
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
236
-            {
237
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
238
-                $numHost++;
239
-            }
240
-            return $hostArray;            
241
-        }
242
-        throw new Exception('Unkown result');
243
-    }
220
+		if (property_exists($result,'error') )
221
+		{
222
+			if (property_exists($result,'status'))
223
+			{
224
+				throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
225
+			}
226
+			else
227
+			{
228
+				throw new Exception('Ret code ' .$result->error.' : Unkown status');
229
+			}
230
+		}
231
+		if (property_exists($result, 'results'))
232
+		{
233
+			$numHost=0;
234
+			$hostArray=array();
235
+			while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
236
+			{
237
+				$hostArray[$numHost] = $result->results[$numHost]->attrs;
238
+				$numHost++;
239
+			}
240
+			return $hostArray;            
241
+		}
242
+		throw new Exception('Unkown result');
243
+	}
244 244
 
245
-    /**
246
-     * Get all host and IP from hostgroup
247
-     * @param string $hostGroup
248
-     * @throws Exception
249
-     * @return array : attributes : address, address6, name
250
-     */
251
-    public function getHostsIPByHostGroup($hostGroup)
252
-    {        
253
-        $url='objects/hosts';
254
-        $body=array(
255
-            "filter"        => '\"'.$hostGroup.'\" in host.groups',
256
-            "attrs"         => array('address','address','name')
257
-        );
258
-        try
259
-        {
260
-            $result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
261
-        } catch (Exception $e)
262
-        {
263
-            throw new Exception($e->getMessage());
264
-        }
245
+	/**
246
+	 * Get all host and IP from hostgroup
247
+	 * @param string $hostGroup
248
+	 * @throws Exception
249
+	 * @return array : attributes : address, address6, name
250
+	 */
251
+	public function getHostsIPByHostGroup($hostGroup)
252
+	{        
253
+		$url='objects/hosts';
254
+		$body=array(
255
+			"filter"        => '\"'.$hostGroup.'\" in host.groups',
256
+			"attrs"         => array('address','address','name')
257
+		);
258
+		try
259
+		{
260
+			$result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
261
+		} catch (Exception $e)
262
+		{
263
+			throw new Exception($e->getMessage());
264
+		}
265 265
         
266
-        if (property_exists($result,'error') )
267
-        {
268
-            if (property_exists($result,'status'))
269
-            {
270
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
271
-            }
272
-            else
273
-            {
274
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
275
-            }
276
-        }
277
-        if (property_exists($result, 'results'))
278
-        {
279
-            $numHost=0;
280
-            $hostArray=array();
281
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
282
-            {
283
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
284
-                $hostArray[$numHost]->name = $result->results[$numHost]->name;
285
-                $numHost++;
286
-            }
287
-            return $hostArray;
288
-        }
289
-        throw new Exception('Unkown result');
290
-    }
266
+		if (property_exists($result,'error') )
267
+		{
268
+			if (property_exists($result,'status'))
269
+			{
270
+				throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
271
+			}
272
+			else
273
+			{
274
+				throw new Exception('Ret code ' .$result->error.' : Unkown status');
275
+			}
276
+		}
277
+		if (property_exists($result, 'results'))
278
+		{
279
+			$numHost=0;
280
+			$hostArray=array();
281
+			while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
282
+			{
283
+				$hostArray[$numHost] = $result->results[$numHost]->attrs;
284
+				$hostArray[$numHost]->name = $result->results[$numHost]->name;
285
+				$numHost++;
286
+			}
287
+			return $hostArray;
288
+		}
289
+		throw new Exception('Unkown result');
290
+	}
291 291
     
292
-    /**
293
-     * Send request to API
294
-     * @param string $method get/post/...
295
-     * @param string $url (after /v1/ )
296
-     * @param array $headers
297
-     * @param array $body 
298
-     * @throws Exception
299
-     * @return array
300
-     */
301
-    public function request($method, $url, $headers, $body) {
302
-        $auth = sprintf('%s:%s', $this->user, $this->pass);
303
-        $curlHeaders = array("Accept: application/json");
304
-        if ($body !== null) {
305
-            $body = json_encode($body);
306
-            array_push($curlHeaders, 'Content-Type: application/json');
307
-            //array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
308
-        }
309
-        //var_dump($body);
310
-        //var_dump($this->url($url));
311
-        if ($headers !== null) {
312
-            $curlFinalHeaders = array_merge($curlHeaders, $headers);
313
-        } else 
314
-        {
315
-            $curlFinalHeaders=$curlHeaders;
316
-        }
317
-        $curl = $this->curl();
318
-        $opts = array(
319
-            CURLOPT_URL		=> $this->url($url),
320
-            CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
321
-            CURLOPT_USERPWD		=> $auth,
322
-            CURLOPT_CUSTOMREQUEST	=> strtoupper($method),
323
-            CURLOPT_RETURNTRANSFER 	=> true,
324
-            CURLOPT_CONNECTTIMEOUT 	=> 10,
325
-            CURLOPT_SSL_VERIFYHOST 	=> false,
326
-            CURLOPT_SSL_VERIFYPEER 	=> false,
327
-        );
328
-        if ($body !== null) {
329
-            $opts[CURLOPT_POSTFIELDS] = $body;
330
-        }
331
-        curl_setopt_array($curl, $opts);
332
-        $res = curl_exec($curl);
333
-        if ($res === false) {
334
-            throw new Exception('CURL ERROR: ' . curl_error($curl));
335
-        }
336
-        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
337
-        if ($statusCode === 401) {
338
-            throw new Exception('Unable to authenticate, please check your API credentials');
339
-        }
340
-        return $this->fromJsonResult($res);
341
-    }
292
+	/**
293
+	 * Send request to API
294
+	 * @param string $method get/post/...
295
+	 * @param string $url (after /v1/ )
296
+	 * @param array $headers
297
+	 * @param array $body 
298
+	 * @throws Exception
299
+	 * @return array
300
+	 */
301
+	public function request($method, $url, $headers, $body) {
302
+		$auth = sprintf('%s:%s', $this->user, $this->pass);
303
+		$curlHeaders = array("Accept: application/json");
304
+		if ($body !== null) {
305
+			$body = json_encode($body);
306
+			array_push($curlHeaders, 'Content-Type: application/json');
307
+			//array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
308
+		}
309
+		//var_dump($body);
310
+		//var_dump($this->url($url));
311
+		if ($headers !== null) {
312
+			$curlFinalHeaders = array_merge($curlHeaders, $headers);
313
+		} else 
314
+		{
315
+			$curlFinalHeaders=$curlHeaders;
316
+		}
317
+		$curl = $this->curl();
318
+		$opts = array(
319
+			CURLOPT_URL		=> $this->url($url),
320
+			CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
321
+			CURLOPT_USERPWD		=> $auth,
322
+			CURLOPT_CUSTOMREQUEST	=> strtoupper($method),
323
+			CURLOPT_RETURNTRANSFER 	=> true,
324
+			CURLOPT_CONNECTTIMEOUT 	=> 10,
325
+			CURLOPT_SSL_VERIFYHOST 	=> false,
326
+			CURLOPT_SSL_VERIFYPEER 	=> false,
327
+		);
328
+		if ($body !== null) {
329
+			$opts[CURLOPT_POSTFIELDS] = $body;
330
+		}
331
+		curl_setopt_array($curl, $opts);
332
+		$res = curl_exec($curl);
333
+		if ($res === false) {
334
+			throw new Exception('CURL ERROR: ' . curl_error($curl));
335
+		}
336
+		$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
337
+		if ($statusCode === 401) {
338
+			throw new Exception('Unable to authenticate, please check your API credentials');
339
+		}
340
+		return $this->fromJsonResult($res);
341
+	}
342 342
     
343
-    /**
344
-     * 
345
-     * @param string $json json encoded 
346
-     * @throws Exception
347
-     * @return array json decoded
348
-     */
349
-    protected function fromJsonResult($json) {
350
-        $result = @json_decode($json);
351
-        //var_dump($json);
352
-        if ($result === null) {
353
-            throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
354
-        }
355
-        return $result;
356
-    }
343
+	/**
344
+	 * 
345
+	 * @param string $json json encoded 
346
+	 * @throws Exception
347
+	 * @return array json decoded
348
+	 */
349
+	protected function fromJsonResult($json) {
350
+		$result = @json_decode($json);
351
+		//var_dump($json);
352
+		if ($result === null) {
353
+			throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
354
+		}
355
+		return $result;
356
+	}
357 357
     
358
-    /**
359
-     * Return text error no json error
360
-     * @param string $errorCode
361
-     * @return string
362
-     */
363
-    protected function getLastJsonErrorMessage($errorCode) {
364
-        if (!array_key_exists($errorCode, $this->errorReference)) {
365
-            return self::JSON_UNKNOWN_ERROR;
366
-        }
367
-        return $this->errorReference[$errorCode];
368
-    }
358
+	/**
359
+	 * Return text error no json error
360
+	 * @param string $errorCode
361
+	 * @return string
362
+	 */
363
+	protected function getLastJsonErrorMessage($errorCode) {
364
+		if (!array_key_exists($errorCode, $this->errorReference)) {
365
+			return self::JSON_UNKNOWN_ERROR;
366
+		}
367
+		return $this->errorReference[$errorCode];
368
+	}
369 369
 }
370 370
 
Please login to merge, or discard this patch.
Spacing   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -8,19 +8,19 @@  discard block
 block discarded – undo
8 8
 
9 9
 class Icinga2API 
10 10
 {
11
-    protected $version = 'v1';      //< icinga2 api version
11
+    protected $version='v1'; //< icinga2 api version
12 12
     
13
-    protected $host;                //< icinga2 host name or IP
14
-    protected $port;                //< icinga2 api port
13
+    protected $host; //< icinga2 host name or IP
14
+    protected $port; //< icinga2 api port
15 15
     
16
-    protected $user;                //< user name
17
-    protected $pass;                //< user password
18
-    protected $usercert;            //< user key for certificate auth (NOT IMPLEMENTED)
19
-    protected $authmethod='pass';   //< Authentication : 'pass' or 'cert'
16
+    protected $user; //< user name
17
+    protected $pass; //< user password
18
+    protected $usercert; //< user key for certificate auth (NOT IMPLEMENTED)
19
+    protected $authmethod='pass'; //< Authentication : 'pass' or 'cert'
20 20
 
21 21
     protected $curl;
22 22
     // http://php.net/manual/de/function.json-last-error.php#119985
23
-    protected $errorReference = [
23
+    protected $errorReference=[
24 24
         JSON_ERROR_NONE => 'No error has occurred.',
25 25
         JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
26 26
         JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
         JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
32 32
         JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
33 33
     ];
34
-    const JSON_UNKNOWN_ERROR = 'Unknown error.';
34
+    const JSON_UNKNOWN_ERROR='Unknown error.';
35 35
     
36 36
     /**
37 37
      * Creates Icinga2API object
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
      * @param string $host host name or IP
40 40
      * @param number $port API port
41 41
      */
42
-    public function __construct($host, $port = 5665)
42
+    public function __construct($host, $port=5665)
43 43
     {
44 44
         $this->host=$host;
45 45
         $this->port=$port;
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
      * @param string $user
50 50
      * @param string $pass
51 51
      */
52
-    public function setCredentials($user,$pass)
52
+    public function setCredentials($user, $pass)
53 53
     {
54 54
         $this->user=$user;
55 55
         $this->pass=$pass;
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
      * @param string $user
62 62
      * @param string $usercert
63 63
      */
64
-    public function setCredentialskey($user,$usercert)
64
+    public function setCredentialskey($user, $usercert)
65 65
     {
66 66
         $this->user=$user;
67 67
         $this->usercert=$usercert;
@@ -85,13 +85,13 @@  discard block
 block discarded – undo
85 85
         if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
86 86
         {
87 87
             
88
-            foreach ( $permissions as $mustPermission)
88
+            foreach ($permissions as $mustPermission)
89 89
             {
90 90
                 $curPermOK=0;
91
-                foreach ( $result->results[0]->permissions as $curPermission)
91
+                foreach ($result->results[0]->permissions as $curPermission)
92 92
                 {
93
-                    $curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
94
-                    if (preg_match('#'.$curPermission.'#',$mustPermission))
93
+                    $curPermission=preg_replace('/\*/', '.*', $curPermission); // put * as .* to created a regexp
94
+                    if (preg_match('#'.$curPermission.'#', $mustPermission))
95 95
                     {
96 96
                         $curPermOK=1;
97 97
                         break;
@@ -106,12 +106,12 @@  discard block
 block discarded – undo
106 106
             }
107 107
             if ($permOk == 0)
108 108
             {
109
-                return array(true,'API connection OK, but missing permission : '.$permMissing);
109
+                return array(true, 'API connection OK, but missing permission : '.$permMissing);
110 110
             }
111
-            return array(false,'API connection OK');
111
+            return array(false, 'API connection OK');
112 112
             
113 113
         }
114
-        return array(true,'API connection OK, but cannot get permissions');
114
+        return array(true, 'API connection OK, but cannot get permissions');
115 115
     }
116 116
     
117 117
     
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
      */
127 127
     protected function curl() {
128 128
         if ($this->curl === null) {
129
-            $this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
129
+            $this->curl=curl_init(sprintf('https://%s:%d', $this->host, $this->port));
130 130
             if ($this->curl === false) {
131 131
                 throw new Exception('CURL INIT ERROR');
132 132
             }
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
      * @param string $perfdata : performance data as string
144 144
      * @return array (status = true (oK) or false (nok), string message)
145 145
      */
146
-    public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
146
+    public function serviceCheckResult($host, $service, $state, $display, $perfdata='')
147 147
     {
148 148
         //Send a POST request to the URL endpoint /v1/actions/process-check-result
149 149
         //actions/process-check-result?service=example.localdomain!passive-ping6
@@ -162,9 +162,9 @@  discard block
 block discarded – undo
162 162
         {
163 163
             return array(false, $e->getMessage());
164 164
         }
165
-        if (property_exists($result,'error') )
165
+        if (property_exists($result, 'error'))
166 166
         {
167
-            if (property_exists($result,'status'))
167
+            if (property_exists($result, 'status'))
168 168
             {
169 169
                 $message=$result->status;
170 170
             }
@@ -172,21 +172,21 @@  discard block
 block discarded – undo
172 172
             {
173 173
                 $message="Unkown status";
174 174
             }
175
-            return array(false , 'Ret code ' .$result->error.' : '.$message);
175
+            return array(false, 'Ret code '.$result->error.' : '.$message);
176 176
         }
177 177
         if (property_exists($result, 'results'))
178 178
         {
179 179
             if (isset($result->results[0]))
180 180
             {
181
-                return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
181
+                return array(true, 'code '.$result->results[0]->code.' : '.$result->results[0]->status);
182 182
             }
183 183
             else
184 184
             {
185
-                return array(false,'Service not found');
185
+                return array(false, 'Service not found');
186 186
             }
187 187
             
188 188
         }
189
-        return array(false,'Unkown result, open issue with this : '.print_r($result,true));
189
+        return array(false, 'Unkown result, open issue with this : '.print_r($result, true));
190 190
     }
191 191
  
192 192
     /**
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
         $url='objects/hosts';
208 208
         $body=array(
209 209
             "filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
210
-            "attrs"         => array('__name','name','display_name')
210
+            "attrs"         => array('__name', 'name', 'display_name')
211 211
         );
212 212
         try
213 213
         {
@@ -217,24 +217,24 @@  discard block
 block discarded – undo
217 217
             throw new Exception($e->getMessage());
218 218
         }
219 219
         
220
-        if (property_exists($result,'error') )
220
+        if (property_exists($result, 'error'))
221 221
         {
222
-            if (property_exists($result,'status'))
222
+            if (property_exists($result, 'status'))
223 223
             {
224
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
224
+                throw new Exception('Ret code '.$result->error.' : '.$result->status);
225 225
             }
226 226
             else
227 227
             {
228
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
228
+                throw new Exception('Ret code '.$result->error.' : Unkown status');
229 229
             }
230 230
         }
231 231
         if (property_exists($result, 'results'))
232 232
         {
233 233
             $numHost=0;
234 234
             $hostArray=array();
235
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
235
+            while (isset($result->results[$numHost]) && property_exists($result->results[$numHost], 'attrs'))
236 236
             {
237
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
237
+                $hostArray[$numHost]=$result->results[$numHost]->attrs;
238 238
                 $numHost++;
239 239
             }
240 240
             return $hostArray;            
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
         $url='objects/hosts';
254 254
         $body=array(
255 255
             "filter"        => '\"'.$hostGroup.'\" in host.groups',
256
-            "attrs"         => array('address','address','name')
256
+            "attrs"         => array('address', 'address', 'name')
257 257
         );
258 258
         try
259 259
         {
@@ -263,25 +263,25 @@  discard block
 block discarded – undo
263 263
             throw new Exception($e->getMessage());
264 264
         }
265 265
         
266
-        if (property_exists($result,'error') )
266
+        if (property_exists($result, 'error'))
267 267
         {
268
-            if (property_exists($result,'status'))
268
+            if (property_exists($result, 'status'))
269 269
             {
270
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
270
+                throw new Exception('Ret code '.$result->error.' : '.$result->status);
271 271
             }
272 272
             else
273 273
             {
274
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
274
+                throw new Exception('Ret code '.$result->error.' : Unkown status');
275 275
             }
276 276
         }
277 277
         if (property_exists($result, 'results'))
278 278
         {
279 279
             $numHost=0;
280 280
             $hostArray=array();
281
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
281
+            while (isset($result->results[$numHost]) && property_exists($result->results[$numHost], 'attrs'))
282 282
             {
283
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
284
-                $hostArray[$numHost]->name = $result->results[$numHost]->name;
283
+                $hostArray[$numHost]=$result->results[$numHost]->attrs;
284
+                $hostArray[$numHost]->name=$result->results[$numHost]->name;
285 285
                 $numHost++;
286 286
             }
287 287
             return $hostArray;
@@ -299,23 +299,23 @@  discard block
 block discarded – undo
299 299
      * @return array
300 300
      */
301 301
     public function request($method, $url, $headers, $body) {
302
-        $auth = sprintf('%s:%s', $this->user, $this->pass);
303
-        $curlHeaders = array("Accept: application/json");
302
+        $auth=sprintf('%s:%s', $this->user, $this->pass);
303
+        $curlHeaders=array("Accept: application/json");
304 304
         if ($body !== null) {
305
-            $body = json_encode($body);
305
+            $body=json_encode($body);
306 306
             array_push($curlHeaders, 'Content-Type: application/json');
307 307
             //array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
308 308
         }
309 309
         //var_dump($body);
310 310
         //var_dump($this->url($url));
311 311
         if ($headers !== null) {
312
-            $curlFinalHeaders = array_merge($curlHeaders, $headers);
312
+            $curlFinalHeaders=array_merge($curlHeaders, $headers);
313 313
         } else 
314 314
         {
315 315
             $curlFinalHeaders=$curlHeaders;
316 316
         }
317
-        $curl = $this->curl();
318
-        $opts = array(
317
+        $curl=$this->curl();
318
+        $opts=array(
319 319
             CURLOPT_URL		=> $this->url($url),
320 320
             CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
321 321
             CURLOPT_USERPWD		=> $auth,
@@ -326,14 +326,14 @@  discard block
 block discarded – undo
326 326
             CURLOPT_SSL_VERIFYPEER 	=> false,
327 327
         );
328 328
         if ($body !== null) {
329
-            $opts[CURLOPT_POSTFIELDS] = $body;
329
+            $opts[CURLOPT_POSTFIELDS]=$body;
330 330
         }
331 331
         curl_setopt_array($curl, $opts);
332
-        $res = curl_exec($curl);
332
+        $res=curl_exec($curl);
333 333
         if ($res === false) {
334
-            throw new Exception('CURL ERROR: ' . curl_error($curl));
334
+            throw new Exception('CURL ERROR: '.curl_error($curl));
335 335
         }
336
-        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
336
+        $statusCode=curl_getinfo($curl, CURLINFO_HTTP_CODE);
337 337
         if ($statusCode === 401) {
338 338
             throw new Exception('Unable to authenticate, please check your API credentials');
339 339
         }
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
      * @return array json decoded
348 348
      */
349 349
     protected function fromJsonResult($json) {
350
-        $result = @json_decode($json);
350
+        $result=@json_decode($json);
351 351
         //var_dump($json);
352 352
         if ($result === null) {
353 353
             throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
Please login to merge, or discard this patch.
library/Trapdirector/Config/MIBLoader.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -31,10 +31,10 @@  discard block
 block discarded – undo
31 31
 				
32 32
 	}
33 33
 
34
-    /**
35
-     * Get all mibs in db which have at least one trap
36
-     * @return array
37
-     */	
34
+	/**
35
+	 * Get all mibs in db which have at least one trap
36
+	 * @return array
37
+	 */	
38 38
 	
39 39
 	public function getMIBList()
40 40
 	{
@@ -58,9 +58,9 @@  discard block
 block discarded – undo
58 58
 	
59 59
 	
60 60
 	/** Get trap list from a mib 
61
-	*	@param $mib string mib name
62
-	*	@return array : traps
63
-	*/
61
+	 *	@param $mib string mib name
62
+	 *	@return array : traps
63
+	 */
64 64
 	public function getTrapList($mib)
65 65
 	{
66 66
 		$traps=array();
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 		$query=$dbconn->select()
69 69
 				->from(
70 70
 					$this->config->getMIBCacheTableName(),
71
-				    array('name' => 'name', 'oid' => 'oid', 'description' => 'description'))
71
+					array('name' => 'name', 'oid' => 'oid', 'description' => 'description'))
72 72
 				->where("mib = '".$mib."' AND type='21'") ;
73 73
 		$names=$dbconn->fetchAll($query);
74 74
 		foreach ($names as $val)
@@ -79,9 +79,9 @@  discard block
 block discarded – undo
79 79
 	}
80 80
 	
81 81
 	/** Get objects a trap can have
82
-	*	@param string $trap oid of trap
83
-	*	@return array|null : null if trap not found, or array ( <oid> => name/mib/type )
84
-	*/
82
+	 *	@param string $trap oid of trap
83
+	 *	@return array|null : null if trap not found, or array ( <oid> => name/mib/type )
84
+	 */
85 85
 	public function getObjectList($trap)
86 86
 	{
87 87
 		$objects=array();
@@ -97,15 +97,15 @@  discard block
 block discarded – undo
97 97
 		if ( ($id == null) || ! property_exists($id,'id') ) return null;
98 98
 		
99 99
 		$query=$dbconn->select()
100
-		        ->from(
101
-		            array('c' => $this->config->getMIBCacheTableName()),
102
-		            array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
103
-		                'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
104
-		                'description' => 'c.description'))
105
-		        ->join(
106
-		            array('o' => $this->config->getMIBCacheTableTrapObjName()),
107
-		            'o.trap_id='.$id->id )
108
-		        ->where("o.object_id = c.id");
100
+				->from(
101
+					array('c' => $this->config->getMIBCacheTableName()),
102
+					array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
103
+						'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
104
+						'description' => 'c.description'))
105
+				->join(
106
+					array('o' => $this->config->getMIBCacheTableTrapObjName()),
107
+					'o.trap_id='.$id->id )
108
+				->where("o.object_id = c.id");
109 109
 		$listObjects=$dbconn->fetchAll($query);
110 110
 		if ( count($listObjects)==0 ) return null;
111 111
 		
@@ -123,12 +123,12 @@  discard block
 block discarded – undo
123 123
 	}
124 124
 
125 125
 	/** translate oid in MIB::Name 
126
-	*	@param string $oid
127
-	*	@return array|null :  return array with index (oid -> oid, mib -> mib name, name -> oid name, type -> oid type)
128
-	*/
126
+	 *	@param string $oid
127
+	 *	@return array|null :  return array with index (oid -> oid, mib -> mib name, name -> oid name, type -> oid type)
128
+	 */
129 129
 	public function translateOID($oid)
130 130
 	{
131
-	    if (!preg_match('/^\./',$oid)) $oid = '.' . $oid; // Add a leading '.'
131
+		if (!preg_match('/^\./',$oid)) $oid = '.' . $oid; // Add a leading '.'
132 132
 		$retArray=array('oid' => $oid, 'mib' => null, 'name'=>null,'type'=>null);
133 133
 		$dbconn = $this->db;
134 134
 
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
 				->from(
137 137
 					array('o' => $this->config->getMIBCacheTableName()),
138 138
 					array('mib'=>'o.mib','name' => 'o.name','type'=>'o.syntax',
139
-					    'type_enum'=>'o.type_enum', 'description'=>'o.description'))
139
+						'type_enum'=>'o.type_enum', 'description'=>'o.description'))
140 140
 				->where('o.oid=\''.$oid.'\'');
141 141
 		$object=$dbconn->fetchRow($query);
142 142
 		if ($object != null) 
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
 		// Try to get oid name from snmptranslate
153 153
 		$matches=array();
154 154
 		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
155
-		    ' '.$oid);
155
+			' '.$oid);
156 156
 		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
157 157
 		if ($ret_code===0 || $ret_code===false) {
158 158
 			return null;
@@ -164,8 +164,8 @@  discard block
 block discarded – undo
164 164
 			" | grep SYNTAX | sed 's/SYNTAX[[:blank:]]*//'");
165 165
 		if (preg_match('/(.*)\{(.*)\}/',$translate,$matches))
166 166
 		{
167
-		    $retArray['type']=$matches[1];
168
-		    $retArray['type_enum']=$matches[2];
167
+			$retArray['type']=$matches[1];
168
+			$retArray['type_enum']=$matches[2];
169 169
 		}
170 170
 		else
171 171
 		{
@@ -229,25 +229,25 @@  discard block
 block discarded – undo
229 229
 	 */
230 230
 	public function getTrapDetails($oid=null,$id=null)
231 231
 	{	    
232
-	    // Get trap id in DB
233
-	    if ($oid===null)
234
-	    {
235
-	        $where="c.id = '$id'";
236
-	    }
237
-	    else
238
-	    {
239
-	        $where="c.oid = '$oid'";
240
-	    }
241
-	    $query=$this->db->select()
242
-           ->from(
243
-            array('c' => $this->config->getMIBCacheTableName()),
244
-            array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
245
-                'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
246
-                'description' => 'c.description'))
247
-            ->where($where);
248
-        $trap=$this->db->fetchRow($query);
232
+		// Get trap id in DB
233
+		if ($oid===null)
234
+		{
235
+			$where="c.id = '$id'";
236
+		}
237
+		else
238
+		{
239
+			$where="c.oid = '$oid'";
240
+		}
241
+		$query=$this->db->select()
242
+		   ->from(
243
+			array('c' => $this->config->getMIBCacheTableName()),
244
+			array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
245
+				'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
246
+				'description' => 'c.description'))
247
+			->where($where);
248
+		$trap=$this->db->fetchRow($query);
249 249
         
250
-        return $trap;
250
+		return $trap;
251 251
 	}
252 252
 	
253 253
 }
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/MibDatabase.php 1 patch
Indentation   +154 added lines, -154 removed lines patch added patch discarded remove patch
@@ -4,183 +4,183 @@
 block discarded – undo
4 4
 
5 5
 trait MibDatabase
6 6
 {   
7
-    /** @var array $oidDesc MUST be overide by calling class */
8
-    protected $oidDesc;
7
+	/** @var array $oidDesc MUST be overide by calling class */
8
+	protected $oidDesc;
9 9
     
10
-    /** @var array $dbOidIndex MUST be overide by calling class */
11
-    protected $dbOidIndex;
10
+	/** @var array $dbOidIndex MUST be overide by calling class */
11
+	protected $dbOidIndex;
12 12
     
13
-    /** @return \Trapdirector\Logging */
14
-    abstract public function getLogging();
13
+	/** @return \Trapdirector\Logging */
14
+	abstract public function getLogging();
15 15
     
16
-    /** @return \Trapdirector\Database */
17
-    abstract public function getTrapsDB();
16
+	/** @return \Trapdirector\Database */
17
+	abstract public function getTrapsDB();
18 18
 
19 19
     
20
-    /**
21
-     * Update or add an OID to database uses $this->dbOidIndex for mem cache
22
-     * and $this->oidDesc doe data
23
-     * @return number : 0=unchanged, 1 = changed, 2=created
24
-     */
25
-    public function update_oid()
26
-    {
27
-        $db_conn=$this->getTrapsDB()->db_connect_trap();
28
-        // Quote description.
29
-        $this->oidDesc['description']=$db_conn->quote($this->oidDesc['description']);
20
+	/**
21
+	 * Update or add an OID to database uses $this->dbOidIndex for mem cache
22
+	 * and $this->oidDesc doe data
23
+	 * @return number : 0=unchanged, 1 = changed, 2=created
24
+	 */
25
+	public function update_oid()
26
+	{
27
+		$db_conn=$this->getTrapsDB()->db_connect_trap();
28
+		// Quote description.
29
+		$this->oidDesc['description']=$db_conn->quote($this->oidDesc['description']);
30 30
         
31
-        if (isset($this->dbOidIndex[$this->oidDesc['oid']]))
32
-        { // oid exists in db, so update
33
-            return $this->update_oid_update();
34
-        }
35
-        // create new OID.
36
-        return $this->update_oid_create();
31
+		if (isset($this->dbOidIndex[$this->oidDesc['oid']]))
32
+		{ // oid exists in db, so update
33
+			return $this->update_oid_update();
34
+		}
35
+		// create new OID.
36
+		return $this->update_oid_create();
37 37
         
38
-    }
38
+	}
39 39
     
40
-    /**
41
-     * Update object in DB with object in dbOidIndex if name/mib/type has changed.
42
-     * @return number : 0=unchanged, 1 = changed, 2=created
43
-     */
44
-    private function update_oid_update()
45
-    {
40
+	/**
41
+	 * Update object in DB with object in dbOidIndex if name/mib/type has changed.
42
+	 * @return number : 0=unchanged, 1 = changed, 2=created
43
+	 */
44
+	private function update_oid_update()
45
+	{
46 46
         
47
-        $db_conn=$this->getTrapsDB()->db_connect_trap();
47
+		$db_conn=$this->getTrapsDB()->db_connect_trap();
48 48
         
49
-        if ($this->dbOidIndex[$this->oidDesc['oid']]['key'] == -1)
50
-        { // newly created.
51
-            return 0;
52
-        }
53
-        $oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
54
-        $dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
55
-        if ( $this->oidDesc['name'] != $dbOid['name'] ||
56
-            $this->oidDesc['mib'] != $dbOid['mib'] ||
57
-            $this->oidDesc['type'] !=$dbOid['type']
58
-            )
59
-        { // Do update
60
-            $sql='UPDATE '.$this->getTrapsDB()->dbPrefix.'mib_cache SET '.
61
-                'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'.
62
-                ', syntax = :syntax, type_enum = :type_enum, description = :description '.
63
-                ' WHERE id= :id';
64
-            $sqlQuery=$db_conn->prepare($sql);
49
+		if ($this->dbOidIndex[$this->oidDesc['oid']]['key'] == -1)
50
+		{ // newly created.
51
+			return 0;
52
+		}
53
+		$oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
54
+		$dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
55
+		if ( $this->oidDesc['name'] != $dbOid['name'] ||
56
+			$this->oidDesc['mib'] != $dbOid['mib'] ||
57
+			$this->oidDesc['type'] !=$dbOid['type']
58
+			)
59
+		{ // Do update
60
+			$sql='UPDATE '.$this->getTrapsDB()->dbPrefix.'mib_cache SET '.
61
+				'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'.
62
+				', syntax = :syntax, type_enum = :type_enum, description = :description '.
63
+				' WHERE id= :id';
64
+			$sqlQuery=$db_conn->prepare($sql);
65 65
             
66
-            $sqlParam=array(
67
-                ':name' => $this->oidDesc['name'],
68
-                ':type' => $this->oidDesc['type'],
69
-                ':mib' => $this->oidDesc['mib'],
70
-                ':tc' =>  $this->oidDesc['textconv']??'null',
71
-                ':display_hint' => $this->oidDesc['dispHint']??'null' ,
72
-                ':syntax' => $this->oidDesc['syntax']==null??'null',
73
-                ':type_enum' => $this->oidDesc['type_enum']??'null',
74
-                ':description' => $this->oidDesc['description']??'null',
75
-                ':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
76
-            );
66
+			$sqlParam=array(
67
+				':name' => $this->oidDesc['name'],
68
+				':type' => $this->oidDesc['type'],
69
+				':mib' => $this->oidDesc['mib'],
70
+				':tc' =>  $this->oidDesc['textconv']??'null',
71
+				':display_hint' => $this->oidDesc['dispHint']??'null' ,
72
+				':syntax' => $this->oidDesc['syntax']==null??'null',
73
+				':type_enum' => $this->oidDesc['type_enum']??'null',
74
+				':description' => $this->oidDesc['description']??'null',
75
+				':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
76
+			);
77 77
             
78
-            if ($sqlQuery->execute($sqlParam) === false) {
79
-                $this->getLogging()->log('Error in query : ' . $sql,ERROR,'');
80
-            }
81
-            $this->getLogging()->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
82
-            return 1;
83
-        }
84
-        else
85
-        {
86
-            $this->getLogging()->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
87
-            return 0;
88
-        }
89
-    }
78
+			if ($sqlQuery->execute($sqlParam) === false) {
79
+				$this->getLogging()->log('Error in query : ' . $sql,ERROR,'');
80
+			}
81
+			$this->getLogging()->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
82
+			return 1;
83
+		}
84
+		else
85
+		{
86
+			$this->getLogging()->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
87
+			return 0;
88
+		}
89
+	}
90 90
 
91
-    /**
92
-     * Create object in DB with object in dbOidIndex
93
-     * @return number : 0=unchanged, 1 = changed, 2=created
94
-     */
95
-    private function update_oid_create()
96
-    {
97
-        // Insert data
91
+	/**
92
+	 * Create object in DB with object in dbOidIndex
93
+	 * @return number : 0=unchanged, 1 = changed, 2=created
94
+	 */
95
+	private function update_oid_create()
96
+	{
97
+		// Insert data
98 98
         
99
-        $db_conn=$this->getTrapsDB()->db_connect_trap();
100
-        $sql='INSERT INTO '.$this->getTrapsDB()->dbPrefix.'mib_cache '.
101
-            '(oid, name, type , mib, textual_convention, display_hint '.
102
-            ', syntax, type_enum , description ) ' .
103
-            'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
104
-            ', :syntax, :type_enum, :description )';
99
+		$db_conn=$this->getTrapsDB()->db_connect_trap();
100
+		$sql='INSERT INTO '.$this->getTrapsDB()->dbPrefix.'mib_cache '.
101
+			'(oid, name, type , mib, textual_convention, display_hint '.
102
+			', syntax, type_enum , description ) ' .
103
+			'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
104
+			', :syntax, :type_enum, :description )';
105 105
         
106
-        if ($this->getTrapsDB()->trapDBType == 'pgsql') $sql .= 'RETURNING id';
106
+		if ($this->getTrapsDB()->trapDBType == 'pgsql') $sql .= 'RETURNING id';
107 107
         
108
-        $sqlQuery=$db_conn->prepare($sql);
108
+		$sqlQuery=$db_conn->prepare($sql);
109 109
         
110
-        $sqlParam=array(
111
-            ':oid' => $this->oidDesc['oid'],
112
-            ':name' => $this->oidDesc['name'],
113
-            ':type' => $this->oidDesc['type'],
114
-            ':mib' => $this->oidDesc['mib'],
115
-            ':tc' =>  $this->oidDesc['textconv']??'null',
116
-            ':display_hint' => $this->oidDesc['dispHint']??'null',
117
-            ':syntax' => $this->oidDesc['syntax']??'null',
118
-            ':type_enum' => $this->oidDesc['type_enum']??'null',
119
-            ':description' => $this->oidDesc['description']??'null'
120
-        );
110
+		$sqlParam=array(
111
+			':oid' => $this->oidDesc['oid'],
112
+			':name' => $this->oidDesc['name'],
113
+			':type' => $this->oidDesc['type'],
114
+			':mib' => $this->oidDesc['mib'],
115
+			':tc' =>  $this->oidDesc['textconv']??'null',
116
+			':display_hint' => $this->oidDesc['dispHint']??'null',
117
+			':syntax' => $this->oidDesc['syntax']??'null',
118
+			':type_enum' => $this->oidDesc['type_enum']??'null',
119
+			':description' => $this->oidDesc['description']??'null'
120
+		);
121 121
         
122
-        if ($sqlQuery->execute($sqlParam) === false) {
123
-            $this->getLogging()->log('Error in query : ' . $sql,1,'');
124
-        }
122
+		if ($sqlQuery->execute($sqlParam) === false) {
123
+			$this->getLogging()->log('Error in query : ' . $sql,1,'');
124
+		}
125 125
         
126
-        switch ($this->getTrapsDB()->trapDBType)
127
-        {
128
-            case 'pgsql':
129
-                // Get last id to insert oid/values in secondary table
130
-                if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
131
-                    $this->getLogging()->log('Error getting id - pgsql - ',1,'');
132
-                }
133
-                if (! isset($inserted_id_ret['id'])) {
134
-                    $this->getLogging()->log('Error getting id - pgsql - empty.',ERROR);
135
-                    return 0;
136
-                }
137
-                $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
138
-                break;
139
-            case 'mysql':
140
-                // Get last id to insert oid/values in secondary table
141
-                $sql='SELECT LAST_INSERT_ID();';
142
-                if (($ret_code=$db_conn->query($sql)) === false) {
143
-                    $this->getLogging()->log('Erreur getting id - mysql - ',ERROR);
144
-                    return 0;
145
-                }
126
+		switch ($this->getTrapsDB()->trapDBType)
127
+		{
128
+			case 'pgsql':
129
+				// Get last id to insert oid/values in secondary table
130
+				if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
131
+					$this->getLogging()->log('Error getting id - pgsql - ',1,'');
132
+				}
133
+				if (! isset($inserted_id_ret['id'])) {
134
+					$this->getLogging()->log('Error getting id - pgsql - empty.',ERROR);
135
+					return 0;
136
+				}
137
+				$this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
138
+				break;
139
+			case 'mysql':
140
+				// Get last id to insert oid/values in secondary table
141
+				$sql='SELECT LAST_INSERT_ID();';
142
+				if (($ret_code=$db_conn->query($sql)) === false) {
143
+					$this->getLogging()->log('Erreur getting id - mysql - ',ERROR);
144
+					return 0;
145
+				}
146 146
                 
147
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
148
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
149
-                $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
150
-                break;
151
-            default:
152
-                $this->getLogging()->log('Error SQL type Unknown : '.$this->getTrapsDB()->trapDBType,ERROR);
153
-                return 0;
154
-        }
147
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
148
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
149
+				$this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
150
+				break;
151
+			default:
152
+				$this->getLogging()->log('Error SQL type Unknown : '.$this->getTrapsDB()->trapDBType,ERROR);
153
+				return 0;
154
+		}
155 155
         
156
-        // Set as newly created.
157
-        $this->dbOidIndex[$this->oidDesc['oid']]['key']=-1;
158
-        return 2;
159
-    }
156
+		// Set as newly created.
157
+		$this->dbOidIndex[$this->oidDesc['oid']]['key']=-1;
158
+		return 2;
159
+	}
160 160
 
161
-    /**
162
-     * get all objects for a trap.
163
-     * @param integer $trapId
164
-     * @return array : array of cached objects
165
-     */
166
-    private function cache_db_objects($trapId)
167
-    {
168
-        $dbObjects=array(); // cache of objects for trap in db
169
-        $db_conn=$this->getTrapsDB()->db_connect_trap();
170
-        // Get all objects
171
-        $sql='SELECT * FROM '.$this->getTrapsDB()->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
172
-        $this->getLogging()->log('SQL query get all traps: '.$sql,DEBUG );
173
-        if (($ret_code=$db_conn->query($sql)) === false) {
174
-            $this->getLogging()->log('No result in query : ' . $sql,1,'');
175
-        }
176
-        $dbObjectsRaw=$ret_code->fetchAll();
161
+	/**
162
+	 * get all objects for a trap.
163
+	 * @param integer $trapId
164
+	 * @return array : array of cached objects
165
+	 */
166
+	private function cache_db_objects($trapId)
167
+	{
168
+		$dbObjects=array(); // cache of objects for trap in db
169
+		$db_conn=$this->getTrapsDB()->db_connect_trap();
170
+		// Get all objects
171
+		$sql='SELECT * FROM '.$this->getTrapsDB()->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
172
+		$this->getLogging()->log('SQL query get all traps: '.$sql,DEBUG );
173
+		if (($ret_code=$db_conn->query($sql)) === false) {
174
+			$this->getLogging()->log('No result in query : ' . $sql,1,'');
175
+		}
176
+		$dbObjectsRaw=$ret_code->fetchAll();
177 177
         
178
-        foreach ($dbObjectsRaw as $val)
179
-        {
180
-            $dbObjects[$val['object_id']]=1;
181
-        }
182
-        return $dbObjects;
183
-    }
178
+		foreach ($dbObjectsRaw as $val)
179
+		{
180
+			$dbObjects[$val['object_id']]=1;
181
+		}
182
+		return $dbObjects;
183
+	}
184 184
     
185 185
 
186 186
 }
187 187
\ No newline at end of file
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Plugins.php 1 patch
Indentation   +457 added lines, -457 removed lines patch added patch discarded remove patch
@@ -17,519 +17,519 @@
 block discarded – undo
17 17
  */
18 18
 class Plugins
19 19
 {
20
-    /** Array of plugin objects. Keys ar plugin name
21
-     * @var PluginTemplate[] $pluginsList Plugins array with name as index
22
-     * $pluginsList[plugin name]['object']  : plugin object (NULL of not loaded)
23
-     * $pluginsList[plugin name]['allOID']  : bool true if plugin catches all oid
24
-     * $pluginsList[plugin name]['target']  : bool true if plugin can be trap processing target
25
-     * $pluginsList[plugin name]['enabled'] : bool true if plugin is in enabled list 
26
-     **/
27
-    protected $pluginsList = array();
20
+	/** Array of plugin objects. Keys ar plugin name
21
+	 * @var PluginTemplate[] $pluginsList Plugins array with name as index
22
+	 * $pluginsList[plugin name]['object']  : plugin object (NULL of not loaded)
23
+	 * $pluginsList[plugin name]['allOID']  : bool true if plugin catches all oid
24
+	 * $pluginsList[plugin name]['target']  : bool true if plugin can be trap processing target
25
+	 * $pluginsList[plugin name]['enabled'] : bool true if plugin is in enabled list 
26
+	 **/
27
+	protected $pluginsList = array();
28 28
 
29
-    /** Array of functions names
30
-     * @var array $functionList 
31
-     * $functionList[name]['plugin'] : Plugin name
32
-     * $functionList[name]['function'] : Plugin function to call (null if plugin not loaded)
33
-    */
34
-    protected $functionList=array();
29
+	/** Array of functions names
30
+	 * @var array $functionList 
31
+	 * $functionList[name]['plugin'] : Plugin name
32
+	 * $functionList[name]['function'] : Plugin function to call (null if plugin not loaded)
33
+	 */
34
+	protected $functionList=array();
35 35
     
36
-    /** @var string[] $enabledPlugins list of enabled plugins */
37
-    //public $enabledPlugins = array();
36
+	/** @var string[] $enabledPlugins list of enabled plugins */
37
+	//public $enabledPlugins = array();
38 38
 
39 39
     
40
-    /** @var Logging $logClass */
41
-    protected $logClass;
40
+	/** @var Logging $logClass */
41
+	protected $logClass;
42 42
 
43
-    /** @var Trap $trapClass */
44
-    protected $trapClass;
43
+	/** @var Trap $trapClass */
44
+	protected $trapClass;
45 45
     
46
-    /** @var string $pluginDir */
47
-    protected $pluginDir;
46
+	/** @var string $pluginDir */
47
+	protected $pluginDir;
48 48
     
49
-    /** Setup class
50
-     * @param Trap $logClass  the top trap class
51
-     * @param string $plugin_dir optional plugin directory
52
-     * @throws \Exception
53
-     */
54
-    function __construct(Trap $trapClass,string $pluginDir='')
55
-    {
56
-        if ($pluginDir == '')
57
-        {
58
-            $this->pluginDir=dirname(__DIR__).'/Plugins';
59
-        }
60
-        else 
61
-        {
62
-            $this->pluginDir=$pluginDir;
63
-        }
64
-        // Set and check Logging class
65
-        $this->trapClass=$trapClass;
66
-        if ($this->trapClass === null)
67
-        {
68
-            throw new Exception('Log class not loaded into trap class');
69
-        }
70
-        $this->logClass=$trapClass->logging;
71
-        if ($this->logClass === null)
72
-        {
73
-            throw new Exception('Log class not loaded into trap class');
74
-        }
75
-        // check DB class and get plugins list.
76
-        if ($this->trapClass->trapsDB === null)
77
-        {
78
-            throw new Exception('Database class not loaded into trap class');
79
-        }
80
-        $this->loadEnabledPlugins();
81
-    }
49
+	/** Setup class
50
+	 * @param Trap $logClass  the top trap class
51
+	 * @param string $plugin_dir optional plugin directory
52
+	 * @throws \Exception
53
+	 */
54
+	function __construct(Trap $trapClass,string $pluginDir='')
55
+	{
56
+		if ($pluginDir == '')
57
+		{
58
+			$this->pluginDir=dirname(__DIR__).'/Plugins';
59
+		}
60
+		else 
61
+		{
62
+			$this->pluginDir=$pluginDir;
63
+		}
64
+		// Set and check Logging class
65
+		$this->trapClass=$trapClass;
66
+		if ($this->trapClass === null)
67
+		{
68
+			throw new Exception('Log class not loaded into trap class');
69
+		}
70
+		$this->logClass=$trapClass->logging;
71
+		if ($this->logClass === null)
72
+		{
73
+			throw new Exception('Log class not loaded into trap class');
74
+		}
75
+		// check DB class and get plugins list.
76
+		if ($this->trapClass->trapsDB === null)
77
+		{
78
+			throw new Exception('Database class not loaded into trap class');
79
+		}
80
+		$this->loadEnabledPlugins();
81
+	}
82 82
     
83 83
     
84
-    /**
85
-     * Load enabled plugins from database config table.
86
-     * Fills enabledPlugins and functionList properties
87
-     * @throws \Exception
88
-     */
89
-    private function loadEnabledPlugins()
90
-    {
91
-        $PluginList = $this->trapClass->trapsDB->getDBConfig('enabled_plugins');
84
+	/**
85
+	 * Load enabled plugins from database config table.
86
+	 * Fills enabledPlugins and functionList properties
87
+	 * @throws \Exception
88
+	 */
89
+	private function loadEnabledPlugins()
90
+	{
91
+		$PluginList = $this->trapClass->trapsDB->getDBConfig('enabled_plugins');
92 92
                
93
-        if ($PluginList === null || $PluginList == '')
94
-        {
95
-            $this->logClass->log('No enabled plugins',DEBUG);
96
-            return;
97
-        }
98
-        else
99
-        {   // Saved config : <plugin name>;<Catch all OID ? 1|0>;<Trap target ? 1|0>;<func 1 name>|<func 2 name>... ,<plugin2 name>....
100
-            $this->logClass->log('Enabled plugins = '.$PluginList,DEBUG);
93
+		if ($PluginList === null || $PluginList == '')
94
+		{
95
+			$this->logClass->log('No enabled plugins',DEBUG);
96
+			return;
97
+		}
98
+		else
99
+		{   // Saved config : <plugin name>;<Catch all OID ? 1|0>;<Trap target ? 1|0>;<func 1 name>|<func 2 name>... ,<plugin2 name>....
100
+			$this->logClass->log('Enabled plugins = '.$PluginList,DEBUG);
101 101
             
102
-            $pluginArray = explode(',', $PluginList);
103
-            foreach ($pluginArray as $pluginElmt)
104
-            {
105
-                $pluginElmt = explode(';',$pluginElmt);
106
-                if ($pluginElmt === false || count($pluginElmt) != 4)
107
-                {
108
-                    throw new \Exception('Invalid plugin configuration : '. $PluginList );
109
-                }
110
-                $pluginName=$pluginElmt[0];
102
+			$pluginArray = explode(',', $PluginList);
103
+			foreach ($pluginArray as $pluginElmt)
104
+			{
105
+				$pluginElmt = explode(';',$pluginElmt);
106
+				if ($pluginElmt === false || count($pluginElmt) != 4)
107
+				{
108
+					throw new \Exception('Invalid plugin configuration : '. $PluginList );
109
+				}
110
+				$pluginName=$pluginElmt[0];
111 111
                 
112
-                $pluginListElmt = array();
113
-                $pluginListElmt['object'] = null; // class not loaded
114
-                $pluginListElmt['allOID'] = ($pluginElmt[1]=='1') ? true : false;
115
-                $pluginListElmt['target'] = ($pluginElmt[2]=='1') ? true : false;
116
-                $pluginListElmt['enabled'] = true;
112
+				$pluginListElmt = array();
113
+				$pluginListElmt['object'] = null; // class not loaded
114
+				$pluginListElmt['allOID'] = ($pluginElmt[1]=='1') ? true : false;
115
+				$pluginListElmt['target'] = ($pluginElmt[2]=='1') ? true : false;
116
+				$pluginListElmt['enabled'] = true;
117 117
                 
118
-                $this->pluginsList[$pluginName] = $pluginListElmt;
118
+				$this->pluginsList[$pluginName] = $pluginListElmt;
119 119
                 
120
-                // deal with plugin functions
121
-                $pluginFunctions = explode('|',$pluginElmt[3]);
122
-                if ($pluginFunctions !== false)
123
-                {
124
-                    foreach ($pluginFunctions as $function)
125
-                    {
126
-                        $this->functionList[$function] = array(
127
-                            'plugin'    =>   $pluginName,
128
-                            'function'  =>  null
129
-                        );
130
-                    }
131
-                }
132
-            }
120
+				// deal with plugin functions
121
+				$pluginFunctions = explode('|',$pluginElmt[3]);
122
+				if ($pluginFunctions !== false)
123
+				{
124
+					foreach ($pluginFunctions as $function)
125
+					{
126
+						$this->functionList[$function] = array(
127
+							'plugin'    =>   $pluginName,
128
+							'function'  =>  null
129
+						);
130
+					}
131
+				}
132
+			}
133 133
 
134
-        }
134
+		}
135 135
         
136
-    }
136
+	}
137 137
 
138
-    /**
139
-     * Save enabled plugin array in DB config
140
-     * @return bool true if OK, or false (error logged by DB Class)
141
-     */
142
-    private function saveEnabledPlugins()
143
-    {
144
-        $saveString='';
145
-        foreach ($this->pluginsList as $name => $value)
146
-        {
147
-            if ($value['enabled'] == false)
148
-            {
149
-                continue;
150
-            }
151
-            $functionString='';
152
-            foreach ($this->functionList as $fName => $fvalue)
153
-            {
154
-                if ($fvalue['plugin'] != $name)
155
-                {
156
-                    continue;
157
-                }
158
-                $functionString .= ($functionString == '') ? '' : '|'; // add separator if not empty
159
-                $functionString .= $fName;
160
-            }
161
-            $saveString .= ($saveString == '')?'':',' ;
138
+	/**
139
+	 * Save enabled plugin array in DB config
140
+	 * @return bool true if OK, or false (error logged by DB Class)
141
+	 */
142
+	private function saveEnabledPlugins()
143
+	{
144
+		$saveString='';
145
+		foreach ($this->pluginsList as $name => $value)
146
+		{
147
+			if ($value['enabled'] == false)
148
+			{
149
+				continue;
150
+			}
151
+			$functionString='';
152
+			foreach ($this->functionList as $fName => $fvalue)
153
+			{
154
+				if ($fvalue['plugin'] != $name)
155
+				{
156
+					continue;
157
+				}
158
+				$functionString .= ($functionString == '') ? '' : '|'; // add separator if not empty
159
+				$functionString .= $fName;
160
+			}
161
+			$saveString .= ($saveString == '')?'':',' ;
162 162
             
163
-            $allOID = ($value['allOID'] === true) ? 1 : 0;
164
-            $target = ($value['target'] === true) ? 1 : 0;
165
-            $saveString .= $name . ';' . $allOID . ';' . $target . ';' . $functionString ;
166
-        }
167
-        $this->logClass->log('Saving : ' . $saveString,DEBUG);
168
-        return $this->trapClass->trapsDB->setDBConfig('enabled_plugins', $saveString);
169
-    }
163
+			$allOID = ($value['allOID'] === true) ? 1 : 0;
164
+			$target = ($value['target'] === true) ? 1 : 0;
165
+			$saveString .= $name . ';' . $allOID . ';' . $target . ';' . $functionString ;
166
+		}
167
+		$this->logClass->log('Saving : ' . $saveString,DEBUG);
168
+		return $this->trapClass->trapsDB->setDBConfig('enabled_plugins', $saveString);
169
+	}
170 170
     
171
-    /** Get enabled plugin list by name
172
-     * @return array
173
-     */
174
-    public function getEnabledPlugins() : array
175
-    {
176
-        $retArray=array();
177
-        foreach ($this->pluginsList as $name => $value)
178
-        {
179
-            if ($value['enabled'] == true)
180
-            {
181
-                array_push($retArray,$name);
182
-            }
183
-        }
184
-        return $retArray;
185
-    }
171
+	/** Get enabled plugin list by name
172
+	 * @return array
173
+	 */
174
+	public function getEnabledPlugins() : array
175
+	{
176
+		$retArray=array();
177
+		foreach ($this->pluginsList as $name => $value)
178
+		{
179
+			if ($value['enabled'] == true)
180
+			{
181
+				array_push($retArray,$name);
182
+			}
183
+		}
184
+		return $retArray;
185
+	}
186 186
 
187
-    /** Enable plugin (enabling an enabled plugin is OK, same for disabled).
188
-     *  and save in DB config
189
-     * @param string $pluginName
190
-     * @param bool $enabled true to enable, false to disable
191
-     * @return bool true if OK, or false (error logged)
192
-     */
193
-    public function enablePlugin(string $pluginName,bool $enabled)
194
-    {
195
-        if ($enabled === false)
196
-        {
197
-            // If plugin is defined set to disable
198
-            if ( isset($this->pluginsList[$pluginName]))
199
-            {
200
-                $this->pluginsList[$pluginName]['enabled'] = false;
201
-            }            
202
-            return $this->saveEnabledPlugins();
203
-        }
204
-        // Check if plugin is loaded / exists
205
-        if ( ! isset($this->pluginsList[$pluginName]) || 
206
-                $this->pluginsList[$pluginName]['object'] === null)
207
-        {
208
-            try {
209
-                $this->registerPlugin($pluginName);
210
-            } catch (Exception $e) {
211
-                $this->logClass->log('Cannot enable plugin : ' . $e->getMessage(),WARN);
212
-                return false;
213
-            }
214
-        }
215
-        $this->pluginsList[$pluginName]['enabled'] = true;
216
-        // save in DB and return 
217
-        return $this->saveEnabledPlugins();
218
-    }
187
+	/** Enable plugin (enabling an enabled plugin is OK, same for disabled).
188
+	 *  and save in DB config
189
+	 * @param string $pluginName
190
+	 * @param bool $enabled true to enable, false to disable
191
+	 * @return bool true if OK, or false (error logged)
192
+	 */
193
+	public function enablePlugin(string $pluginName,bool $enabled)
194
+	{
195
+		if ($enabled === false)
196
+		{
197
+			// If plugin is defined set to disable
198
+			if ( isset($this->pluginsList[$pluginName]))
199
+			{
200
+				$this->pluginsList[$pluginName]['enabled'] = false;
201
+			}            
202
+			return $this->saveEnabledPlugins();
203
+		}
204
+		// Check if plugin is loaded / exists
205
+		if ( ! isset($this->pluginsList[$pluginName]) || 
206
+				$this->pluginsList[$pluginName]['object'] === null)
207
+		{
208
+			try {
209
+				$this->registerPlugin($pluginName);
210
+			} catch (Exception $e) {
211
+				$this->logClass->log('Cannot enable plugin : ' . $e->getMessage(),WARN);
212
+				return false;
213
+			}
214
+		}
215
+		$this->pluginsList[$pluginName]['enabled'] = true;
216
+		// save in DB and return 
217
+		return $this->saveEnabledPlugins();
218
+	}
219 219
    
220
-    /**
221
-     * Destroy plugin objects and reload them with new enabled list.
222
-     * TODO : Code this function (ref DAEMON_MODE)
223
-     */
224
-    public function reloadAllPlugins()
225
-    {
226
-        return;
227
-    }
220
+	/**
221
+	 * Destroy plugin objects and reload them with new enabled list.
222
+	 * TODO : Code this function (ref DAEMON_MODE)
223
+	 */
224
+	public function reloadAllPlugins()
225
+	{
226
+		return;
227
+	}
228 228
  
229
-    /** Load plugin by name. Create entry if not in $pluginsList
230
-     * @param string $pluginName Plugin name to load
231
-     * @return bool true if created, false if already loaded
232
-     * @throws Exception on error loading plugin
233
-     */
234
-    public function registerPlugin(string $pluginName)
235
-    {
236
-        if ( ! isset($this->pluginsList[$pluginName]) ) // Plugin isn't enable, create entry
237
-        {
238
-            $pluginListElmt = array();
239
-            $pluginListElmt['object'] = null; // class not loaded
240
-            $pluginListElmt['enabled'] = false;
241
-            $this->pluginsList[$pluginName] = $pluginListElmt;
242
-        }
229
+	/** Load plugin by name. Create entry if not in $pluginsList
230
+	 * @param string $pluginName Plugin name to load
231
+	 * @return bool true if created, false if already loaded
232
+	 * @throws Exception on error loading plugin
233
+	 */
234
+	public function registerPlugin(string $pluginName)
235
+	{
236
+		if ( ! isset($this->pluginsList[$pluginName]) ) // Plugin isn't enable, create entry
237
+		{
238
+			$pluginListElmt = array();
239
+			$pluginListElmt['object'] = null; // class not loaded
240
+			$pluginListElmt['enabled'] = false;
241
+			$this->pluginsList[$pluginName] = $pluginListElmt;
242
+		}
243 243
         
244
-        if ($this->pluginsList[$pluginName]['object'] !== null)
245
-        {
246
-            return false;
247
-        }
248
-        try {
249
-            // Include plugin file
250
-            include_once($this->pluginDir.'/' . $pluginName . '.php');
244
+		if ($this->pluginsList[$pluginName]['object'] !== null)
245
+		{
246
+			return false;
247
+		}
248
+		try {
249
+			// Include plugin file
250
+			include_once($this->pluginDir.'/' . $pluginName . '.php');
251 251
             
252
-            // Create full class name with namespace
253
-            $pluginClassName = __NAMESPACE__ . '\\Plugins\\' . $pluginName;
252
+			// Create full class name with namespace
253
+			$pluginClassName = __NAMESPACE__ . '\\Plugins\\' . $pluginName;
254 254
             
255
-            // Create class
256
-            $newClass = new $pluginClassName();
255
+			// Create class
256
+			$newClass = new $pluginClassName();
257 257
             
258
-            // Set logging
259
-            $newClass->setLoggingClass($this->logClass);
258
+			// Set logging
259
+			$newClass->setLoggingClass($this->logClass);
260 260
             
261
-            // Add in plugin array
262
-            $this->pluginsList[$pluginName]['object']=$newClass;
263
-            $this->pluginsList[$pluginName]['allOID']=$newClass->catchAllTraps;
264
-            $this->pluginsList[$pluginName]['target']=$newClass->processTraps;
261
+			// Add in plugin array
262
+			$this->pluginsList[$pluginName]['object']=$newClass;
263
+			$this->pluginsList[$pluginName]['allOID']=$newClass->catchAllTraps;
264
+			$this->pluginsList[$pluginName]['target']=$newClass->processTraps;
265 265
             
266
-            // Delete old functions
267
-            foreach ($this->functionList as $fname => $fvalue)
268
-            {
269
-                if ($fvalue['plugin'] == $pluginName)
270
-                {
271
-                    unset($this->functionList[$fname]);
272
-                }
273
-            }
274
-            // Add functions
275
-            foreach ($newClass->functions as $fname => $function)
276
-            {
277
-                if (isset($this->functionList[$fname]))
278
-                {
279
-                    if ($this->functionList[$fname]['plugin'] != $pluginName )
280
-                    {
281
-                        throw new Exception('Duplicate function name '.$fname . ' in ' 
282
-                            . $pluginName . ' and ' . $this->functionList[$fname]['plugin']);
283
-                    }
266
+			// Delete old functions
267
+			foreach ($this->functionList as $fname => $fvalue)
268
+			{
269
+				if ($fvalue['plugin'] == $pluginName)
270
+				{
271
+					unset($this->functionList[$fname]);
272
+				}
273
+			}
274
+			// Add functions
275
+			foreach ($newClass->functions as $fname => $function)
276
+			{
277
+				if (isset($this->functionList[$fname]))
278
+				{
279
+					if ($this->functionList[$fname]['plugin'] != $pluginName )
280
+					{
281
+						throw new Exception('Duplicate function name '.$fname . ' in ' 
282
+							. $pluginName . ' and ' . $this->functionList[$fname]['plugin']);
283
+					}
284 284
                     
285
-                }
286
-                else
287
-                {
288
-                    $this->functionList[$fname]=array();
289
-                    $this->functionList[$fname]['plugin'] = $pluginName;
290
-                }
291
-                $this->functionList[$fname]['function']=$function['function'];
292
-            }
293
-            $this->logClass->log('Registered plugin '.$pluginName,DEBUG);
285
+				}
286
+				else
287
+				{
288
+					$this->functionList[$fname]=array();
289
+					$this->functionList[$fname]['plugin'] = $pluginName;
290
+				}
291
+				$this->functionList[$fname]['function']=$function['function'];
292
+			}
293
+			$this->logClass->log('Registered plugin '.$pluginName,DEBUG);
294 294
             
295
-        } catch (Exception $e) {
296
-            unset($this->pluginsList[$pluginName]);
297
-            $errorMessage = "Error registering plugin $pluginName : ".$e->getMessage();
298
-            $this->logClass->log($errorMessage,WARN);
299
-            // Disable the plugin
300
-            $this->enablePlugin($pluginName, false);
301
-            throw new \Exception($errorMessage);
302
-        } catch (Throwable $t) {
303
-            unset($this->pluginsList[$pluginName]);
304
-            $errorMessage = $t->getMessage() . ' in file ' . $t->getFile() . ' line ' . $t->getLine();
305
-            $this->logClass->log($errorMessage,WARN);
306
-            // Disable the plugin
307
-            $this->enablePlugin($pluginName, false);
308
-            throw new \Exception($errorMessage);
309
-        }
310
-        return true;
311
-    }
295
+		} catch (Exception $e) {
296
+			unset($this->pluginsList[$pluginName]);
297
+			$errorMessage = "Error registering plugin $pluginName : ".$e->getMessage();
298
+			$this->logClass->log($errorMessage,WARN);
299
+			// Disable the plugin
300
+			$this->enablePlugin($pluginName, false);
301
+			throw new \Exception($errorMessage);
302
+		} catch (Throwable $t) {
303
+			unset($this->pluginsList[$pluginName]);
304
+			$errorMessage = $t->getMessage() . ' in file ' . $t->getFile() . ' line ' . $t->getLine();
305
+			$this->logClass->log($errorMessage,WARN);
306
+			// Disable the plugin
307
+			$this->enablePlugin($pluginName, false);
308
+			throw new \Exception($errorMessage);
309
+		}
310
+		return true;
311
+	}
312 312
     
313
-    /** Registers all plugins (check=false) or only those with name present in array (check=true)
314
-     * @param bool $checkEnabled Check if plugin is enabled before loading it
315
-     * @return string Errors encountered while registering plugins
316
-     */
317
-    public function registerAllPlugins(bool $checkEnabled=true)
318
-    {
319
-        $retDisplay='';
320
-        // First load enabled plugins
321
-        foreach (array_keys($this->pluginsList) as $pluginName)
322
-        {
323
-            try {
324
-                $this->registerPlugin($pluginName);
325
-            } catch (Exception $e) {
326
-                $retDisplay .= $e->getMessage() . ' / ';
327
-            }
328
-        }
329
-        if ($checkEnabled === false) // Load all php files in plugin dir
330
-        {
331
-            foreach (glob($this->pluginDir."/*.php") as $filename)
332
-            {             
333
-                $pluginName=basename($filename,'.php');
334
-                if (!preg_match('/^[a-zA-Z0-9]+$/',$pluginName))
335
-                {
336
-                    $this->logClass->log("Invalid plugin name : ".$pluginName, WARN);
337
-                    $retDisplay .= "Invalid plugin name : ".$pluginName . " / ";
338
-                    break;
339
-                }
340
-                try { // Already registerd plugin will simply return false
341
-                    $this->registerPlugin($pluginName);               
342
-                } catch (Exception $e) {
343
-                    $retDisplay .= $e->getMessage() . ' / ';
344
-                }
345
-            }
346
-        }
313
+	/** Registers all plugins (check=false) or only those with name present in array (check=true)
314
+	 * @param bool $checkEnabled Check if plugin is enabled before loading it
315
+	 * @return string Errors encountered while registering plugins
316
+	 */
317
+	public function registerAllPlugins(bool $checkEnabled=true)
318
+	{
319
+		$retDisplay='';
320
+		// First load enabled plugins
321
+		foreach (array_keys($this->pluginsList) as $pluginName)
322
+		{
323
+			try {
324
+				$this->registerPlugin($pluginName);
325
+			} catch (Exception $e) {
326
+				$retDisplay .= $e->getMessage() . ' / ';
327
+			}
328
+		}
329
+		if ($checkEnabled === false) // Load all php files in plugin dir
330
+		{
331
+			foreach (glob($this->pluginDir."/*.php") as $filename)
332
+			{             
333
+				$pluginName=basename($filename,'.php');
334
+				if (!preg_match('/^[a-zA-Z0-9]+$/',$pluginName))
335
+				{
336
+					$this->logClass->log("Invalid plugin name : ".$pluginName, WARN);
337
+					$retDisplay .= "Invalid plugin name : ".$pluginName . " / ";
338
+					break;
339
+				}
340
+				try { // Already registerd plugin will simply return false
341
+					$this->registerPlugin($pluginName);               
342
+				} catch (Exception $e) {
343
+					$retDisplay .= $e->getMessage() . ' / ';
344
+				}
345
+			}
346
+		}
347 347
         
348
-        if ($retDisplay == '')
349
-        {
350
-            return 'All plugins loaded OK';
351
-        }
352
-        else
353
-        {
354
-            return $retDisplay;
355
-        }
356
-    }
348
+		if ($retDisplay == '')
349
+		{
350
+			return 'All plugins loaded OK';
351
+		}
352
+		else
353
+		{
354
+			return $retDisplay;
355
+		}
356
+	}
357 357
     
358
-    /**
359
-     * Returns array of name of loaded plugins
360
-     * @return array
361
-     */
362
-    public function pluginList() : array
363
-    {
364
-        return array_keys($this->pluginsList);    
365
-    }
358
+	/**
359
+	 * Returns array of name of loaded plugins
360
+	 * @return array
361
+	 */
362
+	public function pluginList() : array
363
+	{
364
+		return array_keys($this->pluginsList);    
365
+	}
366 366
 
367
-    /**
368
-     * Get plugin details
369
-     * @param string $name name of plugins
370
-     * @return boolean|stdClass result as stdClass or false if plugin not found.
371
-     * @throws \Exception if registering is not possible
372
-     */
373
-    public function pluginDetails(string $name)
374
-    {
375
-        if (!array_key_exists($name, $this->pluginsList))
376
-        {
377
-            return false;
378
-        }
379
-        if ($this->pluginsList[$name]['object'] === null)
380
-        {
381
-            $this->registerPlugin($name); // can throw exception handled by caller
382
-        }
383
-        $retObj = new stdClass();
384
-        $retObj->name           = $name;
385
-        $retObj->catchAllTraps  = $this->pluginsList[$name]['allOID'];
386
-        $retObj->processTraps   = $this->pluginsList[$name]['target'];
387
-        $retObj->description    = $this->pluginsList[$name]['object']->description;
388
-        $functions=array();
389
-        foreach ($this->functionList as $fName => $func)
390
-        {
391
-            if ($func['plugin'] == $name)
392
-            {
393
-                array_push($functions,$fName);
394
-            }
395
-        }
396
-        $retObj->funcArray=$functions;
397
-        return $retObj;
398
-    }
367
+	/**
368
+	 * Get plugin details
369
+	 * @param string $name name of plugins
370
+	 * @return boolean|stdClass result as stdClass or false if plugin not found.
371
+	 * @throws \Exception if registering is not possible
372
+	 */
373
+	public function pluginDetails(string $name)
374
+	{
375
+		if (!array_key_exists($name, $this->pluginsList))
376
+		{
377
+			return false;
378
+		}
379
+		if ($this->pluginsList[$name]['object'] === null)
380
+		{
381
+			$this->registerPlugin($name); // can throw exception handled by caller
382
+		}
383
+		$retObj = new stdClass();
384
+		$retObj->name           = $name;
385
+		$retObj->catchAllTraps  = $this->pluginsList[$name]['allOID'];
386
+		$retObj->processTraps   = $this->pluginsList[$name]['target'];
387
+		$retObj->description    = $this->pluginsList[$name]['object']->description;
388
+		$functions=array();
389
+		foreach ($this->functionList as $fName => $func)
390
+		{
391
+			if ($func['plugin'] == $name)
392
+			{
393
+				array_push($functions,$fName);
394
+			}
395
+		}
396
+		$retObj->funcArray=$functions;
397
+		return $retObj;
398
+	}
399 399
        
400
-    /**
401
-     * Get plugin name from function name
402
-     * @param string $funcName
403
-     * @param string $pluginName
404
-     * @return boolean returns plugin object of false;
405
-     */
406
-    public function getFunction($funcName,&$pluginName)
407
-    {
408
-        if (! isset($this->functionList[$funcName]) )
409
-        {
410
-            return false;
411
-        }
412
-        $pluginName = $this->functionList[$funcName]['plugin'];
413
-        return true;
414
-    }
400
+	/**
401
+	 * Get plugin name from function name
402
+	 * @param string $funcName
403
+	 * @param string $pluginName
404
+	 * @return boolean returns plugin object of false;
405
+	 */
406
+	public function getFunction($funcName,&$pluginName)
407
+	{
408
+		if (! isset($this->functionList[$funcName]) )
409
+		{
410
+			return false;
411
+		}
412
+		$pluginName = $this->functionList[$funcName]['plugin'];
413
+		return true;
414
+	}
415 415
     
416
-    /**
417
-     * Get functions params and description
418
-     * @param string $funcName
419
-     * @return boolean|stdClass false if not found or object (name,params,description)
420
-     * @throws \Exception if registering is not possible
421
-     */
422
-    public function getFunctionDetails($funcName)
423
-    {
424
-        if (! isset($this->functionList[$funcName]) )
425
-        {
426
-            return false;
427
-        }
428
-        $pluginName = $this->functionList[$funcName]['plugin']; // plugin name
429
-        $plugin = $this->pluginsList[$pluginName]['object']; // plugin object
430
-        if ($plugin === null)
431
-        {
432
-            $this->registerPlugin($pluginName); // can throw exception handled by caller
433
-        }
434
-        $retObj = new stdClass();
435
-        $retObj->name           = $funcName;
436
-        $retObj->plugin         = $pluginName;
437
-        $retObj->params         = $plugin->functions[$funcName]['params'];
438
-        $retObj->description    = $plugin->functions[$funcName]['description'];
439
-        return $retObj;
440
-    }
416
+	/**
417
+	 * Get functions params and description
418
+	 * @param string $funcName
419
+	 * @return boolean|stdClass false if not found or object (name,params,description)
420
+	 * @throws \Exception if registering is not possible
421
+	 */
422
+	public function getFunctionDetails($funcName)
423
+	{
424
+		if (! isset($this->functionList[$funcName]) )
425
+		{
426
+			return false;
427
+		}
428
+		$pluginName = $this->functionList[$funcName]['plugin']; // plugin name
429
+		$plugin = $this->pluginsList[$pluginName]['object']; // plugin object
430
+		if ($plugin === null)
431
+		{
432
+			$this->registerPlugin($pluginName); // can throw exception handled by caller
433
+		}
434
+		$retObj = new stdClass();
435
+		$retObj->name           = $funcName;
436
+		$retObj->plugin         = $pluginName;
437
+		$retObj->params         = $plugin->functions[$funcName]['params'];
438
+		$retObj->description    = $plugin->functions[$funcName]['description'];
439
+		return $retObj;
440
+	}
441 441
     
442
-    /**
443
-     * Evaluate function with parameters
444
-     * @param string $funcName
445
-     * @param mixed $params
446
-     * @throws Exception
447
-     * @return bool
448
-     */
449
-    public function getFunctionEval(string $funcName,$params) : bool
450
-    {
451
-        if (! isset($this->functionList[$funcName]) )
452
-        {
453
-            throw new Exception($funcName . ' not found.');
454
-        }
455
-        $pluginName = $this->functionList[$funcName]['plugin']; // plugin name
456
-        $plugin = $this->pluginsList[$pluginName]['object']; // plugin object
442
+	/**
443
+	 * Evaluate function with parameters
444
+	 * @param string $funcName
445
+	 * @param mixed $params
446
+	 * @throws Exception
447
+	 * @return bool
448
+	 */
449
+	public function getFunctionEval(string $funcName,$params) : bool
450
+	{
451
+		if (! isset($this->functionList[$funcName]) )
452
+		{
453
+			throw new Exception($funcName . ' not found.');
454
+		}
455
+		$pluginName = $this->functionList[$funcName]['plugin']; // plugin name
456
+		$plugin = $this->pluginsList[$pluginName]['object']; // plugin object
457 457
 
458
-        if ($plugin === null)
459
-        {
460
-            $this->registerPlugin($pluginName); // can throw exception handled by caller
461
-            $plugin = $this->pluginsList[$pluginName]['object'];
462
-        }
458
+		if ($plugin === null)
459
+		{
460
+			$this->registerPlugin($pluginName); // can throw exception handled by caller
461
+			$plugin = $this->pluginsList[$pluginName]['object'];
462
+		}
463 463
         
464
-        $propertyName = $this->functionList[$funcName]['function'];
465
-        $this->logClass->log('Using property '. $propertyName . ' of class : '.$pluginName,DEBUG);
464
+		$propertyName = $this->functionList[$funcName]['function'];
465
+		$this->logClass->log('Using property '. $propertyName . ' of class : '.$pluginName,DEBUG);
466 466
         
467
-        return $plugin->{$propertyName}($params);        
468
-    }
467
+		return $plugin->{$propertyName}($params);        
468
+	}
469 469
     
470
-    public function evaluateFunctionString(string $functionString) : bool
471
-    {
472
-        $matches=array();
473
-        // Cleanup spaces
474
-        //$functionString = $this->trapClass->ruleClass->eval_cleanup($functionString);
475
-        //$this->logClass->log('eval cleanup : '.$functionString,DEBUG);
470
+	public function evaluateFunctionString(string $functionString) : bool
471
+	{
472
+		$matches=array();
473
+		// Cleanup spaces
474
+		//$functionString = $this->trapClass->ruleClass->eval_cleanup($functionString);
475
+		//$this->logClass->log('eval cleanup : '.$functionString,DEBUG);
476 476
         
477
-        // Match function call
478
-        $num=preg_match('/^__([a-zA-Z0-9]+)\((.+)\)$/', $functionString , $matches);
479
-        if ($num !=1)
480
-        {
481
-            throw new \ErrorException('Function syntax error : ' . $functionString );
482
-        }
483
-        $this->logClass->log('Got function : '. $matches[1] . ', params : '.$matches[2],DEBUG);
484
-        $funcName=$matches[1];
477
+		// Match function call
478
+		$num=preg_match('/^__([a-zA-Z0-9]+)\((.+)\)$/', $functionString , $matches);
479
+		if ($num !=1)
480
+		{
481
+			throw new \ErrorException('Function syntax error : ' . $functionString );
482
+		}
483
+		$this->logClass->log('Got function : '. $matches[1] . ', params : '.$matches[2],DEBUG);
484
+		$funcName=$matches[1];
485 485
         
486
-        // Get parameters comma separated
487
-        $funcParams=str_getcsv($matches[2],',','"',"\\");
488
-        $this->logClass->log('Function params : ' . print_r($funcParams,true),DEBUG);
486
+		// Get parameters comma separated
487
+		$funcParams=str_getcsv($matches[2],',','"',"\\");
488
+		$this->logClass->log('Function params : ' . print_r($funcParams,true),DEBUG);
489 489
         
490
-        // return evaluation
491
-        return $this->getFunctionEval($funcName, $funcParams);        
490
+		// return evaluation
491
+		return $this->getFunctionEval($funcName, $funcParams);        
492 492
         
493
-    }
493
+	}
494 494
     
495 495
 }
496 496
 
497 497
 abstract class PluginTemplate
498 498
 {
499 499
     
500
-    /** @var Logging $loggingClass */
501
-    private $loggingClass;
500
+	/** @var Logging $loggingClass */
501
+	private $loggingClass;
502 502
     
503
-    /** @var string $name Name of plugin */
504
-    public $name;
503
+	/** @var string $name Name of plugin */
504
+	public $name;
505 505
     
506
-    /** @var string $description Description of plugin */
507
-    public $description='Default plugin description';
506
+	/** @var string $description Description of plugin */
507
+	public $description='Default plugin description';
508 508
     
509
-    /** @var array $functions Functions of this plugin for rule eval*/
510
-    public $functions=array();
509
+	/** @var array $functions Functions of this plugin for rule eval*/
510
+	public $functions=array();
511 511
     
512
-    /** @var boolean $catchAllTraps Set to true if all traps will be sent to the plugin */
513
-    public $catchAllTraps=false;
512
+	/** @var boolean $catchAllTraps Set to true if all traps will be sent to the plugin */
513
+	public $catchAllTraps=false;
514 514
     
515
-    /** @var boolean $processTraps Set to true if plugins can handle traps */
516
-    public $processTraps=false;
515
+	/** @var boolean $processTraps Set to true if plugins can handle traps */
516
+	public $processTraps=false;
517 517
     
518
-    /**
519
-     * @param \Trapdirector\Logging $loggingClass
520
-     */
521
-    public function setLoggingClass($loggingClass)
522
-    {
523
-        $this->loggingClass = $loggingClass;
524
-    }
518
+	/**
519
+	 * @param \Trapdirector\Logging $loggingClass
520
+	 */
521
+	public function setLoggingClass($loggingClass)
522
+	{
523
+		$this->loggingClass = $loggingClass;
524
+	}
525 525
     
526
-    /**
527
-     * 
528
-     * @param string $message
529
-     * @param int $level DEBUG/INFO/WARN/CRIT
530
-     */
531
-    public function log($message,$level)
532
-    {
533
-        $this->loggingClass->log('[ '.get_class($this).'] '. $message, $level);
534
-    }
526
+	/**
527
+	 * 
528
+	 * @param string $message
529
+	 * @param int $level DEBUG/INFO/WARN/CRIT
530
+	 */
531
+	public function log($message,$level)
532
+	{
533
+		$this->loggingClass->log('[ '.get_class($this).'] '. $message, $level);
534
+	}
535 535
 }
536 536
\ No newline at end of file
Please login to merge, or discard this patch.