Passed
Pull Request — master (#78)
by
unknown
03:51
created
application/controllers/StatusController.php 3 patches
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -21,8 +21,8 @@  discard block
 block discarded – undo
21 21
 		/************  Trapdb ***********/
22 22
 		try
23 23
 		{
24
-		    $dbConn = $this->getUIDatabase()->getDbConn();
25
-		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
24
+			$dbConn = $this->getUIDatabase()->getDbConn();
25
+			if ($dbConn === null) throw new \ErrorException('uncatched db error');
26 26
 			$query = $dbConn->select()->from(
27 27
 				$this->getModuleConfig()->getTrapTableName(),
28 28
 				array('COUNT(*)')
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 		
52 52
 		try
53 53
 		{		
54
-		    $this->view->currentLogDestination=$this->getUIDatabase()->getDBConfigValue('log_destination');
54
+			$this->view->currentLogDestination=$this->getUIDatabase()->getDBConfigValue('log_destination');
55 55
 			$this->view->logDestinations=$this->getModuleConfig()->getLogDestinations();
56 56
 			$this->view->currentLogFile=$this->getUIDatabase()->getDBConfigValue('log_file');
57 57
 			$this->view->logLevels=$this->getModuleConfig()->getlogLevels();
@@ -65,23 +65,23 @@  discard block
 block discarded – undo
65 65
 		/*************** SNMP configuration ****************/
66 66
 		try
67 67
 		{
68
-		    $this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
69
-		    $this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
-		    $this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
68
+			$this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
69
+			$this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
+			$this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
71 71
 		    
72 72
 		}
73 73
 		catch (Exception $e)
74 74
 		{
75
-		    $this->displayExitError('status',$e->getMessage());
75
+			$this->displayExitError('status',$e->getMessage());
76 76
 		}		
77 77
 		
78 78
 	} 
79 79
   
80 80
 	/** Mib management
81
-	*	Post param : action=update_mib_db : update mib database
82
-	*	Post param : ation=check_update : check if mib update is finished
83
-	*	File post : mibfile -> save mib file
84
-	*/
81
+	 *	Post param : action=update_mib_db : update mib database
82
+	 *	Post param : ation=check_update : check if mib update is finished
83
+	 *	File post : mibfile -> save mib file
84
+	 */
85 85
 	public function mibAction()
86 86
 	{
87 87
 		$this->prepareTabs()->activate('mib');
@@ -100,22 +100,22 @@  discard block
 block discarded – undo
100 100
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
101 101
 					if (preg_match('/OK/',$return))
102 102
 					{
103
-					    $this->_helper->json(array('status'=>'OK'));
103
+						$this->_helper->json(array('status'=>'OK'));
104 104
 					}
105 105
 					// Error
106 106
 					$this->_helper->json(array('status'=>$return));
107 107
 				}
108 108
 				if ($action == 'check_update')
109 109
 				{
110
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
111
-				    if ($file == false)
112
-				    {   // process is dead
113
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
114
-				        return;
115
-				    }
116
-				    $pid=fgets($file);
117
-				    $output=array();
118
-				    $retVal=0;
110
+					$file=@fopen('/tmp/trapdirector_update.pid','r');
111
+					if ($file == false)
112
+					{   // process is dead
113
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
114
+						return;
115
+					}
116
+					$pid=fgets($file);
117
+					$output=array();
118
+					$retVal=0;
119 119
 					exec('ps '.$pid,$output,$retVal);
120 120
 					if ($retVal == 0)
121 121
 					{ // process is alive
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 					}
124 124
 					else
125 125
 					{ // process is dead
126
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
126
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
127 127
 					}
128 128
 				}
129 129
 				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
@@ -136,27 +136,27 @@  discard block
 block discarded – undo
136 136
 				$destDir=array_shift($DirConf);
137 137
 				if (!is_dir($destDir))
138 138
 				{
139
-				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
139
+					$this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
140 140
 				}
141 141
 				else
142 142
 				{
143
-				    if (!is_writable($destDir))
144
-				    {
145
-				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
146
-				    }
147
-				    else
148
-				    {
149
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150
-				        $sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']);
151
-				        if (move_uploaded_file($sourceTmpNam,$destination)===false)
152
-    				    {
153
-    				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154
-    				    }
155
-    				    else
156
-    				    {
157
-    				        $this->view->uploadStatus="File $name uploaded in $destDir";
158
-    				    }
159
-				    }
143
+					if (!is_writable($destDir))
144
+					{
145
+						$this->view->uploadStatus="ERROR : $destDir directory is not writable";
146
+					}
147
+					else
148
+					{
149
+						$destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150
+						$sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']);
151
+						if (move_uploaded_file($sourceTmpNam,$destination)===false)
152
+						{
153
+							$this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154
+						}
155
+						else
156
+						{
157
+							$this->view->uploadStatus="File $name uploaded in $destDir";
158
+						}
159
+					}
160 160
 				}
161 161
 
162 162
 			}
@@ -172,16 +172,16 @@  discard block
 block discarded – undo
172 172
 			$translate=exec($snmptranslate . ' 1');
173 173
 			if (preg_match('/iso/',$translate))
174 174
 			{
175
-			    $translate=exec($snmptranslate . ' 1.3.6.1.4');
176
-			    if (preg_match('/private/',$translate))
177
-			    {		    
178
-    				$this->view->snmptranslate='works fine';
179
-    				$this->view->snmptranslate_state='ok';
180
-			    }
181
-			    else
182
-			    {
183
-			        $this->view->snmptranslate='works fine but missing basic MIBs';
184
-			    }
175
+				$translate=exec($snmptranslate . ' 1.3.6.1.4');
176
+				if (preg_match('/private/',$translate))
177
+				{		    
178
+					$this->view->snmptranslate='works fine';
179
+					$this->view->snmptranslate_state='ok';
180
+				}
181
+				else
182
+				{
183
+					$this->view->snmptranslate='works fine but missing basic MIBs';
184
+				}
185 185
 			}
186 186
 			else
187 187
 			{
@@ -244,63 +244,63 @@  discard block
 block discarded – undo
244 244
 	/** UI options */
245 245
 	public function uimgtAction()
246 246
 	{
247
-	    $this->prepareTabs()->activate('uimgt');
247
+		$this->prepareTabs()->activate('uimgt');
248 248
 	    
249
-	    $this->view->setError='';
250
-	    $this->view->setOKMsg='';
249
+		$this->view->setError='';
250
+		$this->view->setOKMsg='';
251 251
 	    
252
-	    //max_rows=25&row_update=update
253
-	    if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
254
-	    {
255
-	        $maxRows = $this->getRequest()->getParam('max_rows');
256
-	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257
-	        {
258
-	            $this->view->setError='Max rows must be a number';
259
-	        }
260
-	        else
261
-	        {
262
-	            $this->setitemListDisplay($maxRows);
263
-	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
264
-	        }
265
-	    }
252
+		//max_rows=25&row_update=update
253
+		if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
254
+		{
255
+			$maxRows = $this->getRequest()->getParam('max_rows');
256
+			if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257
+			{
258
+				$this->view->setError='Max rows must be a number';
259
+			}
260
+			else
261
+			{
262
+				$this->setitemListDisplay($maxRows);
263
+				$this->view->setOKMsg='Set max rows to ' . $maxRows;
264
+			}
265
+		}
266 266
 	    
267
-	    if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
268
-	    {
269
-	        $addCat = $this->getRequest()->getParam('add_category');
270
-            $this->addHandlersCategory($addCat);
271
-	    }
267
+		if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
268
+		{
269
+			$addCat = $this->getRequest()->getParam('add_category');
270
+			$this->addHandlersCategory($addCat);
271
+		}
272 272
 	    
273
-	    if ( $this->getRequest()->getPost('type',NULL) !== NULL )
274
-	    {
275
-	        $type = $this->getRequest()->getPost('type',NULL);
276
-	        $index = $this->getRequest()->getPost('index',NULL);
277
-	        $newname = $this->getRequest()->getPost('newname',NULL);
273
+		if ( $this->getRequest()->getPost('type',NULL) !== NULL )
274
+		{
275
+			$type = $this->getRequest()->getPost('type',NULL);
276
+			$index = $this->getRequest()->getPost('index',NULL);
277
+			$newname = $this->getRequest()->getPost('newname',NULL);
278 278
 
279
-	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280
-	            $this->_helper->json(array('status'=>'Bad index'));
279
+			if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280
+				$this->_helper->json(array('status'=>'Bad index'));
281 281
 	        
282
-	        switch ($type)
283
-	        {
284
-	            case 'delete':
285
-	                $this->delHandlersCategory($index);
286
-	                $this->_helper->json(array('status'=>'OK'));
287
-	                return;
288
-	                break;
289
-	            case 'rename':
290
-	                $this->renameHandlersCategory($index, $newname);
291
-	                $this->_helper->json(array('status'=>'OK'));
292
-	                return;
293
-	                break;
294
-	            default:
295
-	                $this->_helper->json(array('status'=>'Unknwon command'));
296
-	                return;
297
-	                break;
298
-	        }
299
-	    }
282
+			switch ($type)
283
+			{
284
+				case 'delete':
285
+					$this->delHandlersCategory($index);
286
+					$this->_helper->json(array('status'=>'OK'));
287
+					return;
288
+					break;
289
+				case 'rename':
290
+					$this->renameHandlersCategory($index, $newname);
291
+					$this->_helper->json(array('status'=>'OK'));
292
+					return;
293
+					break;
294
+				default:
295
+					$this->_helper->json(array('status'=>'Unknwon command'));
296
+					return;
297
+					break;
298
+			}
299
+		}
300 300
 	    
301
-	    $this->view->maxRows = $this->itemListDisplay();
301
+		$this->view->maxRows = $this->itemListDisplay();
302 302
 	    
303
-	    $this->view->categories = $this->getHandlersCategory();
303
+		$this->view->categories = $this->getHandlersCategory();
304 304
 	    
305 305
 	    
306 306
 	    
@@ -349,47 +349,47 @@  discard block
 block discarded – undo
349 349
 	 */
350 350
 	public function pluginsAction()
351 351
 	{
352
-	    $this->prepareTabs()->activate('plugins');
352
+		$this->prepareTabs()->activate('plugins');
353 353
 	    
354
-	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
355
-	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
356
-	    $Trap = new Trap($icingaweb2_etc,4);
354
+		require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
355
+		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
356
+		$Trap = new Trap($icingaweb2_etc,4);
357 357
 	    
358
-	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
358
+		$this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
359 359
 	    
360
-	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
360
+		$enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
361 361
 
362
-	    $pluginList = $Trap->pluginClass->pluginList();
362
+		$pluginList = $Trap->pluginClass->pluginList();
363 363
 	    
364
-	    // Plugin list and fill function name list
365
-	    $functionList=array();
366
-	    $this->view->pluginArray=array();
367
-	    foreach ($pluginList as $plugin)
368
-	    {
369
-	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
370
-	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
371
-	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
372
-	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
373
-	        $pluginDetails->description = htmlentities($pluginDetails->description);
374
-	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
375
-	        array_push($this->view->pluginArray, $pluginDetails);
376
-	        // Get functions for function details
377
-	        foreach ($pluginDetails->funcArray as $function)
378
-	        {
379
-	            array_push($functionList,$function);
380
-	        }
381
-	    }
364
+		// Plugin list and fill function name list
365
+		$functionList=array();
366
+		$this->view->pluginArray=array();
367
+		foreach ($pluginList as $plugin)
368
+		{
369
+			$pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
370
+			$pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
371
+			$pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
372
+			$pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
373
+			$pluginDetails->description = htmlentities($pluginDetails->description);
374
+			$pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
375
+			array_push($this->view->pluginArray, $pluginDetails);
376
+			// Get functions for function details
377
+			foreach ($pluginDetails->funcArray as $function)
378
+			{
379
+				array_push($functionList,$function);
380
+			}
381
+		}
382 382
 	    
383
-	    // Function list with details
384
-	    $this->view->functionList=array();
385
-	    foreach ($functionList as $function)
386
-	    {
387
-	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
388
-	        $functionDetail->params = htmlentities($functionDetail->params);
389
-	        $functionDetail->description = htmlentities($functionDetail->description);
390
-	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
391
-	        array_push($this->view->functionList, $functionDetail);
392
-	    }
383
+		// Function list with details
384
+		$this->view->functionList=array();
385
+		foreach ($functionList as $function)
386
+		{
387
+			$functionDetail = $Trap->pluginClass->getFunctionDetails($function);
388
+			$functionDetail->params = htmlentities($functionDetail->params);
389
+			$functionDetail->description = htmlentities($functionDetail->description);
390
+			$functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
391
+			array_push($this->view->functionList, $functionDetail);
392
+		}
393 393
 
394 394
 	}
395 395
 
@@ -398,47 +398,47 @@  discard block
 block discarded – undo
398 398
 	 */
399 399
 	public function debugAction()
400 400
 	{
401
-	    $this->view->answer='No answer';
402
-	    $this->view->input1 = '';
401
+		$this->view->answer='No answer';
402
+		$this->view->input1 = '';
403 403
 	    
404
-	    $postData=$this->getRequest()->getPost();
405
-	    if (isset($postData['input1']))
406
-	    {
407
-	        $input1 = $postData['input1'];
408
-	        $input2 = $postData['input2'];
409
-	        $input3 = $postData['input3'];
410
-	        $this->view->input1 = $input1;
411
-	        //$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
412
-	        try {
413
-	            $this->view->answer = 'Answer : ';
414
-	            $API = $this->getIdoConn();
415
-	            $DB = $this->getUIDatabase();
404
+		$postData=$this->getRequest()->getPost();
405
+		if (isset($postData['input1']))
406
+		{
407
+			$input1 = $postData['input1'];
408
+			$input2 = $postData['input2'];
409
+			$input3 = $postData['input3'];
410
+			$this->view->input1 = $input1;
411
+			//$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
412
+			try {
413
+				$this->view->answer = 'Answer : ';
414
+				$API = $this->getIdoConn();
415
+				$DB = $this->getUIDatabase();
416 416
 
417
-	            //$hosts = $DB->getServicesByHostGroupid($input1);
418
-	            //$this->view->answer .= 'services : '.print_r($hosts,true);
417
+				//$hosts = $DB->getServicesByHostGroupid($input1);
418
+				//$this->view->answer .= 'services : '.print_r($hosts,true);
419 419
 	            
420
-	            $hosts = $API->getServicesByHostGroupid($input1);
421
-	            $this->view->answer .= 'services : '.print_r($hosts,true);
420
+				$hosts = $API->getServicesByHostGroupid($input1);
421
+				$this->view->answer .= 'services : '.print_r($hosts,true);
422 422
 	            
423 423
 
424 424
 	            
425
-	            return;
426
-	            $hosts = $API->getHostByIP($input1);
427
-	            $this->view->answer .= 'Host : '. print_r($hosts,true);
428
-	            $hosts = $API->getHostGroupByName($input1);
429
-	            $this->view->answer .= 'Group : '.print_r($hosts,true);
430
-	            $hosts = $API->getServicesByHostid($input1);
431
-	            $this->view->answer .= 'service : '.print_r($hosts,true);
425
+				return;
426
+				$hosts = $API->getHostByIP($input1);
427
+				$this->view->answer .= 'Host : '. print_r($hosts,true);
428
+				$hosts = $API->getHostGroupByName($input1);
429
+				$this->view->answer .= 'Group : '.print_r($hosts,true);
430
+				$hosts = $API->getServicesByHostid($input1);
431
+				$this->view->answer .= 'service : '.print_r($hosts,true);
432 432
 	            
433
-	            /* $hosts = $API->getHostsIPByHostGroup($input1);
433
+				/* $hosts = $API->getHostsIPByHostGroup($input1);
434 434
 	            $this->view->answer .= "\n Hostgrp : " . print_r($hosts,true); */
435 435
 	            
436
-	        } catch (Exception $e)
437
-	        {
438
-	            $this->view->answer = "Exception : " . print_r($e);
439
-	        }
436
+			} catch (Exception $e)
437
+			{
438
+				$this->view->answer = "Exception : " . print_r($e);
439
+			}
440 440
 	        
441
-	    }
441
+		}
442 442
 	    
443 443
 	}
444 444
 	
@@ -450,36 +450,36 @@  discard block
 block discarded – undo
450 450
 		)->add('mib', array(
451 451
 			'label' => $this->translate('MIB Management'),
452 452
 			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
453
-	    )->add('uimgt', array(
454
-	        'label' => $this->translate('UI Configuration'),
455
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
456
-        )->add('services', array(
453
+		)->add('uimgt', array(
454
+			'label' => $this->translate('UI Configuration'),
455
+			'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
456
+		)->add('services', array(
457 457
 			'label' => $this->translate('Services management'),
458 458
 			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
459
-	    )->add('plugins', array(
460
-	        'label' => $this->translate('Plugins management'),
461
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
462
-	    );
459
+		)->add('plugins', array(
460
+			'label' => $this->translate('Plugins management'),
461
+			'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
462
+		);
463 463
 	} 
464 464
 }
465 465
 
466 466
 // TODO : see if useless 
467 467
 class UploadForm extends Form
468 468
 { 
469
-    public function __construct($options = null) 
470
-    {
471
-        parent::__construct($options);
472
-        $this->addElements2();
473
-    }
469
+	public function __construct($options = null) 
470
+	{
471
+		parent::__construct($options);
472
+		$this->addElements2();
473
+	}
474 474
 
475
-    public function addElements2()
476
-    {
477
-        // File Input
478
-        $file = new File('mib-file');
479
-        $file->setLabel('Mib upload');
480
-             //->setAttrib('multiple', null);
481
-        $this->addElement($file);
475
+	public function addElements2()
476
+	{
477
+		// File Input
478
+		$file = new File('mib-file');
479
+		$file->setLabel('Mib upload');
480
+			 //->setAttrib('multiple', null);
481
+		$this->addElement($file);
482 482
 		$button = new Submit("upload",array('ignore'=>false));
483 483
 		$this->addElement($button);//->setIgnore(false);
484
-    }
484
+	}
485 485
 }
Please login to merge, or discard this patch.
Spacing   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -21,19 +21,19 @@  discard block
 block discarded – undo
21 21
 		/************  Trapdb ***********/
22 22
 		try
23 23
 		{
24
-		    $dbConn = $this->getUIDatabase()->getDbConn();
24
+		    $dbConn=$this->getUIDatabase()->getDbConn();
25 25
 		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
26
-			$query = $dbConn->select()->from(
26
+			$query=$dbConn->select()->from(
27 27
 				$this->getModuleConfig()->getTrapTableName(),
28 28
 				array('COUNT(*)')
29 29
 			);			
30 30
 			$this->view->trap_count=$dbConn->fetchOne($query);
31
-			$query = $dbConn->select()->from(
31
+			$query=$dbConn->select()->from(
32 32
 				$this->getModuleConfig()->getTrapDataTableName(),
33 33
 				array('COUNT(*)')
34 34
 			);			
35 35
 			$this->view->trap_object_count=$dbConn->fetchOne($query);
36
-			$query = $dbConn->select()->from(
36
+			$query=$dbConn->select()->from(
37 37
 				$this->getModuleConfig()->getTrapRuleName(),
38 38
 				array('COUNT(*)')
39 39
 			);			
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 		}
45 45
 		catch (Exception $e)
46 46
 		{
47
-			$this->displayExitError('status',$e->getMessage());
47
+			$this->displayExitError('status', $e->getMessage());
48 48
 		}
49 49
 		
50 50
 		/*************** Log destination *******************/
@@ -59,20 +59,20 @@  discard block
 block discarded – undo
59 59
 		}
60 60
 		catch (Exception $e)
61 61
 		{
62
-			$this->displayExitError('status',$e->getMessage());
62
+			$this->displayExitError('status', $e->getMessage());
63 63
 		}
64 64
 		
65 65
 		/*************** SNMP configuration ****************/
66 66
 		try
67 67
 		{
68
-		    $this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
68
+		    $this->view->useSnmpTrapAddess=($this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1) ? TRUE : FALSE;
69 69
 		    $this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
-		    $this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
70
+		    $this->view->SnmpTrapAddressOIDDefault=($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid']) ? TRUE : FALSE;
71 71
 		    
72 72
 		}
73 73
 		catch (Exception $e)
74 74
 		{
75
-		    $this->displayExitError('status',$e->getMessage());
75
+		    $this->displayExitError('status', $e->getMessage());
76 76
 		}		
77 77
 		
78 78
 	} 
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 				if ($action == 'update_mib_db')
99 99
 				{ // Do the update in background
100 100
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
101
-					if (preg_match('/OK/',$return))
101
+					if (preg_match('/OK/', $return))
102 102
 					{
103 103
 					    $this->_helper->json(array('status'=>'OK'));
104 104
 					}
@@ -107,32 +107,32 @@  discard block
 block discarded – undo
107 107
 				}
108 108
 				if ($action == 'check_update')
109 109
 				{
110
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
110
+				    $file=@fopen('/tmp/trapdirector_update.pid', 'r');
111 111
 				    if ($file == false)
112 112
 				    {   // process is dead
113
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
113
+				        $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'Cannot open file'));
114 114
 				        return;
115 115
 				    }
116 116
 				    $pid=fgets($file);
117 117
 				    $output=array();
118 118
 				    $retVal=0;
119
-					exec('ps '.$pid,$output,$retVal);
119
+					exec('ps '.$pid, $output, $retVal);
120 120
 					if ($retVal == 0)
121 121
 					{ // process is alive
122 122
 						$this->_helper->json(array('status'=>'Alive and kicking'));
123 123
 					}
124 124
 					else
125 125
 					{ // process is dead
126
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
126
+					    $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'no proc'.$pid));
127 127
 					}
128 128
 				}
129
-				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
129
+				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible'));
130 130
 			}
131 131
 			/** Check for mib file UPLOAD */
132 132
 			if (isset($_FILES['mibfile']))
133 133
 			{
134 134
 				$name=htmlspecialchars($_FILES['mibfile']['name']);
135
-				$DirConf=explode(':',$this->Config()->get('config', 'snmptranslate_dirs'));
135
+				$DirConf=explode(':', $this->Config()->get('config', 'snmptranslate_dirs'));
136 136
 				$destDir=array_shift($DirConf);
137 137
 				if (!is_dir($destDir))
138 138
 				{
@@ -146,9 +146,9 @@  discard block
 block discarded – undo
146 146
 				    }
147 147
 				    else
148 148
 				    {
149
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
149
+				        $destination=$destDir.'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150 150
 				        $sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']);
151
-				        if (move_uploaded_file($sourceTmpNam,$destination)===false)
151
+				        if (move_uploaded_file($sourceTmpNam, $destination) === false)
152 152
     				    {
153 153
     				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154 154
     				    }
@@ -164,16 +164,16 @@  discard block
 block discarded – undo
164 164
 		}
165 165
 		
166 166
 		// snmptranslate tests
167
-		$snmptranslate = $this->Config()->get('config', 'snmptranslate');
167
+		$snmptranslate=$this->Config()->get('config', 'snmptranslate');
168 168
 		$this->view->snmptranslate_bin=$snmptranslate;
169 169
 		$this->view->snmptranslate_state='warn';
170
-		if (is_executable ( $snmptranslate ))
170
+		if (is_executable($snmptranslate))
171 171
 		{
172
-			$translate=exec($snmptranslate . ' 1');
173
-			if (preg_match('/iso/',$translate))
172
+			$translate=exec($snmptranslate.' 1');
173
+			if (preg_match('/iso/', $translate))
174 174
 			{
175
-			    $translate=exec($snmptranslate . ' 1.3.6.1.4');
176
-			    if (preg_match('/private/',$translate))
175
+			    $translate=exec($snmptranslate.' 1.3.6.1.4');
176
+			    if (preg_match('/private/', $translate))
177 177
 			    {		    
178 178
     				$this->view->snmptranslate='works fine';
179 179
     				$this->view->snmptranslate_state='ok';
@@ -196,46 +196,46 @@  discard block
 block discarded – undo
196 196
 		// mib database
197 197
 		
198 198
 		$this->view->mibDbCount=$this->getMIB()->countObjects();
199
-		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null,21);
199
+		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null, 21);
200 200
 		
201 201
 		// mib dirs
202 202
 		$DirConf=$this->Config()->get('config', 'snmptranslate_dirs');
203
-		$dirArray=explode(':',$DirConf);
203
+		$dirArray=explode(':', $DirConf);
204 204
 
205 205
 		// Get base directories from net-snmp-config
206 206
 		$output=$matches=array();
207 207
 		$retVal=0;
208
-		$sysDirs=exec('net-snmp-config --default-mibdirs',$output,$retVal);
209
-		if ($retVal==0)
208
+		$sysDirs=exec('net-snmp-config --default-mibdirs', $output, $retVal);
209
+		if ($retVal == 0)
210 210
 		{
211
-			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
211
+			$dirArray=array_merge($dirArray, explode(':', $sysDirs));
212 212
 		}
213 213
 		else
214 214
 		{
215
-			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
216
-			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
215
+			$translateOut=exec($this->Config()->get('config', 'snmptranslate').' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
216
+			if (preg_match('/MIBDIRS.*\'([^\']+)\'/', $translateOut, $matches))
217 217
 			{
218
-				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
218
+				$dirArray=array_merge($dirArray, explode(':', $matches[1]));
219 219
 			}
220 220
 			else
221 221
 			{
222
-				array_push($dirArray,'Install net-snmp-config to see system directories');
222
+				array_push($dirArray, 'Install net-snmp-config to see system directories');
223 223
 			}
224 224
 		}
225 225
 		
226 226
 		$this->view->dirArray=$dirArray;
227 227
 		
228 228
 		$output=null;
229
-		foreach (explode(':',$DirConf) as $mibdir)
229
+		foreach (explode(':', $DirConf) as $mibdir)
230 230
 		{
231
-			exec('ls '.$mibdir.' | grep -v traplist.txt',$output);
231
+			exec('ls '.$mibdir.' | grep -v traplist.txt', $output);
232 232
 		}
233 233
 		//$i=0;$listFiles='';while (isset($output[$i])) $listFiles.=$output[$i++];
234 234
 		//$this->view->fileList=explode(' ',$listFiles);
235 235
 		$this->view->fileList=$output;
236 236
 		
237 237
 		// Zend form 
238
-		$this->view->form= new UploadForm();
238
+		$this->view->form=new UploadForm();
239 239
 		//$this->view->form= new Form('upload-form');
240 240
 		
241 241
 		
@@ -250,9 +250,9 @@  discard block
 block discarded – undo
250 250
 	    $this->view->setOKMsg='';
251 251
 	    
252 252
 	    //max_rows=25&row_update=update
253
-	    if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
253
+	    if ($this->getRequest()->getParam('max_rows', NULL) !== NULL)
254 254
 	    {
255
-	        $maxRows = $this->getRequest()->getParam('max_rows');
255
+	        $maxRows=$this->getRequest()->getParam('max_rows');
256 256
 	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257 257
 	        {
258 258
 	            $this->view->setError='Max rows must be a number';
@@ -260,21 +260,21 @@  discard block
 block discarded – undo
260 260
 	        else
261 261
 	        {
262 262
 	            $this->setitemListDisplay($maxRows);
263
-	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
263
+	            $this->view->setOKMsg='Set max rows to '.$maxRows;
264 264
 	        }
265 265
 	    }
266 266
 	    
267
-	    if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
267
+	    if ($this->getRequest()->getParam('add_category', NULL) !== NULL)
268 268
 	    {
269
-	        $addCat = $this->getRequest()->getParam('add_category');
269
+	        $addCat=$this->getRequest()->getParam('add_category');
270 270
             $this->addHandlersCategory($addCat);
271 271
 	    }
272 272
 	    
273
-	    if ( $this->getRequest()->getPost('type',NULL) !== NULL )
273
+	    if ($this->getRequest()->getPost('type', NULL) !== NULL)
274 274
 	    {
275
-	        $type = $this->getRequest()->getPost('type',NULL);
276
-	        $index = $this->getRequest()->getPost('index',NULL);
277
-	        $newname = $this->getRequest()->getPost('newname',NULL);
275
+	        $type=$this->getRequest()->getPost('type', NULL);
276
+	        $index=$this->getRequest()->getPost('index', NULL);
277
+	        $newname=$this->getRequest()->getPost('newname', NULL);
278 278
 
279 279
 	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280 280
 	            $this->_helper->json(array('status'=>'Bad index'));
@@ -298,9 +298,9 @@  discard block
 block discarded – undo
298 298
 	        }
299 299
 	    }
300 300
 	    
301
-	    $this->view->maxRows = $this->itemListDisplay();
301
+	    $this->view->maxRows=$this->itemListDisplay();
302 302
 	    
303
-	    $this->view->categories = $this->getHandlersCategory();
303
+	    $this->view->categories=$this->getHandlersCategory();
304 304
 	    
305 305
 	    
306 306
 	    
@@ -324,18 +324,18 @@  discard block
 block discarded – undo
324 324
 		$this->view->templateForm_output='';
325 325
 		if (isset($postData['template_name']) && isset($postData['template_revert_time']))
326 326
 		{
327
-			$template_create = 'icingacli director service create --json \'{ "check_command": "dummy", ';
328
-			$template_create .= '"check_interval": "' .$postData['template_revert_time']. '", "check_timeout": "20", "disabled": false, "enable_active_checks": true, "enable_event_handler": true, "enable_notifications": true, "enable_passive_checks": true, "enable_perfdata": true, "max_check_attempts": "1", ';
329
-			$template_create .= '"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
327
+			$template_create='icingacli director service create --json \'{ "check_command": "dummy", ';
328
+			$template_create.='"check_interval": "'.$postData['template_revert_time'].'", "check_timeout": "20", "disabled": false, "enable_active_checks": true, "enable_event_handler": true, "enable_notifications": true, "enable_passive_checks": true, "enable_perfdata": true, "max_check_attempts": "1", ';
329
+			$template_create.='"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
330 330
 			$output=array();
331 331
 			$ret_code=0;
332
-			exec($template_create,$output,$ret_code);
332
+			exec($template_create, $output, $ret_code);
333 333
 			if ($ret_code != 0)
334 334
 			{
335
-				$this->displayExitError("Status -> Services","Error creating template : ".$output[0].'<br>Command was : '.$template_create);
335
+				$this->displayExitError("Status -> Services", "Error creating template : ".$output[0].'<br>Command was : '.$template_create);
336 336
 			}
337
-			exec('icingacli director config deploy',$output,$ret_code);
338
-			$this->view->templateForm_output='Template '.$postData['template_name']. ' created';
337
+			exec('icingacli director config deploy', $output, $ret_code);
338
+			$this->view->templateForm_output='Template '.$postData['template_name'].' created';
339 339
 		}
340 340
 		
341 341
 		// template creation form
@@ -351,15 +351,15 @@  discard block
 block discarded – undo
351 351
 	{
352 352
 	    $this->prepareTabs()->activate('plugins');
353 353
 	    
354
-	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
354
+	    require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
355 355
 	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
356
-	    $Trap = new Trap($icingaweb2_etc,4);
356
+	    $Trap=new Trap($icingaweb2_etc, 4);
357 357
 	    
358
-	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
358
+	    $this->view->pluginLoaded=htmlentities($Trap->pluginClass->registerAllPlugins(false));
359 359
 	    
360
-	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
360
+	    $enabledPlugins=$Trap->pluginClass->getEnabledPlugins();
361 361
 
362
-	    $pluginList = $Trap->pluginClass->pluginList();
362
+	    $pluginList=$Trap->pluginClass->pluginList();
363 363
 	    
364 364
 	    // Plugin list and fill function name list
365 365
 	    $functionList=array();
@@ -367,16 +367,16 @@  discard block
 block discarded – undo
367 367
 	    foreach ($pluginList as $plugin)
368 368
 	    {
369 369
 	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
370
-	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
371
-	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
372
-	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
373
-	        $pluginDetails->description = htmlentities($pluginDetails->description);
374
-	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
370
+	        $pluginDetails->enabled=(in_array($plugin, $enabledPlugins)) ? true : false;
371
+	        $pluginDetails->catchAllTraps=($pluginDetails->catchAllTraps === true) ? 'Yes' : 'No';
372
+	        $pluginDetails->processTraps=($pluginDetails->processTraps === true) ? 'Yes' : 'No';
373
+	        $pluginDetails->description=htmlentities($pluginDetails->description);
374
+	        $pluginDetails->description=preg_replace('/\n/', '<br>', $pluginDetails->description);
375 375
 	        array_push($this->view->pluginArray, $pluginDetails);
376 376
 	        // Get functions for function details
377 377
 	        foreach ($pluginDetails->funcArray as $function)
378 378
 	        {
379
-	            array_push($functionList,$function);
379
+	            array_push($functionList, $function);
380 380
 	        }
381 381
 	    }
382 382
 	    
@@ -384,10 +384,10 @@  discard block
 block discarded – undo
384 384
 	    $this->view->functionList=array();
385 385
 	    foreach ($functionList as $function)
386 386
 	    {
387
-	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
388
-	        $functionDetail->params = htmlentities($functionDetail->params);
389
-	        $functionDetail->description = htmlentities($functionDetail->description);
390
-	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
387
+	        $functionDetail=$Trap->pluginClass->getFunctionDetails($function);
388
+	        $functionDetail->params=htmlentities($functionDetail->params);
389
+	        $functionDetail->description=htmlentities($functionDetail->description);
390
+	        $functionDetail->description=preg_replace('/\n/', '<br>', $functionDetail->description);
391 391
 	        array_push($this->view->functionList, $functionDetail);
392 392
 	    }
393 393
 
@@ -399,43 +399,43 @@  discard block
 block discarded – undo
399 399
 	public function debugAction()
400 400
 	{
401 401
 	    $this->view->answer='No answer';
402
-	    $this->view->input1 = '';
402
+	    $this->view->input1='';
403 403
 	    
404 404
 	    $postData=$this->getRequest()->getPost();
405 405
 	    if (isset($postData['input1']))
406 406
 	    {
407
-	        $input1 = $postData['input1'];
408
-	        $input2 = $postData['input2'];
409
-	        $input3 = $postData['input3'];
410
-	        $this->view->input1 = $input1;
407
+	        $input1=$postData['input1'];
408
+	        $input2=$postData['input2'];
409
+	        $input3=$postData['input3'];
410
+	        $this->view->input1=$input1;
411 411
 	        //$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
412 412
 	        try {
413
-	            $this->view->answer = 'Answer : ';
414
-	            $API = $this->getIdoConn();
415
-	            $DB = $this->getUIDatabase();
413
+	            $this->view->answer='Answer : ';
414
+	            $API=$this->getIdoConn();
415
+	            $DB=$this->getUIDatabase();
416 416
 
417 417
 	            //$hosts = $DB->getServicesByHostGroupid($input1);
418 418
 	            //$this->view->answer .= 'services : '.print_r($hosts,true);
419 419
 	            
420
-	            $hosts = $API->getServicesByHostGroupid($input1);
421
-	            $this->view->answer .= 'services : '.print_r($hosts,true);
420
+	            $hosts=$API->getServicesByHostGroupid($input1);
421
+	            $this->view->answer.='services : '.print_r($hosts, true);
422 422
 	            
423 423
 
424 424
 	            
425 425
 	            return;
426
-	            $hosts = $API->getHostByIP($input1);
427
-	            $this->view->answer .= 'Host : '. print_r($hosts,true);
428
-	            $hosts = $API->getHostGroupByName($input1);
429
-	            $this->view->answer .= 'Group : '.print_r($hosts,true);
430
-	            $hosts = $API->getServicesByHostid($input1);
431
-	            $this->view->answer .= 'service : '.print_r($hosts,true);
426
+	            $hosts=$API->getHostByIP($input1);
427
+	            $this->view->answer.='Host : '.print_r($hosts, true);
428
+	            $hosts=$API->getHostGroupByName($input1);
429
+	            $this->view->answer.='Group : '.print_r($hosts, true);
430
+	            $hosts=$API->getServicesByHostid($input1);
431
+	            $this->view->answer.='service : '.print_r($hosts, true);
432 432
 	            
433 433
 	            /* $hosts = $API->getHostsIPByHostGroup($input1);
434 434
 	            $this->view->answer .= "\n Hostgrp : " . print_r($hosts,true); */
435 435
 	            
436 436
 	        } catch (Exception $e)
437 437
 	        {
438
-	            $this->view->answer = "Exception : " . print_r($e);
438
+	            $this->view->answer="Exception : ".print_r($e);
439 439
 	        }
440 440
 	        
441 441
 	    }
@@ -446,19 +446,19 @@  discard block
 block discarded – undo
446 446
 	{
447 447
 		return $this->getTabs()->add('status', array(
448 448
 			'label' => $this->translate('Status'),
449
-			'url'   => $this->getModuleConfig()->urlPath() . '/status')
449
+			'url'   => $this->getModuleConfig()->urlPath().'/status')
450 450
 		)->add('mib', array(
451 451
 			'label' => $this->translate('MIB Management'),
452
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
452
+			'url'   => $this->getModuleConfig()->urlPath().'/status/mib')
453 453
 	    )->add('uimgt', array(
454 454
 	        'label' => $this->translate('UI Configuration'),
455
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
455
+	        'url'   => $this->getModuleConfig()->urlPath().'/status/uimgt')
456 456
         )->add('services', array(
457 457
 			'label' => $this->translate('Services management'),
458
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
458
+			'url'   => $this->getModuleConfig()->urlPath().'/status/services')
459 459
 	    )->add('plugins', array(
460 460
 	        'label' => $this->translate('Plugins management'),
461
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
461
+	        'url'   => $this->getModuleConfig()->urlPath().'/status/plugins')
462 462
 	    );
463 463
 	} 
464 464
 }
@@ -466,7 +466,7 @@  discard block
 block discarded – undo
466 466
 // TODO : see if useless 
467 467
 class UploadForm extends Form
468 468
 { 
469
-    public function __construct($options = null) 
469
+    public function __construct($options=null) 
470 470
     {
471 471
         parent::__construct($options);
472 472
         $this->addElements2();
@@ -475,11 +475,11 @@  discard block
 block discarded – undo
475 475
     public function addElements2()
476 476
     {
477 477
         // File Input
478
-        $file = new File('mib-file');
478
+        $file=new File('mib-file');
479 479
         $file->setLabel('Mib upload');
480 480
              //->setAttrib('multiple', null);
481 481
         $this->addElement($file);
482
-		$button = new Submit("upload",array('ignore'=>false));
483
-		$this->addElement($button);//->setIgnore(false);
482
+		$button=new Submit("upload", array('ignore'=>false));
483
+		$this->addElement($button); //->setIgnore(false);
484 484
     }
485 485
 }
Please login to merge, or discard this patch.
Braces   +19 added lines, -29 removed lines patch added patch discarded remove patch
@@ -22,7 +22,9 @@  discard block
 block discarded – undo
22 22
 		try
23 23
 		{
24 24
 		    $dbConn = $this->getUIDatabase()->getDbConn();
25
-		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
25
+		    if ($dbConn === null) {
26
+		    	throw new \ErrorException('uncatched db error');
27
+		    }
26 28
 			$query = $dbConn->select()->from(
27 29
 				$this->getModuleConfig()->getTrapTableName(),
28 30
 				array('COUNT(*)')
@@ -41,8 +43,7 @@  discard block
 block discarded – undo
41 43
  			
42 44
 			$this->view->trap_days_delete=$this->getUIDatabase()->getDBConfigValue('db_remove_days');
43 45
 			
44
-		}
45
-		catch (Exception $e)
46
+		} catch (Exception $e)
46 47
 		{
47 48
 			$this->displayExitError('status',$e->getMessage());
48 49
 		}
@@ -56,8 +57,7 @@  discard block
 block discarded – undo
56 57
 			$this->view->currentLogFile=$this->getUIDatabase()->getDBConfigValue('log_file');
57 58
 			$this->view->logLevels=$this->getModuleConfig()->getlogLevels();
58 59
 			$this->view->currentLogLevel=$this->getUIDatabase()->getDBConfigValue('log_level');
59
-		}
60
-		catch (Exception $e)
60
+		} catch (Exception $e)
61 61
 		{
62 62
 			$this->displayExitError('status',$e->getMessage());
63 63
 		}
@@ -69,8 +69,7 @@  discard block
 block discarded – undo
69 69
 		    $this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70 70
 		    $this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
71 71
 		    
72
-		}
73
-		catch (Exception $e)
72
+		} catch (Exception $e)
74 73
 		{
75 74
 		    $this->displayExitError('status',$e->getMessage());
76 75
 		}		
@@ -120,8 +119,7 @@  discard block
 block discarded – undo
120 119
 					if ($retVal == 0)
121 120
 					{ // process is alive
122 121
 						$this->_helper->json(array('status'=>'Alive and kicking'));
123
-					}
124
-					else
122
+					} else
125 123
 					{ // process is dead
126 124
 					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
127 125
 					}
@@ -137,22 +135,19 @@  discard block
 block discarded – undo
137 135
 				if (!is_dir($destDir))
138 136
 				{
139 137
 				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
140
-				}
141
-				else
138
+				} else
142 139
 				{
143 140
 				    if (!is_writable($destDir))
144 141
 				    {
145 142
 				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
146
-				    }
147
-				    else
143
+				    } else
148 144
 				    {
149 145
 				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150 146
 				        $sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']);
151 147
 				        if (move_uploaded_file($sourceTmpNam,$destination)===false)
152 148
     				    {
153 149
     				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154
-    				    }
155
-    				    else
150
+    				    } else
156 151
     				    {
157 152
     				        $this->view->uploadStatus="File $name uploaded in $destDir";
158 153
     				    }
@@ -177,18 +172,15 @@  discard block
 block discarded – undo
177 172
 			    {		    
178 173
     				$this->view->snmptranslate='works fine';
179 174
     				$this->view->snmptranslate_state='ok';
180
-			    }
181
-			    else
175
+			    } else
182 176
 			    {
183 177
 			        $this->view->snmptranslate='works fine but missing basic MIBs';
184 178
 			    }
185
-			}
186
-			else
179
+			} else
187 180
 			{
188 181
 				$this->view->snmptranslate='Can execute but no OID to name resolution';
189 182
 			}
190
-		}
191
-		else
183
+		} else
192 184
 		{
193 185
 			$this->view->snmptranslate='Cannot execute';
194 186
 		}
@@ -209,15 +201,13 @@  discard block
 block discarded – undo
209 201
 		if ($retVal==0)
210 202
 		{
211 203
 			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
212
-		}
213
-		else
204
+		} else
214 205
 		{
215 206
 			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
216 207
 			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
217 208
 			{
218 209
 				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
219
-			}
220
-			else
210
+			} else
221 211
 			{
222 212
 				array_push($dirArray,'Install net-snmp-config to see system directories');
223 213
 			}
@@ -256,8 +246,7 @@  discard block
 block discarded – undo
256 246
 	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257 247
 	        {
258 248
 	            $this->view->setError='Max rows must be a number';
259
-	        }
260
-	        else
249
+	        } else
261 250
 	        {
262 251
 	            $this->setitemListDisplay($maxRows);
263 252
 	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
@@ -276,8 +265,9 @@  discard block
 block discarded – undo
276 265
 	        $index = $this->getRequest()->getPost('index',NULL);
277 266
 	        $newname = $this->getRequest()->getPost('newname',NULL);
278 267
 
279
-	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280
-	            $this->_helper->json(array('status'=>'Bad index'));
268
+	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1) {
269
+	        	            $this->_helper->json(array('status'=>'Bad index'));
270
+	        }
281 271
 	        
282 272
 	        switch ($type)
283 273
 	        {
Please login to merge, or discard this patch.
application/controllers/HandlerController.php 1 patch
Indentation   +294 added lines, -295 removed lines patch added patch discarded remove patch
@@ -12,13 +12,12 @@  discard block
 block discarded – undo
12 12
 
13 13
 //use Icinga\Web\Form as Form;
14 14
 /** Rules management
15
-
16
-*/
15
+ */
17 16
 class HandlerController extends TrapsController
18 17
 {
19 18
 
20 19
 	/** index : list existing rules 
21
-	*/
20
+	 */
22 21
 	public function indexAction()
23 22
 	{	
24 23
 		$this->checkReadPermission();
@@ -28,14 +27,14 @@  discard block
 block discarded – undo
28 27
 		if ($dbConn === null) throw new \ErrorException('uncatched db error');
29 28
 		
30 29
 		$handlerTable = new HandlerTable(
31
-		      $this->moduleConfig->getTrapRuleName(),
32
-		      $this->moduleConfig->getHandlerListTitles(),
33
-		      $this->moduleConfig->getHandlerListDisplayColumns(),
34
-		      $this->moduleConfig->getHandlerColumns(),
35
-		      $dbConn->getDbAdapter(),
30
+			  $this->moduleConfig->getTrapRuleName(),
31
+			  $this->moduleConfig->getHandlerListTitles(),
32
+			  $this->moduleConfig->getHandlerListDisplayColumns(),
33
+			  $this->moduleConfig->getHandlerColumns(),
34
+			  $dbConn->getDbAdapter(),
36 35
 //		      $dbConn->getConnection(),
37
-		      $this->view,
38
-		      $this->moduleConfig->urlPath());
36
+			  $this->view,
37
+			  $this->moduleConfig->urlPath());
39 38
 		
40 39
 		$handlerTable->setMaxPerPage($this->itemListDisplay());
41 40
 		
@@ -57,7 +56,7 @@  discard block
 block discarded – undo
57 56
 		
58 57
 		// TODO : Obsolete remove after new table validation.
59 58
 		
60
-	    /**
59
+		/**
61 60
 		$this->getHandlerListTable()->setConnection($dbConn);
62 61
 		$this->getHandlerListTable()->setMibloader($this->getMIB());
63 62
 		// Apply pagination limits 
@@ -74,22 +73,22 @@  discard block
 block discarded – undo
74 73
 	 */
75 74
 	public function testruleAction()
76 75
 	{
77
-	    $this->checkReadPermission();
78
-	    $this->getTabs()->add('get',array(
79
-	        'active'	=> true,
80
-	        'label'		=> $this->translate('Test Rule'),
81
-	        'url'		=> Url::fromRequest()
82
-	    ));
76
+		$this->checkReadPermission();
77
+		$this->getTabs()->add('get',array(
78
+			'active'	=> true,
79
+			'label'		=> $this->translate('Test Rule'),
80
+			'url'		=> Url::fromRequest()
81
+		));
83 82
 	    
84 83
 
85
-	    if ($this->params->get('rule') !== null) 
86
-	    {
87
-	        $this->view->rule= $this->params->get('rule');
88
-	    }
89
-	    else
90
-	    {
91
-	        $this->view->rule='';
92
-	    }
84
+		if ($this->params->get('rule') !== null) 
85
+		{
86
+			$this->view->rule= $this->params->get('rule');
87
+		}
88
+		else
89
+		{
90
+			$this->view->rule='';
91
+		}
93 92
 	}
94 93
 	
95 94
 	/**
@@ -97,31 +96,31 @@  discard block
 block discarded – undo
97 96
 	 */
98 97
 	private function add_setup_vars()
99 98
 	{
100
-	    // variables to send to view
101
-	    $this->view->hostlist=array(); // host list to input datalist
102
-	    $this->view->hostname=''; // Host name in input text
103
-	    $this->view->serviceGet=false; // Set to true to get list of service if only one host set
104
-	    $this->view->serviceSet=null; // Select service in services select (must have serviceGet=true).
105
-	    $this->view->mainoid=''; // Trap OID
106
-	    $this->view->mib=''; // Trap mib
107
-	    $this->view->name=''; // Trap name
108
-	    $this->view->trapListForMIB=array(); // Trap list if mib exists for trap
109
-	    $this->view->objectList=array(); // objects sent with trap
110
-	    $this->view->display=''; // Initial display
111
-	    $this->view->rule=''; // rule display
112
-	    $this->view->revertOK=''; // revert OK in seconds
113
-	    $this->view->hostid=-1; // normally set by javascript serviceGet()
114
-	    $this->view->ruleid=-1; // Rule id in DB for update & delete
115
-	    $this->view->setToUpdate=false; // set form as update form
116
-	    $this->view->setRuleMatch=-1; // set action on rule match (default nothing)
117
-	    $this->view->setRuleNoMatch=-1; // set action on rule no match (default nothing)
99
+		// variables to send to view
100
+		$this->view->hostlist=array(); // host list to input datalist
101
+		$this->view->hostname=''; // Host name in input text
102
+		$this->view->serviceGet=false; // Set to true to get list of service if only one host set
103
+		$this->view->serviceSet=null; // Select service in services select (must have serviceGet=true).
104
+		$this->view->mainoid=''; // Trap OID
105
+		$this->view->mib=''; // Trap mib
106
+		$this->view->name=''; // Trap name
107
+		$this->view->trapListForMIB=array(); // Trap list if mib exists for trap
108
+		$this->view->objectList=array(); // objects sent with trap
109
+		$this->view->display=''; // Initial display
110
+		$this->view->rule=''; // rule display
111
+		$this->view->revertOK=''; // revert OK in seconds
112
+		$this->view->hostid=-1; // normally set by javascript serviceGet()
113
+		$this->view->ruleid=-1; // Rule id in DB for update & delete
114
+		$this->view->setToUpdate=false; // set form as update form
115
+		$this->view->setRuleMatch=-1; // set action on rule match (default nothing)
116
+		$this->view->setRuleNoMatch=-1; // set action on rule no match (default nothing)
118 117
 	    
119
-	    $this->view->selectGroup=false; // Select by group if true
120
-	    $this->view->hostgroupid=-1; // host group id
121
-	    $this->view->serviceGroupGet=false; // Get list of service for group (set serviceSet to select one)
118
+		$this->view->selectGroup=false; // Select by group if true
119
+		$this->view->hostgroupid=-1; // host group id
120
+		$this->view->serviceGroupGet=false; // Get list of service for group (set serviceSet to select one)
122 121
 	    
123
-	    $this->view->modifier=null;
124
-	    $this->view->modified=null;
122
+		$this->view->modifier=null;
123
+		$this->view->modified=null;
125 124
 	}
126 125
 	
127 126
 	/**
@@ -130,102 +129,102 @@  discard block
 block discarded – undo
130 129
 	 */
131 130
 	private function add_from_existing($trapid)
132 131
 	{
133
-	    /********** Setup from existing trap ***************/
134
-	    // Get the full trap info
135
-	    $trapDetail=$this->getTrapDetail($trapid);
132
+		/********** Setup from existing trap ***************/
133
+		// Get the full trap info
134
+		$trapDetail=$this->getTrapDetail($trapid);
136 135
 	    
137
-	    $hostfilter=$trapDetail->source_ip;
136
+		$hostfilter=$trapDetail->source_ip;
138 137
 	    
139
-	    // Get host
140
-	    try
141
-	    {
142
-	        $hosts=$this->getIdoConn()->getHostByIP($hostfilter);
143
-	    }
144
-	    catch (Exception $e)
145
-	    {
146
-	        $this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
147
-	    }
138
+		// Get host
139
+		try
140
+		{
141
+			$hosts=$this->getIdoConn()->getHostByIP($hostfilter);
142
+		}
143
+		catch (Exception $e)
144
+		{
145
+			$this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
146
+		}
148 147
 	    
149 148
 	    
150
-	    // if one unique host found -> put id text input
151
-	    if (count($hosts)==1) {
152
-	        $this->view->hostname=$hosts[0]->name;
153
-	        //$hostid=$hosts[0]->id;
154
-	        // Tell JS to get services when page is loaded
155
-	        $this->view->serviceGet=true;
149
+		// if one unique host found -> put id text input
150
+		if (count($hosts)==1) {
151
+			$this->view->hostname=$hosts[0]->name;
152
+			//$hostid=$hosts[0]->id;
153
+			// Tell JS to get services when page is loaded
154
+			$this->view->serviceGet=true;
156 155
 	        
157
-	    }
158
-	    else
159
-	    {
160
-	        foreach($hosts as $key=>$val)
161
-	        {
162
-	            array_push($this->view->hostlist,$hosts[$key]->name);
163
-	        }
164
-	    }
156
+		}
157
+		else
158
+		{
159
+			foreach($hosts as $key=>$val)
160
+			{
161
+				array_push($this->view->hostlist,$hosts[$key]->name);
162
+			}
163
+		}
165 164
 	    
166
-	    // set up trap oid and objects received by the trap
165
+		// set up trap oid and objects received by the trap
167 166
 	    
168
-	    $this->view->mainoid=$trapDetail->trap_oid;
169
-	    if ($trapDetail->trap_name_mib != null)
170
-	    {
171
-	        $this->view->mib=$trapDetail->trap_name_mib;
172
-	        $this->view->name=$trapDetail->trap_name;
173
-	        $this->view->trapListForMIB=$this->getMIB()
174
-	        ->getTrapList($trapDetail->trap_name_mib);
175
-	    }
167
+		$this->view->mainoid=$trapDetail->trap_oid;
168
+		if ($trapDetail->trap_name_mib != null)
169
+		{
170
+			$this->view->mib=$trapDetail->trap_name_mib;
171
+			$this->view->name=$trapDetail->trap_name;
172
+			$this->view->trapListForMIB=$this->getMIB()
173
+			->getTrapList($trapDetail->trap_name_mib);
174
+		}
176 175
 	    
177
-	    // Get all objects that can be in trap from MIB
178
-	    $allObjects=$this->getMIB()->getObjectList($trapDetail->trap_oid);
179
-	    // Get all objects in current Trap
180
-	    $currentTrapObjects=$this->getTrapobjects($trapid);
181
-	    $oid_index=1;
182
-	    foreach ($currentTrapObjects as $key => $val)
183
-	    {
184
-	        $currentObjectType='Unknown';
185
-	        $currentObjectTypeEnum='Unknown';
186
-	        if (isset($allObjects[$val->oid]['type']))
187
-	        {
188
-	            $currentObjectType=$allObjects[$val->oid]['type'];
189
-	            $currentObjectTypeEnum=$allObjects[$val->oid]['type_enum'];
190
-	        }
191
-	        $currentObject=array(
192
-	            $oid_index,
193
-	            $val->oid,
194
-	            $val->oid_name_mib,
195
-	            $val->oid_name,
196
-	            $val->value,
197
-	            $currentObjectType,
198
-	            $currentObjectTypeEnum
199
-	        );
200
-	        $oid_index++;
201
-	        array_push($this->view->objectList,$currentObject);
202
-	        // set currrent object to null in allObjects
203
-	        if (isset($allObjects[$val->oid]))
204
-	        {
205
-	            $allObjects[$val->oid]=null;
206
-	        }
207
-	    }
208
-	    if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
209
-	    {
210
-	        foreach ($allObjects as $key => $val)
211
-	        {
212
-	            if ($val==null) { continue; }
213
-	            array_push($this->view->objectList, array(
214
-	                $oid_index,
215
-	                $key,
216
-	                $allObjects[$key]['mib'],
217
-	                $allObjects[$key]['name'],
218
-	                '',
219
-	                $allObjects[$key]['type'],
220
-	                $allObjects[$key]['type_enum']
221
-	            ));
222
-	            $oid_index++;
223
-	        }
224
-	    }
176
+		// Get all objects that can be in trap from MIB
177
+		$allObjects=$this->getMIB()->getObjectList($trapDetail->trap_oid);
178
+		// Get all objects in current Trap
179
+		$currentTrapObjects=$this->getTrapobjects($trapid);
180
+		$oid_index=1;
181
+		foreach ($currentTrapObjects as $key => $val)
182
+		{
183
+			$currentObjectType='Unknown';
184
+			$currentObjectTypeEnum='Unknown';
185
+			if (isset($allObjects[$val->oid]['type']))
186
+			{
187
+				$currentObjectType=$allObjects[$val->oid]['type'];
188
+				$currentObjectTypeEnum=$allObjects[$val->oid]['type_enum'];
189
+			}
190
+			$currentObject=array(
191
+				$oid_index,
192
+				$val->oid,
193
+				$val->oid_name_mib,
194
+				$val->oid_name,
195
+				$val->value,
196
+				$currentObjectType,
197
+				$currentObjectTypeEnum
198
+			);
199
+			$oid_index++;
200
+			array_push($this->view->objectList,$currentObject);
201
+			// set currrent object to null in allObjects
202
+			if (isset($allObjects[$val->oid]))
203
+			{
204
+				$allObjects[$val->oid]=null;
205
+			}
206
+		}
207
+		if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
208
+		{
209
+			foreach ($allObjects as $key => $val)
210
+			{
211
+				if ($val==null) { continue; }
212
+				array_push($this->view->objectList, array(
213
+					$oid_index,
214
+					$key,
215
+					$allObjects[$key]['mib'],
216
+					$allObjects[$key]['name'],
217
+					'',
218
+					$allObjects[$key]['type'],
219
+					$allObjects[$key]['type_enum']
220
+				));
221
+				$oid_index++;
222
+			}
223
+		}
225 224
 	    
226
-	    // Add a simple display
227
-	    $this->view->display='Trap '.$trapDetail->trap_name.' received';
228
-	    $this->view->create_basic_rule=true;
225
+		// Add a simple display
226
+		$this->view->display='Trap '.$trapDetail->trap_name.' received';
227
+		$this->view->create_basic_rule=true;
229 228
 	}
230 229
 
231 230
 	/**
@@ -234,29 +233,29 @@  discard block
 block discarded – undo
234 233
 	 */
235 234
 	private function add_check_host_exists($ruleDetail)
236 235
 	{
237
-	    // Check if hostname still exists
238
-	    $host_get=$this->getIdoConn()->getHostByName($this->view->hostname);
236
+		// Check if hostname still exists
237
+		$host_get=$this->getIdoConn()->getHostByName($this->view->hostname);
239 238
 	    
240
-	    if (count($host_get)==0)
241
-	    {
242
-	        $this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
243
-	        $this->view->serviceGet=false;
244
-	    }
245
-	    else
246
-	    {
247
-	        // Tell JS to get services when page is loaded
248
-	        $this->view->serviceGet=true;
249
-	        // get service id for form to set :
250
-	        $serviceID=$this->getIdoConn()->getServiceIDByName($this->view->hostname,$ruleDetail->service_name);
251
-	        if (count($serviceID) ==0)
252
-	        {
253
-	            $this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
254
-	        }
255
-	        else
256
-	        {
257
-	            $this->view->serviceSet=$serviceID[0]->id;
258
-	        }
259
-	    }
239
+		if (count($host_get)==0)
240
+		{
241
+			$this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
242
+			$this->view->serviceGet=false;
243
+		}
244
+		else
245
+		{
246
+			// Tell JS to get services when page is loaded
247
+			$this->view->serviceGet=true;
248
+			// get service id for form to set :
249
+			$serviceID=$this->getIdoConn()->getServiceIDByName($this->view->hostname,$ruleDetail->service_name);
250
+			if (count($serviceID) ==0)
251
+			{
252
+				$this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
253
+			}
254
+			else
255
+			{
256
+				$this->view->serviceSet=$serviceID[0]->id;
257
+			}
258
+		}
260 259
 	}
261 260
 
262 261
 	/**
@@ -265,33 +264,33 @@  discard block
 block discarded – undo
265 264
 	 */
266 265
 	private function add_check_hostgroup_exists($ruleDetail)
267 266
 	{
268
-	    // Check if groupe exists
269
-	    $group_get=$this->getIdoConn()->getHostGroupByName($this->view->hostgroupname);
270
-	    if (count($group_get)==0)
271
-	    {
272
-	        $this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
273
-	        $this->view->serviceGroupGet=false;
274
-	    }
275
-	    else
276
-	    {
277
-	        $grpServices=$this->getIdoConn()->getServicesByHostGroupid($group_get[0]->id);
278
-	        $foundGrpService=0;
279
-	        foreach ($grpServices as $grpService)
280
-	        {
281
-	            if ($grpService[0] == $ruleDetail->service_name)
282
-	            {
283
-	                $foundGrpService=1;
284
-	                $this->view->serviceSet=$ruleDetail->service_name;
285
-	            }
286
-	        }
267
+		// Check if groupe exists
268
+		$group_get=$this->getIdoConn()->getHostGroupByName($this->view->hostgroupname);
269
+		if (count($group_get)==0)
270
+		{
271
+			$this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
272
+			$this->view->serviceGroupGet=false;
273
+		}
274
+		else
275
+		{
276
+			$grpServices=$this->getIdoConn()->getServicesByHostGroupid($group_get[0]->id);
277
+			$foundGrpService=0;
278
+			foreach ($grpServices as $grpService)
279
+			{
280
+				if ($grpService[0] == $ruleDetail->service_name)
281
+				{
282
+					$foundGrpService=1;
283
+					$this->view->serviceSet=$ruleDetail->service_name;
284
+				}
285
+			}
287 286
 	        
288
-	        // Tell JS to get services when page is loaded
289
-	        $this->view->serviceGroupGet=true;
290
-	        if ($foundGrpService==0)
291
-	        {
292
-	            $this->view->warning_message.=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
293
-	        }
294
-	    }
287
+			// Tell JS to get services when page is loaded
288
+			$this->view->serviceGroupGet=true;
289
+			if ($foundGrpService==0)
290
+			{
291
+				$this->view->warning_message.=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
292
+			}
293
+		}
295 294
 	}
296 295
 	
297 296
 	/**
@@ -303,52 +302,52 @@  discard block
 block discarded – undo
303 302
 	 */
304 303
 	private function add_create_trap_object_list(&$display, &$rule)
305 304
 	{
306
-	    $curObjectList=array();
307
-	    $index=1;
308
-	    // check in display & rule for : OID(<oid>)
309
-	    $matches=array();
310
-	    while ( preg_match('/_OID\(([\.0-9\*]+)\)/',$display,$matches) ||
311
-	        preg_match('/_OID\(([\.0-9\*]+)\)/',$rule,$matches))
312
-	    {
313
-	        $curOid=$matches[1];
305
+		$curObjectList=array();
306
+		$index=1;
307
+		// check in display & rule for : OID(<oid>)
308
+		$matches=array();
309
+		while ( preg_match('/_OID\(([\.0-9\*]+)\)/',$display,$matches) ||
310
+			preg_match('/_OID\(([\.0-9\*]+)\)/',$rule,$matches))
311
+		{
312
+			$curOid=$matches[1];
314 313
 	        
315
-	        if ( (preg_match('/\*/',$curOid) == 0 ) 
316
-	            && ($object=$this->getMIB()->translateOID($curOid)) != null)
317
-	        {
318
-	            array_push($curObjectList, array(
319
-	                $index,
320
-	                $curOid,
321
-	                $object['mib'],
322
-	                $object['name'],
323
-	                '',
324
-	                $object['type'],
325
-	                $object['type_enum']
326
-	            ));
327
-	        }
328
-	        else
329
-	        {
330
-	            array_push($curObjectList, array(
331
-	                $index,
332
-	                $curOid,
333
-	                'not found',
334
-	                'not found',
335
-	                '',
336
-	                'not found',
337
-	                'not found'
338
-	            ));
339
-	        }
340
-	        $curOid = preg_replace('/\*/','\*',$curOid);
341
-	        $display=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$display);
342
-	        $rule=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$rule);
343
-	        $index++;
344
-	    }
345
-	    return $curObjectList;
314
+			if ( (preg_match('/\*/',$curOid) == 0 ) 
315
+				&& ($object=$this->getMIB()->translateOID($curOid)) != null)
316
+			{
317
+				array_push($curObjectList, array(
318
+					$index,
319
+					$curOid,
320
+					$object['mib'],
321
+					$object['name'],
322
+					'',
323
+					$object['type'],
324
+					$object['type_enum']
325
+				));
326
+			}
327
+			else
328
+			{
329
+				array_push($curObjectList, array(
330
+					$index,
331
+					$curOid,
332
+					'not found',
333
+					'not found',
334
+					'',
335
+					'not found',
336
+					'not found'
337
+				));
338
+			}
339
+			$curOid = preg_replace('/\*/','\*',$curOid);
340
+			$display=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$display);
341
+			$rule=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$rule);
342
+			$index++;
343
+		}
344
+		return $curObjectList;
346 345
 	}
347 346
 	
348 347
 	/** Add a handler  
349
-	*	Get params fromid : setup from existing trap (id of trap table)
350
-	*	Get param ruleid : edit from existing handler (id of rule table)
351
-	*/
348
+	 *	Get params fromid : setup from existing trap (id of trap table)
349
+	 *	Get param ruleid : edit from existing handler (id of rule table)
350
+	 */
352 351
 	public function addAction()
353 352
 	{
354 353
 		$this->checkConfigPermission();
@@ -371,8 +370,8 @@  discard block
 block discarded – undo
371 370
 		//$this->view->trapvalues=false; // Set to true to display 'value' colum in objects
372 371
 		
373 372
 		if (($trapid = $this->params->get('fromid')) !== null) {
374
-		    /********** Setup from existing trap ***************/
375
-            $this->add_from_existing($trapid);
373
+			/********** Setup from existing trap ***************/
374
+			$this->add_from_existing($trapid);
376 375
 			return;
377 376
 		}
378 377
 		
@@ -400,14 +399,14 @@  discard block
 block discarded – undo
400 399
 			$this->view->warning_message='';
401 400
 			if ($this->view->hostname != null)
402 401
 			{
403
-			    $this->view->selectGroup=false;
404
-			    // Check if hostname still exists
405
-			    $this->add_check_host_exists($ruleDetail);
402
+				$this->view->selectGroup=false;
403
+				// Check if hostname still exists
404
+				$this->add_check_host_exists($ruleDetail);
406 405
 			}
407 406
 			else
408 407
 			{
409
-			    $this->view->selectGroup=true;
410
-			    $this->add_check_hostgroup_exists($ruleDetail); //  Check if groupe exists				
408
+				$this->view->selectGroup=true;
409
+				$this->add_check_hostgroup_exists($ruleDetail); //  Check if groupe exists				
411 410
 			}
412 411
 			
413 412
 			$this->view->mainoid=$ruleDetail->trap_oid;
@@ -435,9 +434,9 @@  discard block
 block discarded – undo
435 434
 	}
436 435
 	
437 436
 	/** Validate form and output message to user  
438
-	*	@param in postdata 
439
-	* 	@return string status : OK / <Message>
440
-	**/
437
+	 *	@param in postdata 
438
+	 * 	@return string status : OK / <Message>
439
+	 **/
441 440
 	protected function handlerformAction()
442 441
 	{
443 442
 		$postData=$this->getRequest()->getPost();
@@ -452,8 +451,8 @@  discard block
 block discarded – undo
452 451
 			'host_group_name'=>	array('post' => null,            'val' => null,  'db'=>true),
453 452
 			'serviceid'		=>	array('post' => 'serviceid',                     'db'=>false),
454 453
 			'service_name'	=>	array('post' => 'serviceName',                    'db'=>true),
455
-		    'comment'       =>  array('post' => 'comment',       'val' => '',    'db'=>true),
456
-		    'rule_type'     =>  array('post' => 'category',       'val' => 0,    'db'=>true),
454
+			'comment'       =>  array('post' => 'comment',       'val' => '',    'db'=>true),
455
+			'rule_type'     =>  array('post' => 'category',       'val' => 0,    'db'=>true),
457 456
 			'trap_oid'		=>	array('post' => 'oid',                            'db'=>true),
458 457
 			'revert_ok'		=>	array('post' => 'revertOK',      'val' => 0,      'db'=>true),
459 458
 			'display'		=>	array('post' => 'display',        'val' => '',     'db'=>true),
@@ -462,7 +461,7 @@  discard block
 block discarded – undo
462 461
 			'action_nomatch'=>	array('post' => 'ruleNoMatch',    'val' => -1,    'db'=>true),					
463 462
 			'ip4'			=>	array('post' => null,             'val' => null,  'db'=>true),
464 463
 			'ip6'			=>	array('post' => null,             'val' => null,  'db'=>true),
465
-		    'action_form'	=>	array('post' => 'action_form',    'val' => null, 'db'=>false)
464
+			'action_form'	=>	array('post' => 'action_form',    'val' => null, 'db'=>false)
466 465
 		);
467 466
 		
468 467
 		if (isset($postData[$params['action_form']['post']]) 
@@ -470,7 +469,7 @@  discard block
 block discarded – undo
470 469
 		{
471 470
 			try
472 471
 			{
473
-			    $this->getUIDatabase()->deleteRule($postData[$params['db_rule']['post']]);
472
+				$this->getUIDatabase()->deleteRule($postData[$params['db_rule']['post']]);
474 473
 			}
475 474
 			catch (Exception $e)
476 475
 			{
@@ -480,7 +479,7 @@  discard block
 block discarded – undo
480 479
 			//$this->Module()->
481 480
 			$this->_helper->json(array(
482 481
 				'status'=>'OK',
483
-			    'redirect'=>'trapdirector/handler'
482
+				'redirect'=>'trapdirector/handler'
484 483
 			      
485 484
 			));
486 485
 		}		
@@ -507,8 +506,8 @@  discard block
 block discarded – undo
507 506
 			$isHostGroup=($params['hostgroup']['val'] == 1)?true:false;
508 507
 			if (! $isHostGroup ) 
509 508
 			{  // checks if selection by host 
510
-			    $hostAddr=$this->getIdoConn()->getHostInfoByID($params['hostid']['val']);
511
-			    if ($hostAddr === NULL) throw new \Exception("No object found");
509
+				$hostAddr=$this->getIdoConn()->getHostInfoByID($params['hostid']['val']);
510
+				if ($hostAddr === NULL) throw new \Exception("No object found");
512 511
 				$params['ip4']['val']=$hostAddr->ip4;
513 512
 				$params['ip6']['val']=$hostAddr->ip6;
514 513
 				$checkHostName=$hostAddr->name;
@@ -519,49 +518,49 @@  discard block
 block discarded – undo
519 518
 				}
520 519
 				if ($this->apiMode == TRUE)
521 520
 				{
522
-				    $serviceName=$this->getIdoConn()->getServiceById($params['serviceid']['val']);
523
-				    if (count($serviceName) == 0 )
524
-				    {
525
-				        $this->_helper->json(array('status'=>"Invalid service id : Please re enter service",'sent'=>$params['serviceid']['val'],'found'=>$serviceName[0]->__name));
526
-				        return;
527
-				    }
521
+					$serviceName=$this->getIdoConn()->getServiceById($params['serviceid']['val']);
522
+					if (count($serviceName) == 0 )
523
+					{
524
+						$this->_helper->json(array('status'=>"Invalid service id : Please re enter service",'sent'=>$params['serviceid']['val'],'found'=>$serviceName[0]->__name));
525
+						return;
526
+					}
528 527
 				}
529 528
 				else
530 529
 				{
531
-    				if (!is_numeric($params['serviceid']['val']))
532
-    				{
533
-    				    $this->_helper->json(array('status'=>"Invalid service id ". $params['serviceid']['val']));
534
-    				    return;
535
-    				}
530
+					if (!is_numeric($params['serviceid']['val']))
531
+					{
532
+						$this->_helper->json(array('status'=>"Invalid service id ". $params['serviceid']['val']));
533
+						return;
534
+					}
536 535
     				
537
-    				$serviceName=$this->getUIDatabase()->getObjectNameByid($params['serviceid']['val']);
538
-    				if ($params['service_name']['val'] != $serviceName->name2)
539
-    				{
540
-    					$this->_helper->json(array('status'=>"Invalid service id : Please re enter service"));
541
-    					return;
542
-    				}
536
+					$serviceName=$this->getUIDatabase()->getObjectNameByid($params['serviceid']['val']);
537
+					if ($params['service_name']['val'] != $serviceName->name2)
538
+					{
539
+						$this->_helper->json(array('status'=>"Invalid service id : Please re enter service"));
540
+						return;
541
+					}
543 542
 				}
544 543
 			}
545 544
 			else
546 545
 			{
547
-			    if ($this->apiMode == TRUE)
548
-			    {
549
-			        $object=$this->getIdoConn()->getHostGroupById($params['hostid']['val']);
546
+				if ($this->apiMode == TRUE)
547
+				{
548
+					$object=$this->getIdoConn()->getHostGroupById($params['hostid']['val']);
550 549
 				if (empty($object) || $params['host_name']['val'] != $object->__name)
551
-			        {
552
-			            $this->_helper->json(array('status'=>"Invalid object group id : Please re enter service"));
553
-			            return;
554
-			        }
555
-			    }
556
-			    else 
557
-			    {
558
-    			    $object=$this->getUIDatabase()->getObjectNameByid($params['hostid']['val']);
559
-    				if ($params['host_name']['val'] != $object->name1)
560
-    				{
561
-    					$this->_helper->json(array('status'=>"Invalid object group id : Please re enter service"));
562
-    					return;					
563
-    				}
564
-			    }
550
+					{
551
+						$this->_helper->json(array('status'=>"Invalid object group id : Please re enter service"));
552
+						return;
553
+					}
554
+				}
555
+				else 
556
+				{
557
+					$object=$this->getUIDatabase()->getObjectNameByid($params['hostid']['val']);
558
+					if ($params['host_name']['val'] != $object->name1)
559
+					{
560
+						$this->_helper->json(array('status'=>"Invalid object group id : Please re enter service"));
561
+						return;					
562
+					}
563
+				}
565 564
 				// Put param in correct column (group_name)
566 565
 				$params['host_group_name']['val'] = $params['host_name']['val'];
567 566
 				$params['host_name']['val']=null;
@@ -578,17 +577,17 @@  discard block
 block discarded – undo
578 577
 			
579 578
 			if ($params['db_rule']['val'] == -1 || $params['action_form']['val'] == 'clone') 
580 579
 			{  // If no rule number or action is clone, add the handler
581
-			    $ruleID=$this->getUIDatabase()->addHandlerRule($dbparams);
580
+				$ruleID=$this->getUIDatabase()->addHandlerRule($dbparams);
582 581
 			}
583 582
 			else
584 583
 			{
585
-			    $this->getUIDatabase()->updateHandlerRule($dbparams,$params['db_rule']['val']);
584
+				$this->getUIDatabase()->updateHandlerRule($dbparams,$params['db_rule']['val']);
586 585
 				$ruleID=$params['db_rule']['val'];
587 586
 			}
588 587
 		}
589 588
 		catch (Exception $e)
590 589
 		{
591
-		    $this->_helper->json(array('status'=>$e->getMessage(),'location'=>'Add/update Rule','line'=>$e->getLine(),'file'=>$e->getFile()));
590
+			$this->_helper->json(array('status'=>$e->getMessage(),'location'=>'Add/update Rule','line'=>$e->getLine(),'file'=>$e->getFile()));
592 591
 			return;
593 592
 		}
594 593
 		$this->_helper->json(array('status'=>'OK', 'id' => $ruleID));
@@ -596,9 +595,9 @@  discard block
 block discarded – undo
596 595
 	}
597 596
 
598 597
 	/** Get trap detail by trapid. 
599
-	*	@param integer $trapid : id of trap in received table
600
-	*	@return array (objects)
601
-	*/
598
+	 *	@param integer $trapid : id of trap in received table
599
+	 *	@return array (objects)
600
+	 */
602 601
 	protected function getTrapDetail($trapid) 
603 602
 	{
604 603
 		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
@@ -614,14 +613,14 @@  discard block
 block discarded – undo
614 613
 		}
615 614
 		try
616 615
 		{		
617
-		    $query = $dbConn->select()
616
+			$query = $dbConn->select()
618 617
 				->from($this->getModuleConfig()->getTrapTableName(),$elmts)
619 618
 				->where('id=?',$trapid);
620 619
 				$trapDetail=$dbConn->fetchRow($query);
621 620
 			if ( $trapDetail == null ) 
622 621
 			{
623
-			    $trapDetail = 'NULL';
624
-			    throw new Exception('No traps was found with id = '.$trapid);
622
+				$trapDetail = 'NULL';
623
+				throw new Exception('No traps was found with id = '.$trapid);
625 624
 			}
626 625
 		}
627 626
 		catch (Exception $e)
@@ -635,9 +634,9 @@  discard block
 block discarded – undo
635 634
 	}
636 635
 
637 636
 	/** Get trap objects
638
-	*	@param integer $trapid : trap id
639
-	* 	@return array : full column in db of trap id
640
-	*/
637
+	 *	@param integer $trapid : trap id
638
+	 * 	@return array : full column in db of trap id
639
+	 */
641 640
 	protected function getTrapobjects($trapid)
642 641
 	{	
643 642
 		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
@@ -653,7 +652,7 @@  discard block
 block discarded – undo
653 652
 		}
654 653
 		try
655 654
 		{		
656
-		    $query = $dbConn->select()
655
+			$query = $dbConn->select()
657 656
 				->from($this->moduleConfig->getTrapDataTableName(),$data_elmts)
658 657
 				->where('trap_id=?',$trapid);
659 658
 				$trapDetail=$dbConn->fetchAll($query);
@@ -669,10 +668,10 @@  discard block
 block discarded – undo
669 668
 	}
670 669
 
671 670
 	/** Get rule detail by ruleid.
672
-	*	@param integer $ruleid int id of rule in rule table
673
-	*	@return object|array : column objects in db 
674
-	*
675
-	*/
671
+	 *	@param integer $ruleid int id of rule in rule table
672
+	 *	@return object|array : column objects in db 
673
+	 *
674
+	 */
676 675
 	protected function getRuleDetail($ruleid) 
677 676
 	{
678 677
 		if (!preg_match('/^[0-9]+$/',$ruleid)) { throw new Exception('Invalid id');  }
@@ -683,7 +682,7 @@  discard block
 block discarded – undo
683 682
 		// ***************  Get main data
684 683
 		try
685 684
 		{		
686
-		    $query = $dbConn->select()
685
+			$query = $dbConn->select()
687 686
 				->from($this->getModuleConfig()->getTrapRuleName(),$queryArray)
688 687
 				->where('id=?',$ruleid);
689 688
 			$ruleDetail=$dbConn->fetchRow($query);
@@ -700,7 +699,7 @@  discard block
 block discarded – undo
700 699
 	}
701 700
 
702 701
 	/** Setup tabs for rules 
703
-	*/
702
+	 */
704 703
 	protected function prepareTabs()
705 704
 	{
706 705
 		return $this->getTabs()->add('status', array(
Please login to merge, or discard this patch.
application/controllers/SettingsController.php 2 patches
Indentation   +234 added lines, -234 removed lines patch added patch discarded remove patch
@@ -25,16 +25,16 @@  discard block
 block discarded – undo
25 25
    */
26 26
   private function get_param()
27 27
   {
28
-      $dberrorMsg=$this->params->get('dberror');
29
-      if ($dberrorMsg != '')
30
-      {
31
-          $this->view->errorDetected=$dberrorMsg;
32
-      }
33
-      $dberrorMsg=$this->params->get('idodberror');
34
-      if ($dberrorMsg != '')
35
-      {
36
-          $this->view->errorDetected=$dberrorMsg;
37
-      }
28
+	  $dberrorMsg=$this->params->get('dberror');
29
+	  if ($dberrorMsg != '')
30
+	  {
31
+		  $this->view->errorDetected=$dberrorMsg;
32
+	  }
33
+	  $dberrorMsg=$this->params->get('idodberror');
34
+	  if ($dberrorMsg != '')
35
+	  {
36
+		  $this->view->errorDetected=$dberrorMsg;
37
+	  }
38 38
   }
39 39
   
40 40
   /**
@@ -43,22 +43,22 @@  discard block
 block discarded – undo
43 43
    */
44 44
   private function check_empty_config()
45 45
   {
46
-      $this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
47
-      if ($this->Config()->isEmpty() == true)
48
-      {
49
-          $this->Config()->setSection('config'); // Set base config section.
50
-          try
51
-          {
52
-              $this->Config()->saveIni();
53
-              $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54
-              //$emptyConfig=1;
55
-          }
56
-          catch (Exception $e)
57
-          {
58
-              $this->view->configErrorDetected=$e->getMessage();
59
-          }
46
+	  $this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
47
+	  if ($this->Config()->isEmpty() == true)
48
+	  {
49
+		  $this->Config()->setSection('config'); // Set base config section.
50
+		  try
51
+		  {
52
+			  $this->Config()->saveIni();
53
+			  $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54
+			  //$emptyConfig=1;
55
+		  }
56
+		  catch (Exception $e)
57
+		  {
58
+			  $this->view->configErrorDetected=$e->getMessage();
59
+		  }
60 60
           
61
-      }
61
+	  }
62 62
   }
63 63
   
64 64
   /**
@@ -71,57 +71,57 @@  discard block
 block discarded – undo
71 71
    */
72 72
   private function check_db()
73 73
   {
74
-      $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
-          0	=>	array('Database configuration OK','',''),
76
-          1	=>	array('Database set in config.ini','No database in config.ini',''),
77
-          2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
78
-              Url::fromPath('config/resource')),
79
-          3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
80
-              Url::fromPath('trapdirector/settings/createschema')),
81
-          4	=>	array('Schema is set','Schema is not set for ',
82
-              Url::fromPath('trapdirector/settings/createschema')),
83
-          5	=>	array('Schema is up to date','Schema is outdated :',
84
-              Url::fromPath('trapdirector/settings/updateschema')),
85
-      );
74
+	  $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
+		  0	=>	array('Database configuration OK','',''),
76
+		  1	=>	array('Database set in config.ini','No database in config.ini',''),
77
+		  2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
78
+			  Url::fromPath('config/resource')),
79
+		  3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
80
+			  Url::fromPath('trapdirector/settings/createschema')),
81
+		  4	=>	array('Schema is set','Schema is not set for ',
82
+			  Url::fromPath('trapdirector/settings/createschema')),
83
+		  5	=>	array('Schema is up to date','Schema is outdated :',
84
+			  Url::fromPath('trapdirector/settings/updateschema')),
85
+	  );
86 86
       
87
-      try {
88
-          $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
-          $dberror=array(0,'');
90
-      } catch (DBException $e) {
91
-          $dberror = $e->getArray();
92
-      }
87
+	  try {
88
+		  $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
+		  $dberror=array(0,'');
90
+	  } catch (DBException $e) {
91
+		  $dberror = $e->getArray();
92
+	  }
93 93
       
94
-      $this->view->db_error=$dberror[0];
95
-      switch ($dberror[0])
96
-      {
97
-          case 2:
98
-          case 4:
99
-              $db_message[$dberror[0]][1] .= $dberror[1];
100
-              break;
101
-          case 3:
102
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
103
-              break;
104
-          case 5:
105
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
106
-              break;
107
-          case 0:
108
-          case 1:
109
-              break;
110
-          default:
111
-              new ProgrammingError('Out of bond result from database test');
112
-      }
113
-      $this->view->message=$db_message;
94
+	  $this->view->db_error=$dberror[0];
95
+	  switch ($dberror[0])
96
+	  {
97
+		  case 2:
98
+		  case 4:
99
+			  $db_message[$dberror[0]][1] .= $dberror[1];
100
+			  break;
101
+		  case 3:
102
+			  $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
103
+			  break;
104
+		  case 5:
105
+			  $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
106
+			  break;
107
+		  case 0:
108
+		  case 1:
109
+			  break;
110
+		  default:
111
+			  new ProgrammingError('Out of bond result from database test');
112
+	  }
113
+	  $this->view->message=$db_message;
114 114
       
115
-      try {
116
-          $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
-          $dberror=array(0,'');
118
-      } catch (DBException $e) {
119
-          $dberror = $e->getArray();
120
-      }
115
+	  try {
116
+		  $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
+		  $dberror=array(0,'');
118
+	  } catch (DBException $e) {
119
+		  $dberror = $e->getArray();
120
+	  }
121 121
       
122
-      $this->view->ido_db_error=$dberror[0];
123
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
124
-      $this->view->ido_message .='<br />=&gt; Default to API use. Make sure it is configured and check is returning OK!';
122
+	  $this->view->ido_db_error=$dberror[0];
123
+	  $this->view->ido_message='IDO Database : ' . $dberror[1];
124
+	  $this->view->ido_message .='<br />=&gt; Default to API use. Make sure it is configured and check is returning OK!';
125 125
   }
126 126
   
127 127
   /**
@@ -131,23 +131,23 @@  discard block
 block discarded – undo
131 131
    */
132 132
   private function check_api()
133 133
   {
134
-      if ($this->Config()->get('config', 'icingaAPI_host') != '')
135
-      {
136
-          $apitest=new Icinga2API($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
137
-          $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
138
-          try {
139
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
140
-              //$this->view->apimessageError=false;
141
-          } catch (RuntimeException $e) {
142
-              $this->view->apimessage='API config : ' . $e->getMessage();
143
-              $this->view->apimessageError=true;
144
-          }
145
-      }
146
-      else
147
-      {
148
-          $this->view->apimessage='API parameters not configured';
149
-          $this->view->apimessageError=true;
150
-      }
134
+	  if ($this->Config()->get('config', 'icingaAPI_host') != '')
135
+	  {
136
+		  $apitest=new Icinga2API($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
137
+		  $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
138
+		  try {
139
+			  list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
140
+			  //$this->view->apimessageError=false;
141
+		  } catch (RuntimeException $e) {
142
+			  $this->view->apimessage='API config : ' . $e->getMessage();
143
+			  $this->view->apimessageError=true;
144
+		  }
145
+	  }
146
+	  else
147
+	  {
148
+		  $this->view->apimessage='API parameters not configured';
149
+		  $this->view->apimessageError=true;
150
+	  }
151 151
   }
152 152
 
153 153
   /**
@@ -158,21 +158,21 @@  discard block
 block discarded – undo
158 158
    */
159 159
   private function check_icingaweb_path()
160 160
   {
161
-      $this->view->icingaEtcWarn=0;
162
-      $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
163
-      if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
164
-      {
165
-          $output=array();
161
+	  $this->view->icingaEtcWarn=0;
162
+	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
163
+	  if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
164
+	  {
165
+		  $output=array();
166 166
           
167
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
167
+		  exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
168 168
           
169 169
           
170
-          if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
171
-          {
172
-              $this->view->icingaEtcWarn=1;
173
-              $this->view->icingaweb2_etc=$icingaweb2_etc;
174
-          }
175
-      }
170
+		  if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
171
+		  {
172
+			  $this->view->icingaEtcWarn=1;
173
+			  $this->view->icingaweb2_etc=$icingaweb2_etc;
174
+		  }
175
+	  }
176 176
       
177 177
   }
178 178
   
@@ -183,15 +183,15 @@  discard block
 block discarded – undo
183 183
    */
184 184
   private function get_db_list($allowed)
185 185
   {
186
-      $resources = array();
187
-      foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
188
-      {
189
-          if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
190
-          {
191
-              $resources[$name] = $name;
192
-          }
193
-      }
194
-      return $resources;
186
+	  $resources = array();
187
+	  foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
188
+	  {
189
+		  if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
190
+		  {
191
+			  $resources[$name] = $name;
192
+		  }
193
+	  }
194
+	  return $resources;
195 195
   }
196 196
   
197 197
   /**
@@ -200,23 +200,23 @@  discard block
 block discarded – undo
200 200
    */
201 201
   private function get_php_binary()
202 202
   {
203
-      $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
203
+	  $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
204 204
 
205
-      foreach ($phpBinary as $phpBin )
206
-      {
207
-          $output=array();
208
-          $retCode=255;
209
-          $input="154865134987aaaa";
210
-          exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
205
+	  foreach ($phpBinary as $phpBin )
206
+	  {
207
+		  $output=array();
208
+		  $retCode=255;
209
+		  $input="154865134987aaaa";
210
+		  exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
211 211
           
212
-          if (! isset($output[0])) $output[0]="NO OUT";
212
+		  if (! isset($output[0])) $output[0]="NO OUT";
213 213
           
214
-          if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
215
-          {
216
-              return $phpBin;
217
-          }          
218
-      }
219
-      return NULL;
214
+		  if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
215
+		  {
216
+			  return $phpBin;
217
+		  }          
218
+	  }
219
+	  return NULL;
220 220
   }
221 221
   
222 222
   /**
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
   public function indexAction()
236 236
   {
237 237
       
238
-    // CHeck permissions : display tests in any case, but no configuration.
238
+	// CHeck permissions : display tests in any case, but no configuration.
239 239
 	$this->view->configPermission=$this->checkModuleConfigPermission(1);
240 240
 	// But check read permission
241 241
 	$this->checkReadPermission();
@@ -243,16 +243,16 @@  discard block
 block discarded – undo
243 243
 	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');	
244 244
 	
245 245
 	// Get message : sent on configuration problems detected by controllers
246
-    $this->get_param();
246
+	$this->get_param();
247 247
     
248
-    // Test if configuration exists, if not create for installer script
248
+	// Test if configuration exists, if not create for installer script
249 249
 	$this->check_empty_config();
250 250
 
251 251
 	// Test Database
252
-    $this->check_db();
252
+	$this->check_db();
253 253
 	
254 254
 	// Test API
255
-    $this->check_api();
255
+	$this->check_api();
256 256
 	
257 257
 	//Test snmptrapd alive and options
258 258
 	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 	$phpBinary = $this->get_php_binary();
267 267
 	if ($phpBinary === null)
268 268
 	{
269
-	    $phpBinary = ' PHP BINARY NOT FOUND ';
269
+		$phpBinary = ' PHP BINARY NOT FOUND ';
270 270
 	    
271 271
 	}
272 272
 	
@@ -274,11 +274,11 @@  discard block
 block discarded – undo
274 274
 	$this->view->traps_in_config= $phpBinary . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
275 275
 	
276 276
 	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
277
-	    . ' -c all ' 
278
-	    . ' -d ' . $this->Module()->getBaseDir()
279
-	    . ' -p ' . $phpBinary
280
-	    . ' -a ' . exec('whoami')
281
-	    . ' -w ' . Icinga::app()->getConfigDir();
277
+		. ' -c all ' 
278
+		. ' -d ' . $this->Module()->getBaseDir()
279
+		. ' -p ' . $phpBinary
280
+		. ' -a ' . exec('whoami')
281
+		. ' -w ' . Icinga::app()->getConfigDir();
282 282
 	        
283 283
 	// ******************* configuration form setup*******************
284 284
 	$this->view->form = $form = new TrapsConfigForm();
@@ -312,15 +312,15 @@  discard block
 block discarded – undo
312 312
   public function satelliteAction()
313 313
   {
314 314
       
315
-      // CHeck permissions
316
-      $this->view->configPermission=$this->checkModuleConfigPermission();
315
+	  // CHeck permissions
316
+	  $this->view->configPermission=$this->checkModuleConfigPermission();
317 317
       
318
-      // Setup tabs
319
-      $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
318
+	  // Setup tabs
319
+	  $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
320 320
       
321
-      $this->view->masterHASet = FALSE;
321
+	  $this->view->masterHASet = FALSE;
322 322
       
323
-      $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
323
+	  $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
324 324
   }
325 325
   
326 326
   
@@ -336,8 +336,8 @@  discard block
 block discarded – undo
336 336
 	
337 337
 	try 
338 338
 	{
339
-	    $this->getUIDatabase()->testGetDb(); // Get DB in test mode
340
-	    printf('Schema already exists');
339
+		$this->getUIDatabase()->testGetDb(); // Get DB in test mode
340
+		printf('Schema already exists');
341 341
 	    
342 342
 	} 
343 343
 	catch (DBException $e) 
@@ -348,19 +348,19 @@  discard block
 block discarded – undo
348 348
 		// Get module database name
349 349
 		$dbName=$this->Config()->get('config', 'database');
350 350
 
351
-        $dbResource = ResourceFactory::getResourceConfig($dbName);
352
-        $dbType=$dbResource->get('db');
353
-        switch ($dbType) {
354
-          case 'mysql':
355
-              $dbFileExt='sql';
356
-              break;
357
-          case 'pgsql':
358
-              $dbFileExt='pgsql';
359
-              break;
360
-          default:
361
-              printf("Database configuration error : Unsuported DB");
362
-              return;
363
-        } 
351
+		$dbResource = ResourceFactory::getResourceConfig($dbName);
352
+		$dbType=$dbResource->get('db');
353
+		switch ($dbType) {
354
+		  case 'mysql':
355
+			  $dbFileExt='sql';
356
+			  break;
357
+		  case 'pgsql':
358
+			  $dbFileExt='pgsql';
359
+			  break;
360
+		  default:
361
+			  printf("Database configuration error : Unsuported DB");
362
+			  return;
363
+		} 
364 364
 
365 365
 		printf('<pre>');
366 366
 		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
@@ -384,32 +384,32 @@  discard block
 block discarded – undo
384 384
   public function updateschemaAction()
385 385
   {
386 386
 	  $this->checkModuleConfigPermission();
387
-      $this->getTabs()->add('get',array(
388
-    		'active'	=> true,
389
-    		'label'		=> $this->translate('Update Schema'),
390
-    		'url'		=> Url::fromRequest()
391
-    	));
387
+	  $this->getTabs()->add('get',array(
388
+			'active'	=> true,
389
+			'label'		=> $this->translate('Update Schema'),
390
+			'url'		=> Url::fromRequest()
391
+		));
392 392
 	  // check if needed
393 393
 	  $dberror=array();
394
-      try
395
-      {
396
-          $this->getUIDatabase()->testGetDb(); // Get DB in test mode
397
-          echo 'Schema already exists and is up to date<br>';
398
-          return;
399
-      }
400
-      catch (DBException $e)
401
-      {
402
-          $dberror=$e->getArray(); 
403
-      }
394
+	  try
395
+	  {
396
+		  $this->getUIDatabase()->testGetDb(); // Get DB in test mode
397
+		  echo 'Schema already exists and is up to date<br>';
398
+		  return;
399
+	  }
400
+	  catch (DBException $e)
401
+	  {
402
+		  $dberror=$e->getArray(); 
403
+	  }
404 404
 	  
405 405
 	  echo 'Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a><br><br>';
406 406
 	  
407 407
 	  if ($dberror[0] != 5)
408 408
 	  {
409
-	      echo 'Database does not exists or is not setup correctly<br>';
410
-	      return;
409
+		  echo 'Database does not exists or is not setup correctly<br>';
410
+		  return;
411 411
 	  }
412
-      // setup
412
+	  // setup
413 413
 	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
414 414
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
415 415
 	  $debug_level=4;
@@ -422,20 +422,20 @@  discard block
 block discarded – undo
422 422
 	  $target_version=$dberror[2];
423 423
 	  
424 424
 	  if ($this->params->get('msgok') == null) {
425
-	      // Check for messages and display if any
426
-              echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
427
-	      $Trap->setLogging(2,'syslog');
428
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
429
-	      if ($message != '')
430
-	      {
431
-	          echo 'Note :<br><pre>';
432
-	          echo $message;
433
-	          echo '</pre>';
434
-	          echo '<br>';
435
-	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
436
-	          echo '<br>';
437
-	          return;
438
-	      }
425
+		  // Check for messages and display if any
426
+			  echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
427
+		  $Trap->setLogging(2,'syslog');
428
+		  $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
429
+		  if ($message != '')
430
+		  {
431
+			  echo 'Note :<br><pre>';
432
+			  echo $message;
433
+			  echo '</pre>';
434
+			  echo '<br>';
435
+			  echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
436
+			  echo '<br>';
437
+			  return;
438
+		  }
439 439
 	  }
440 440
 	  
441 441
 	  $Trap->setLogging($debug_level,'display');
@@ -450,52 +450,52 @@  discard block
 block discarded – undo
450 450
   
451 451
   private function checkSnmpTrapd()
452 452
   {
453
-      $psOutput=array();
454
-      // First check is someone is listening to port 162. As not root, we can't have pid... 
455
-      $sspath = exec('which ss 2>/dev/null');
456
-      if(empty($sspath))
457
-      {
458
-          // RHEL based systems
459
-          $sspath = '/usr/sbin/ss';
460
-      }
461
-      if(!is_executable("$sspath"))
462
-      {
463
-          return array(1,"Can not execute $sspath");
464
-      }
465
-      exec("$sspath -lun | grep ':162 '",$psOutput);
466
-      if (count($psOutput) == 0)
467
-      {
468
-          $extra = "";
469
-          if (is_file("/.dockerenv")){ $extra = '<br />=&gt; ignore if Trapdirector is running in a different Docker container'; }
470
-          return array(1,'Port UDP/162 is not open : is snmptrapd running?'. $extra);
471
-      }
472
-      $psOutput=array();
473
-      $selinux_state = '';
474
-      if(is_executable('/usr/sbin/getenforce'))
475
-      {
476
-          $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
477
-      }
478
-      if($selinux_state !== 'Enforcing')
479
-      {
480
-          exec('ps --no-headers -o command -C snmptrapd',$psOutput);
481
-          if (count($psOutput) == 0)
482
-          {
483
-              return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
484
-          }
485
-          // Assume there is only one line... TODO : see if there is a better way to do this
486
-          $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
487
-          if (!preg_match('/-n/',$line))
488
-              return array(1,'snmptrapd has no -n option : '.$line);
489
-          if (!preg_match('/-O[^ ]*n/',$line))
490
-              return array(1,'snmptrapd has no -On option : '.$line);
491
-          if (!preg_match('/-O[^ ]*e/',$line))
492
-              return array(1,'snmptrapd has no -Oe option : '.$line);
453
+	  $psOutput=array();
454
+	  // First check is someone is listening to port 162. As not root, we can't have pid... 
455
+	  $sspath = exec('which ss 2>/dev/null');
456
+	  if(empty($sspath))
457
+	  {
458
+		  // RHEL based systems
459
+		  $sspath = '/usr/sbin/ss';
460
+	  }
461
+	  if(!is_executable("$sspath"))
462
+	  {
463
+		  return array(1,"Can not execute $sspath");
464
+	  }
465
+	  exec("$sspath -lun | grep ':162 '",$psOutput);
466
+	  if (count($psOutput) == 0)
467
+	  {
468
+		  $extra = "";
469
+		  if (is_file("/.dockerenv")){ $extra = '<br />=&gt; ignore if Trapdirector is running in a different Docker container'; }
470
+		  return array(1,'Port UDP/162 is not open : is snmptrapd running?'. $extra);
471
+	  }
472
+	  $psOutput=array();
473
+	  $selinux_state = '';
474
+	  if(is_executable('/usr/sbin/getenforce'))
475
+	  {
476
+		  $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
477
+	  }
478
+	  if($selinux_state !== 'Enforcing')
479
+	  {
480
+		  exec('ps --no-headers -o command -C snmptrapd',$psOutput);
481
+		  if (count($psOutput) == 0)
482
+		  {
483
+			  return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
484
+		  }
485
+		  // Assume there is only one line... TODO : see if there is a better way to do this
486
+		  $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
487
+		  if (!preg_match('/-n/',$line))
488
+			  return array(1,'snmptrapd has no -n option : '.$line);
489
+		  if (!preg_match('/-O[^ ]*n/',$line))
490
+			  return array(1,'snmptrapd has no -On option : '.$line);
491
+		  if (!preg_match('/-O[^ ]*e/',$line))
492
+			  return array(1,'snmptrapd has no -Oe option : '.$line);
493 493
 
494
-          return array(0,'snmptrapd listening to UDP/162, options : '.$line);
495
-      }
496
-      else
497
-      {
498
-          return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
499
-      }
494
+		  return array(0,'snmptrapd listening to UDP/162, options : '.$line);
495
+	  }
496
+	  else
497
+	  {
498
+		  return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
499
+	  }
500 500
   }
501 501
 }
Please login to merge, or discard this patch.
Spacing   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -72,23 +72,23 @@  discard block
 block discarded – undo
72 72
   private function check_db()
73 73
   {
74 74
       $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
-          0	=>	array('Database configuration OK','',''),
76
-          1	=>	array('Database set in config.ini','No database in config.ini',''),
77
-          2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
75
+          0	=>	array('Database configuration OK', '', ''),
76
+          1	=>	array('Database set in config.ini', 'No database in config.ini', ''),
77
+          2	=>	array('Database exists in Icingaweb2 config', 'Database does not exist in Icingaweb2 : ',
78 78
               Url::fromPath('config/resource')),
79
-          3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
79
+          3	=>	array('Database credentials OK', 'Database does not exist/invalid credentials/no schema : ',
80 80
               Url::fromPath('trapdirector/settings/createschema')),
81
-          4	=>	array('Schema is set','Schema is not set for ',
81
+          4	=>	array('Schema is set', 'Schema is not set for ',
82 82
               Url::fromPath('trapdirector/settings/createschema')),
83
-          5	=>	array('Schema is up to date','Schema is outdated :',
83
+          5	=>	array('Schema is up to date', 'Schema is outdated :',
84 84
               Url::fromPath('trapdirector/settings/updateschema')),
85 85
       );
86 86
       
87 87
       try {
88 88
           $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
-          $dberror=array(0,'');
89
+          $dberror=array(0, '');
90 90
       } catch (DBException $e) {
91
-          $dberror = $e->getArray();
91
+          $dberror=$e->getArray();
92 92
       }
93 93
       
94 94
       $this->view->db_error=$dberror[0];
@@ -96,13 +96,13 @@  discard block
 block discarded – undo
96 96
       {
97 97
           case 2:
98 98
           case 4:
99
-              $db_message[$dberror[0]][1] .= $dberror[1];
99
+              $db_message[$dberror[0]][1].=$dberror[1];
100 100
               break;
101 101
           case 3:
102
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
102
+              $db_message[$dberror[0]][1].=$dberror[1].', Message : '.$dberror[2];
103 103
               break;
104 104
           case 5:
105
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
105
+              $db_message[$dberror[0]][1].=' version '.$dberror[1].', version needed : '.$dberror[2];
106 106
               break;
107 107
           case 0:
108 108
           case 1:
@@ -114,14 +114,14 @@  discard block
 block discarded – undo
114 114
       
115 115
       try {
116 116
           $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
-          $dberror=array(0,'');
117
+          $dberror=array(0, '');
118 118
       } catch (DBException $e) {
119
-          $dberror = $e->getArray();
119
+          $dberror=$e->getArray();
120 120
       }
121 121
       
122 122
       $this->view->ido_db_error=$dberror[0];
123
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
124
-      $this->view->ido_message .='<br />=&gt; Default to API use. Make sure it is configured and check is returning OK!';
123
+      $this->view->ido_message='IDO Database : '.$dberror[1];
124
+      $this->view->ido_message.='<br />=&gt; Default to API use. Make sure it is configured and check is returning OK!';
125 125
   }
126 126
   
127 127
   /**
@@ -133,13 +133,13 @@  discard block
 block discarded – undo
133 133
   {
134 134
       if ($this->Config()->get('config', 'icingaAPI_host') != '')
135 135
       {
136
-          $apitest=new Icinga2API($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
136
+          $apitest=new Icinga2API($this->Config()->get('config', 'icingaAPI_host'), $this->Config()->get('config', 'icingaAPI_port'));
137 137
           $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
138 138
           try {
139
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
139
+              list($this->view->apimessageError, $this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
140 140
               //$this->view->apimessageError=false;
141 141
           } catch (RuntimeException $e) {
142
-              $this->view->apimessage='API config : ' . $e->getMessage();
142
+              $this->view->apimessage='API config : '.$e->getMessage();
143 143
               $this->view->apimessageError=true;
144 144
           }
145 145
       }
@@ -164,10 +164,10 @@  discard block
 block discarded – undo
164 164
       {
165 165
           $output=array();
166 166
           
167
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
167
+          exec('cat '.$this->module->getBaseDir().'/bin/trap_in.php | grep "\$icingaweb2Etc=" ', $output);
168 168
           
169 169
           
170
-          if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
170
+          if (!isset($output[0]) || !preg_match('#"'.$icingaweb2_etc.'"#', $output[0]))
171 171
           {
172 172
               $this->view->icingaEtcWarn=1;
173 173
               $this->view->icingaweb2_etc=$icingaweb2_etc;
@@ -183,12 +183,12 @@  discard block
 block discarded – undo
183 183
    */
184 184
   private function get_db_list($allowed)
185 185
   {
186
-      $resources = array();
186
+      $resources=array();
187 187
       foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
188 188
       {
189 189
           if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
190 190
           {
191
-              $resources[$name] = $name;
191
+              $resources[$name]=$name;
192 192
           }
193 193
       }
194 194
       return $resources;
@@ -200,18 +200,18 @@  discard block
 block discarded – undo
200 200
    */
201 201
   private function get_php_binary()
202 202
   {
203
-      $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
203
+      $phpBinary=array(PHP_BINARY, PHP_BINDIR."/php", '/usr/bin/php');
204 204
 
205
-      foreach ($phpBinary as $phpBin )
205
+      foreach ($phpBinary as $phpBin)
206 206
       {
207 207
           $output=array();
208 208
           $retCode=255;
209 209
           $input="154865134987aaaa";
210
-          exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
210
+          exec("$phpBin -r \"echo '$input';\"", $output, $retCode);
211 211
           
212
-          if (! isset($output[0])) $output[0]="NO OUT";
212
+          if (!isset($output[0])) $output[0]="NO OUT";
213 213
           
214
-          if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
214
+          if ($retCode == 0 && preg_match("/$input/", $output[0]) == 1)
215 215
           {
216 216
               return $phpBin;
217 217
           }          
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
 	// But check read permission
241 241
 	$this->checkReadPermission();
242 242
 	
243
-	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');	
243
+	$this->view->tabs=$this->Module()->getConfigTabs()->activate('config');	
244 244
 	
245 245
 	// Get message : sent on configuration problems detected by controllers
246 246
     $this->get_param();
@@ -255,39 +255,39 @@  discard block
 block discarded – undo
255 255
     $this->check_api();
256 256
 	
257 257
 	//Test snmptrapd alive and options
258
-	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
258
+	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage)=$this->checkSnmpTrapd();
259 259
 
260 260
 	// List DB in $ressources
261
-	$resources = $this->get_db_list(array('mysql', 'pgsql')); 
261
+	$resources=$this->get_db_list(array('mysql', 'pgsql')); 
262 262
 
263 263
 	// Check standard Icingaweb2 path
264 264
 	$this->check_icingaweb_path();
265 265
 
266
-	$phpBinary = $this->get_php_binary();
266
+	$phpBinary=$this->get_php_binary();
267 267
 	if ($phpBinary === null)
268 268
 	{
269
-	    $phpBinary = ' PHP BINARY NOT FOUND ';
269
+	    $phpBinary=' PHP BINARY NOT FOUND ';
270 270
 	    
271 271
 	}
272 272
 	
273 273
 	// Setup path for mini documentation
274
-	$this->view->traps_in_config= $phpBinary . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
274
+	$this->view->traps_in_config=$phpBinary.' '.$this->Module()->getBaseDir().'/bin/trap_in.php';
275 275
 	
276
-	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
276
+	$this->view->installer=$this->Module()->getBaseDir().'/bin/installer.sh '
277 277
 	    . ' -c all ' 
278
-	    . ' -d ' . $this->Module()->getBaseDir()
279
-	    . ' -p ' . $phpBinary
280
-	    . ' -a ' . exec('whoami')
281
-	    . ' -w ' . Icinga::app()->getConfigDir();
278
+	    . ' -d '.$this->Module()->getBaseDir()
279
+	    . ' -p '.$phpBinary
280
+	    . ' -a '.exec('whoami')
281
+	    . ' -w '.Icinga::app()->getConfigDir();
282 282
 	        
283 283
 	// ******************* configuration form setup*******************
284
-	$this->view->form = $form = new TrapsConfigForm();
284
+	$this->view->form=$form=new TrapsConfigForm();
285 285
 	
286 286
 	// set default paths;
287
-	$this->view->form->setPaths($this->Module()->getBaseDir(),Icinga::app()->getConfigDir());
287
+	$this->view->form->setPaths($this->Module()->getBaseDir(), Icinga::app()->getConfigDir());
288 288
 	
289 289
 	// set default ido database
290
-	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring','backends')->get('icinga','resource'));
290
+	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring', 'backends')->get('icinga', 'resource'));
291 291
 	
292 292
 	// Make form handle request.
293 293
 	$form->setIniConfig($this->Config())
@@ -316,18 +316,18 @@  discard block
 block discarded – undo
316 316
       $this->view->configPermission=$this->checkModuleConfigPermission();
317 317
       
318 318
       // Setup tabs
319
-      $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
319
+      $this->view->tabs=$this->Module()->getConfigTabs()->activate('satellite');	
320 320
       
321
-      $this->view->masterHASet = FALSE;
321
+      $this->view->masterHASet=FALSE;
322 322
       
323
-      $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
323
+      $this->view->masterHAConf=array('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
324 324
   }
325 325
   
326 326
   
327 327
   public function createschemaAction()
328 328
   {
329 329
 	$this->checkModuleConfigPermission();
330
-	$this->getTabs()->add('create_schema',array(
330
+	$this->getTabs()->add('create_schema', array(
331 331
 		'active'	=> true,
332 332
 		'label'		=> $this->translate('Create Schema'),
333 333
 		'url'		=> Url::fromRequest()
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
 		// Get module database name
349 349
 		$dbName=$this->Config()->get('config', 'database');
350 350
 
351
-        $dbResource = ResourceFactory::getResourceConfig($dbName);
351
+        $dbResource=ResourceFactory::getResourceConfig($dbName);
352 352
         $dbType=$dbResource->get('db');
353 353
         switch ($dbType) {
354 354
           case 'mysql':
@@ -363,28 +363,28 @@  discard block
 block discarded – undo
363 363
         } 
364 364
 
365 365
 		printf('<pre>');
366
-		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
366
+		require_once $this->Module()->getBaseDir().'/bin/trap_class.php';
367 367
 		
368 368
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
369 369
 		$debug_level=4;
370
-		$Trap = new Trap($icingaweb2_etc);
371
-		$Trap->setLogging($debug_level,'display');
370
+		$Trap=new Trap($icingaweb2_etc);
371
+		$Trap->setLogging($debug_level, 'display');
372 372
 		
373 373
 		$prefix=$this->Config()->get('config', 'database_prefix');
374 374
 		// schema file : <path>/SQL/schema_v<verion>.<dbtype>
375
-		$schema=$this->Module()->getBaseDir() . 
376
-		'/SQL/schema_v'. $this->getModuleConfig()->getDbCurVersion() . '.' . $dbFileExt;
375
+		$schema=$this->Module()->getBaseDir(). 
376
+		'/SQL/schema_v'.$this->getModuleConfig()->getDbCurVersion().'.'.$dbFileExt;
377 377
 		
378
-		$Trap->trapsDB->create_schema($schema,$prefix);
378
+		$Trap->trapsDB->create_schema($schema, $prefix);
379 379
 		echo '</pre>';
380 380
 	}
381
-	echo '<br><br>Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a>';
381
+	echo '<br><br>Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a>';
382 382
   }
383 383
 
384 384
   public function updateschemaAction()
385 385
   {
386 386
 	  $this->checkModuleConfigPermission();
387
-      $this->getTabs()->add('get',array(
387
+      $this->getTabs()->add('get', array(
388 388
     		'active'	=> true,
389 389
     		'label'		=> $this->translate('Update Schema'),
390 390
     		'url'		=> Url::fromRequest()
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
           $dberror=$e->getArray(); 
403 403
       }
404 404
 	  
405
-	  echo 'Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a><br><br>';
405
+	  echo 'Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a><br><br>';
406 406
 	  
407 407
 	  if ($dberror[0] != 5)
408 408
 	  {
@@ -410,40 +410,40 @@  discard block
 block discarded – undo
410 410
 	      return;
411 411
 	  }
412 412
       // setup
413
-	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
413
+	  require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
414 414
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
415 415
 	  $debug_level=4;
416
-	  $Trap = new Trap($icingaweb2_etc);
416
+	  $Trap=new Trap($icingaweb2_etc);
417 417
 	  
418 418
 	  
419 419
 	  $prefix=$this->Config()->get('config', 'database_prefix');
420
-	  $updateSchema=$this->Module()->getBaseDir() . '/SQL/';
420
+	  $updateSchema=$this->Module()->getBaseDir().'/SQL/';
421 421
 	  
422 422
 	  $target_version=$dberror[2];
423 423
 	  
424 424
 	  if ($this->params->get('msgok') == null) {
425 425
 	      // Check for messages and display if any
426 426
               echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
427
-	      $Trap->setLogging(2,'syslog');
428
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
427
+	      $Trap->setLogging(2, 'syslog');
428
+	      $message=$Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix, true);
429 429
 	      if ($message != '')
430 430
 	      {
431 431
 	          echo 'Note :<br><pre>';
432 432
 	          echo $message;
433 433
 	          echo '</pre>';
434 434
 	          echo '<br>';
435
-	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
435
+	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="'.Url::fromPath('trapdirector/settings/updateschema').'?msgok=1">Click here to update</a>';
436 436
 	          echo '<br>';
437 437
 	          return;
438 438
 	      }
439 439
 	  }
440 440
 	  
441
-	  $Trap->setLogging($debug_level,'display');
441
+	  $Trap->setLogging($debug_level, 'display');
442 442
 	  
443
-	  echo 'Updating schema to '. $target_version . ': <br>';
443
+	  echo 'Updating schema to '.$target_version.': <br>';
444 444
 	  echo '<pre>';
445 445
 	  	  
446
-	  $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix);
446
+	  $Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix);
447 447
 	  echo '</pre>';
448 448
   }  
449 449
 
@@ -452,50 +452,50 @@  discard block
 block discarded – undo
452 452
   {
453 453
       $psOutput=array();
454 454
       // First check is someone is listening to port 162. As not root, we can't have pid... 
455
-      $sspath = exec('which ss 2>/dev/null');
456
-      if(empty($sspath))
455
+      $sspath=exec('which ss 2>/dev/null');
456
+      if (empty($sspath))
457 457
       {
458 458
           // RHEL based systems
459
-          $sspath = '/usr/sbin/ss';
459
+          $sspath='/usr/sbin/ss';
460 460
       }
461
-      if(!is_executable("$sspath"))
461
+      if (!is_executable("$sspath"))
462 462
       {
463
-          return array(1,"Can not execute $sspath");
463
+          return array(1, "Can not execute $sspath");
464 464
       }
465
-      exec("$sspath -lun | grep ':162 '",$psOutput);
465
+      exec("$sspath -lun | grep ':162 '", $psOutput);
466 466
       if (count($psOutput) == 0)
467 467
       {
468
-          $extra = "";
469
-          if (is_file("/.dockerenv")){ $extra = '<br />=&gt; ignore if Trapdirector is running in a different Docker container'; }
470
-          return array(1,'Port UDP/162 is not open : is snmptrapd running?'. $extra);
468
+          $extra="";
469
+          if (is_file("/.dockerenv")) { $extra='<br />=&gt; ignore if Trapdirector is running in a different Docker container'; }
470
+          return array(1, 'Port UDP/162 is not open : is snmptrapd running?'.$extra);
471 471
       }
472 472
       $psOutput=array();
473
-      $selinux_state = '';
474
-      if(is_executable('/usr/sbin/getenforce'))
473
+      $selinux_state='';
474
+      if (is_executable('/usr/sbin/getenforce'))
475 475
       {
476
-          $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
476
+          $selinux_state=exec('/usr/sbin/getenforce 2>/dev/null');
477 477
       }
478
-      if($selinux_state !== 'Enforcing')
478
+      if ($selinux_state !== 'Enforcing')
479 479
       {
480
-          exec('ps --no-headers -o command -C snmptrapd',$psOutput);
480
+          exec('ps --no-headers -o command -C snmptrapd', $psOutput);
481 481
           if (count($psOutput) == 0)
482 482
           {
483
-              return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
483
+              return array(1, "UDP/162 : OK, but no snmptrapd process (?)");
484 484
           }
485 485
           // Assume there is only one line... TODO : see if there is a better way to do this
486
-          $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
487
-          if (!preg_match('/-n/',$line))
488
-              return array(1,'snmptrapd has no -n option : '.$line);
489
-          if (!preg_match('/-O[^ ]*n/',$line))
490
-              return array(1,'snmptrapd has no -On option : '.$line);
491
-          if (!preg_match('/-O[^ ]*e/',$line))
492
-              return array(1,'snmptrapd has no -Oe option : '.$line);
486
+          $line=preg_replace('/^.*snmptrapd /', '', $psOutput[0]);
487
+          if (!preg_match('/-n/', $line))
488
+              return array(1, 'snmptrapd has no -n option : '.$line);
489
+          if (!preg_match('/-O[^ ]*n/', $line))
490
+              return array(1, 'snmptrapd has no -On option : '.$line);
491
+          if (!preg_match('/-O[^ ]*e/', $line))
492
+              return array(1, 'snmptrapd has no -Oe option : '.$line);
493 493
 
494
-          return array(0,'snmptrapd listening to UDP/162, options : '.$line);
494
+          return array(0, 'snmptrapd listening to UDP/162, options : '.$line);
495 495
       }
496 496
       else
497 497
       {
498
-          return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
498
+          return array(0, 'A daemon (hidden by SELinux) is listening on UDP/162');
499 499
       }
500 500
   }
501 501
 }
Please login to merge, or discard this patch.
application/clicommands/MibCommand.php 2 patches
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -22,77 +22,77 @@  discard block
 block discarded – undo
22 22
 class MibCommand extends Command
23 23
 {
24 24
 	/**
25
-	*	Update mib database
26
-	*
27
-	*	USAGE 
28
-	*
29
-	*	icingli trapdirector mib update
30
-	*	
31
-	*	OPTIONS
32
-	*	
33
-	*	--pid <file> : run in background with pid in <file>
34
-	*
35
-	*	--verb    : Set output log to verbose
36
-	*
37
-	*   --force-check : force check of all traps & objects for change. (NOT IMPLEMENTED)
38
-	*/
25
+	 *	Update mib database
26
+	 *
27
+	 *	USAGE 
28
+	 *
29
+	 *	icingli trapdirector mib update
30
+	 *	
31
+	 *	OPTIONS
32
+	 *	
33
+	 *	--pid <file> : run in background with pid in <file>
34
+	 *
35
+	 *	--verb    : Set output log to verbose
36
+	 *
37
+	 *   --force-check : force check of all traps & objects for change. (NOT IMPLEMENTED)
38
+	 */
39 39
 	public function updateAction()
40 40
 	{
41
-	    $background = $this->params->get('pid', null);
42
-	    $logLevel= $this->params->has('verb') ? 4 : 2;
43
-	    if ($this->params->has('force-check')) { echo "Not implemented"; return;}
44
-	    $forceCheck=$this->params->has('force-check')?True:False;
45
-	    $pid=1;
46
-	    if ($background != null)
47
-	    {
48
-	        $file=@fopen($background,'w');
49
-	        if ($file == false)
50
-	        {
51
-	            echo 'Error : cannot open pid file '.$background;
52
-	            return 1;
53
-	        }
54
-	        $pid = pcntl_fork();
55
-	        if ($pid == -1) {
56
-	            echo 'Error : Cannot fork process';
57
-	            return 1;
58
-	        }
59
-	    }
60
-	    $module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
41
+		$background = $this->params->get('pid', null);
42
+		$logLevel= $this->params->has('verb') ? 4 : 2;
43
+		if ($this->params->has('force-check')) { echo "Not implemented"; return;}
44
+		$forceCheck=$this->params->has('force-check')?True:False;
45
+		$pid=1;
46
+		if ($background != null)
47
+		{
48
+			$file=@fopen($background,'w');
49
+			if ($file == false)
50
+			{
51
+				echo 'Error : cannot open pid file '.$background;
52
+				return 1;
53
+			}
54
+			$pid = pcntl_fork();
55
+			if ($pid == -1) {
56
+				echo 'Error : Cannot fork process';
57
+				return 1;
58
+			}
59
+		}
60
+		$module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
61 61
 		require_once($module->getBaseDir() .'/bin/trap_class.php');
62 62
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
63 63
 		$trap = new Trap($icingaweb2_etc);
64 64
 		if ($pid == 1)
65 65
 		{
66
-		    $trap->setLogging($logLevel,'display');
66
+			$trap->setLogging($logLevel,'display');
67 67
 		}
68 68
 		else
69 69
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
70
-		    if ($pid != 0)
71
-		    {
72
-		        // father process
73
-		        fwrite($file,$pid);
74
-		        fclose($file);
75
-		        echo "OK : process $pid in bckground";
76
-		        return 0;
77
-		    }
78
-		    else
79
-		    {  // son process : close all file descriptors and go to a new session
80
-		        fclose($file);		        
70
+			if ($pid != 0)
71
+			{
72
+				// father process
73
+				fwrite($file,$pid);
74
+				fclose($file);
75
+				echo "OK : process $pid in bckground";
76
+				return 0;
77
+			}
78
+			else
79
+			{  // son process : close all file descriptors and go to a new session
80
+				fclose($file);		        
81 81
 // 		        $sid = posix_setsid();
82
-                fclose(STDIN);
83
-                fclose(STDOUT);
84
-                fclose(STDERR);
85
-                try
86
-                {
87
-                    $trap->mibClass->update_mib_database(false,$forceCheck);
88
-                }
89
-                catch (Exception $e)
90
-                {
91
-                    $trap->logging->log('Error in updating : ' . $e->getMessage(),2);
92
-                }
93
-                unlink($background);
94
-                return 0;
95
-		    }
82
+				fclose(STDIN);
83
+				fclose(STDOUT);
84
+				fclose(STDERR);
85
+				try
86
+				{
87
+					$trap->mibClass->update_mib_database(false,$forceCheck);
88
+				}
89
+				catch (Exception $e)
90
+				{
91
+					$trap->logging->log('Error in updating : ' . $e->getMessage(),2);
92
+				}
93
+				unlink($background);
94
+				return 0;
95
+			}
96 96
 		    
97 97
 		}
98 98
 		
@@ -110,28 +110,28 @@  discard block
 block discarded – undo
110 110
 		}
111 111
 		if ($pid != 1)
112 112
 		{
113
-		    unlink($background);
113
+			unlink($background);
114 114
 		}
115 115
 	}
116 116
 	/**
117
-	*	purge all mib database NOT IMPLEMENTED
118
-	*
119
-	*	USAGE 
120
-	*
121
-	*	icingli trapdirector mib purge --confirm
122
-	*	
123
-	*	OPTIONS
124
-	*	
125
-	*	--confirm : needed to execute purge
126
-	*/
117
+	 *	purge all mib database NOT IMPLEMENTED
118
+	 *
119
+	 *	USAGE 
120
+	 *
121
+	 *	icingli trapdirector mib purge --confirm
122
+	 *	
123
+	 *	OPTIONS
124
+	 *	
125
+	 *	--confirm : needed to execute purge
126
+	 */
127 127
 	public function purgeAction()
128 128
 	{
129 129
 		$db_prefix=$this->Config()->get('config', 'database_prefix');
130 130
 		
131 131
 		if (!$this->params->has('confirm'))
132 132
 		{
133
-		    echo "This needs confirmation with '--confirm'\n";
134
-		    return;
133
+			echo "This needs confirmation with '--confirm'\n";
134
+			return;
135 135
 		}
136 136
 		
137 137
 		$Config = new TrapModuleConfig($db_prefix);
@@ -145,9 +145,9 @@  discard block
 block discarded – undo
145 145
 			$db = IcingaDbConnection::fromResourceName($dbresource)->getDbAdapter();
146 146
 			
147 147
 			$query = $db->delete(
148
-			    $Config->getMIBCacheTableName(),
149
-			    'id>0');
150
-            echo 'Deleted '. $query . " traps and objects\n";
148
+				$Config->getMIBCacheTableName(),
149
+				'id>0');
150
+			echo 'Deleted '. $query . " traps and objects\n";
151 151
 		}
152 152
 		catch (Exception $e)
153 153
 		{
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -38,39 +38,39 @@  discard block
 block discarded – undo
38 38
 	*/
39 39
 	public function updateAction()
40 40
 	{
41
-	    $background = $this->params->get('pid', null);
42
-	    $logLevel= $this->params->has('verb') ? 4 : 2;
43
-	    if ($this->params->has('force-check')) { echo "Not implemented"; return;}
44
-	    $forceCheck=$this->params->has('force-check')?True:False;
41
+	    $background=$this->params->get('pid', null);
42
+	    $logLevel=$this->params->has('verb') ? 4 : 2;
43
+	    if ($this->params->has('force-check')) { echo "Not implemented"; return; }
44
+	    $forceCheck=$this->params->has('force-check') ?True:False;
45 45
 	    $pid=1;
46 46
 	    if ($background != null)
47 47
 	    {
48
-	        $file=@fopen($background,'w');
48
+	        $file=@fopen($background, 'w');
49 49
 	        if ($file == false)
50 50
 	        {
51 51
 	            echo 'Error : cannot open pid file '.$background;
52 52
 	            return 1;
53 53
 	        }
54
-	        $pid = pcntl_fork();
54
+	        $pid=pcntl_fork();
55 55
 	        if ($pid == -1) {
56 56
 	            echo 'Error : Cannot fork process';
57 57
 	            return 1;
58 58
 	        }
59 59
 	    }
60 60
 	    $module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
61
-		require_once($module->getBaseDir() .'/bin/trap_class.php');
61
+		require_once($module->getBaseDir().'/bin/trap_class.php');
62 62
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
63
-		$trap = new Trap($icingaweb2_etc);
63
+		$trap=new Trap($icingaweb2_etc);
64 64
 		if ($pid == 1)
65 65
 		{
66
-		    $trap->setLogging($logLevel,'display');
66
+		    $trap->setLogging($logLevel, 'display');
67 67
 		}
68 68
 		else
69 69
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
70 70
 		    if ($pid != 0)
71 71
 		    {
72 72
 		        // father process
73
-		        fwrite($file,$pid);
73
+		        fwrite($file, $pid);
74 74
 		        fclose($file);
75 75
 		        echo "OK : process $pid in bckground";
76 76
 		        return 0;
@@ -84,11 +84,11 @@  discard block
 block discarded – undo
84 84
                 fclose(STDERR);
85 85
                 try
86 86
                 {
87
-                    $trap->mibClass->update_mib_database(false,$forceCheck);
87
+                    $trap->mibClass->update_mib_database(false, $forceCheck);
88 88
                 }
89 89
                 catch (Exception $e)
90 90
                 {
91
-                    $trap->logging->log('Error in updating : ' . $e->getMessage(),2);
91
+                    $trap->logging->log('Error in updating : '.$e->getMessage(), 2);
92 92
                 }
93 93
                 unlink($background);
94 94
                 return 0;
@@ -100,13 +100,13 @@  discard block
 block discarded – undo
100 100
 		{
101 101
 			echo "Update main mib database : \n";
102 102
 			echo "# (trap found) C (trap already processed) . (every 2 seconds) : \n";
103
-			$trap->mibClass->update_mib_database(true,$forceCheck);
103
+			$trap->mibClass->update_mib_database(true, $forceCheck);
104 104
 			echo "Done\n";
105 105
 			
106 106
 		}
107 107
 		catch (Exception $e)
108 108
 		{
109
-			echo 'Error in updating : ' . $e->getMessage();
109
+			echo 'Error in updating : '.$e->getMessage();
110 110
 		}
111 111
 		if ($pid != 1)
112 112
 		{
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 		    return;
135 135
 		}
136 136
 		
137
-		$Config = new TrapModuleConfig($db_prefix);
137
+		$Config=new TrapModuleConfig($db_prefix);
138 138
 		
139 139
 		try
140 140
 		{
@@ -142,16 +142,16 @@  discard block
 block discarded – undo
142 142
 			$dbresource=$this->Config()->get('config', 'database');
143 143
 			echo "DB name : $dbresource\n";
144 144
 //			$db = IcingaDbConnection::fromResourceName($dbresource)->getConnection();
145
-			$db = IcingaDbConnection::fromResourceName($dbresource)->getDbAdapter();
145
+			$db=IcingaDbConnection::fromResourceName($dbresource)->getDbAdapter();
146 146
 			
147
-			$query = $db->delete(
147
+			$query=$db->delete(
148 148
 			    $Config->getMIBCacheTableName(),
149 149
 			    'id>0');
150
-            echo 'Deleted '. $query . " traps and objects\n";
150
+            echo 'Deleted '.$query." traps and objects\n";
151 151
 		}
152 152
 		catch (Exception $e)
153 153
 		{
154
-			echo 'Error in DB : ' . $e->getMessage();
154
+			echo 'Error in DB : '.$e->getMessage();
155 155
 		}	   
156 156
 	}  	 	
157 157
 
Please login to merge, or discard this patch.
application/clicommands/StatusCommand.php 1 patch
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -24,22 +24,22 @@
 block discarded – undo
24 24
 	public function dbAction()
25 25
 	{
26 26
 		$db_prefix=$this->Config()->get('config', 'database_prefix');
27
-		$Config = new TrapModuleConfig($db_prefix);
27
+		$Config=new TrapModuleConfig($db_prefix);
28 28
 		
29 29
 		try
30 30
 		{
31 31
 			
32 32
 			$dbresource=$this->Config()->get('config', 'database');
33
-			printf("DB name : %s\n",$dbresource);
33
+			printf("DB name : %s\n", $dbresource);
34 34
 //			$dataBase = IcingaDbConnection::fromResourceName($dbresource)->getConnection();
35
-			$dataBase = IcingaDbConnection::fromResourceName($dbresource)->getDbAdapter();
35
+			$dataBase=IcingaDbConnection::fromResourceName($dbresource)->getDbAdapter();
36 36
 			
37
-			$query = $dataBase->select()->from($Config->getTrapTableName(),array('COUNT(*)'));			
38
-			printf("Number of traps : %s\n", $dataBase->fetchOne($query) );
39
-			$query = $dataBase->select()->from($Config->getTrapDataTableName(),array('COUNT(*)'));			
40
-			printf("Number of trap objects : %s\n", $dataBase->fetchOne($query) );
41
-			$query = $dataBase->select()->from($Config->getTrapRuleName(),array('COUNT(*)'));			
42
-			printf("Number of rules : %s\n", $dataBase->fetchOne($query) );
37
+			$query=$dataBase->select()->from($Config->getTrapTableName(), array('COUNT(*)'));			
38
+			printf("Number of traps : %s\n", $dataBase->fetchOne($query));
39
+			$query=$dataBase->select()->from($Config->getTrapDataTableName(), array('COUNT(*)'));			
40
+			printf("Number of trap objects : %s\n", $dataBase->fetchOne($query));
41
+			$query=$dataBase->select()->from($Config->getTrapRuleName(), array('COUNT(*)'));			
42
+			printf("Number of rules : %s\n", $dataBase->fetchOne($query));
43 43
 			
44 44
 		}
45 45
 		catch (Exception $e)
Please login to merge, or discard this patch.
library/Trapdirector/TrapsActions/UIDatabase.php 2 patches
Indentation   +260 added lines, -260 removed lines patch added patch discarded remove patch
@@ -19,30 +19,30 @@  discard block
 block discarded – undo
19 19
  */
20 20
 class DBException extends Exception
21 21
 {
22
-    /** @var array $returnArray */
23
-    private $returnArray;
22
+	/** @var array $returnArray */
23
+	private $returnArray;
24 24
     
25
-    /**
26
-     * Buil DBException
27
-     * @param array $retarray
28
-     * @param string $message
29
-     * @param int $code
30
-     * @param Exception $previous
31
-     */
32
-    public function __construct(array $retarray, string $message = null, int $code = 0, Exception $previous = null)
33
-    {
34
-        parent::__construct($message,$code,$previous);
35
-        $this->returnArray = $retarray;
36
-    }
25
+	/**
26
+	 * Buil DBException
27
+	 * @param array $retarray
28
+	 * @param string $message
29
+	 * @param int $code
30
+	 * @param Exception $previous
31
+	 */
32
+	public function __construct(array $retarray, string $message = null, int $code = 0, Exception $previous = null)
33
+	{
34
+		parent::__construct($message,$code,$previous);
35
+		$this->returnArray = $retarray;
36
+	}
37 37
     
38
-    /**
39
-     * Get exception array
40
-     * @return array
41
-     */
42
-    public function getArray()
43
-    {
44
-        return $this->returnArray;
45
-    }
38
+	/**
39
+	 * Get exception array
40
+	 * @return array
41
+	 */
42
+	public function getArray()
43
+	{
44
+		return $this->returnArray;
45
+	}
46 46
 }
47 47
 
48 48
 /**
@@ -56,279 +56,279 @@  discard block
 block discarded – undo
56 56
  */
57 57
 class UIDatabase //extends TrapDBQuery
58 58
 {
59
-    use TrapDBQuery,IdoDBQuery;
59
+	use TrapDBQuery,IdoDBQuery;
60 60
     
61
-    /** @var TrapsController $trapController TrapController 'parent' class */
62
-    protected  $trapController=null;
61
+	/** @var TrapsController $trapController TrapController 'parent' class */
62
+	protected  $trapController=null;
63 63
     
64
-    /** @var Selectable $trapDB Trap Database*/
65
-    protected $trapDB=null;
64
+	/** @var Selectable $trapDB Trap Database*/
65
+	protected $trapDB=null;
66 66
  
67
-    /** @var Selectable $trapDB Icinga IDO database*/
68
-    protected $idoDB=null;
67
+	/** @var Selectable $trapDB Icinga IDO database*/
68
+	protected $idoDB=null;
69 69
     
70
-    /** @var array $testResult */
71
-    protected $testResult;
70
+	/** @var array $testResult */
71
+	protected $testResult;
72 72
     
73
-    /**
74
-     * 
75
-     * @param TrapsController $trapCtrl
76
-     */
77
-    function __construct(TrapsController $trapCtrl)
78
-    {
79
-        $this->trapController=$trapCtrl;
80
-    }
73
+	/**
74
+	 * 
75
+	 * @param TrapsController $trapCtrl
76
+	 */
77
+	function __construct(TrapsController $trapCtrl)
78
+	{
79
+		$this->trapController=$trapCtrl;
80
+	}
81 81
     
82
-    /**
83
-     * Get TrapsController instance
84
-     * @return TrapsController
85
-     */
86
-    protected function getTrapCtrl()
87
-    {
88
-        return $this->trapController;
89
-    }
82
+	/**
83
+	 * Get TrapsController instance
84
+	 * @return TrapsController
85
+	 */
86
+	protected function getTrapCtrl()
87
+	{
88
+		return $this->trapController;
89
+	}
90 90
     
91
-    /**
92
-     * Test if database version >= min database version
93
-     * 
94
-     * @param \Zend_Db_Adapter_Abstract $dbConn
95
-     * @param int $min Minimum version
96
-     * @param bool $test Test mode
97
-     * @param string $DBname Name of DB
98
-     * @return bool true if OK, false if version < min version
99
-     * @throws Exception if error and test = true
100
-     */
101
-    protected function testDbVersion($dbAdapter,int $min,bool $test, string $DBname)
102
-    {
103
-        try
104
-        {
105
-            $query = $dbAdapter->select()
106
-            ->from($this->trapController->getModuleConfig()->getDbConfigTableName(),'value')
107
-            ->where('name=\'db_version\'');
108
-            $version=$dbAdapter->fetchRow($query);
109
-            if ( ($version == null) || ! property_exists($version,'value') )
110
-            {
111
-                if ($test === true) 
112
-                {
113
-                    $this->testResult = array(4,$DBname);
114
-                    return false;
115
-                }
116
-                $this->trapController->redirectNow('trapdirector/settings?dberror=4');
117
-                return false;
118
-            }
119
-            if ($version->value < $min)
120
-            {
121
-                if ($test === true) 
122
-                {
123
-                    $this->testResult = array(5,$version->value,$min);
124
-                    return false;
125
-                }
126
-                $this->trapController->redirectNow('trapdirector/settings?dberror=5');
127
-                return false;
128
-            }
129
-        }
130
-        catch (Exception $e)
131
-        {
132
-            if ($test === true) 
133
-            {
134
-                $this->testResult = array(3,$DBname,$e->getMessage());
135
-                return false;
136
-            }
137
-            $this->trapController->redirectNow('trapdirector/settings?dberror=4');
138
-            return false;
139
-        }
140
-        return true;
141
-    }
91
+	/**
92
+	 * Test if database version >= min database version
93
+	 * 
94
+	 * @param \Zend_Db_Adapter_Abstract $dbConn
95
+	 * @param int $min Minimum version
96
+	 * @param bool $test Test mode
97
+	 * @param string $DBname Name of DB
98
+	 * @return bool true if OK, false if version < min version
99
+	 * @throws Exception if error and test = true
100
+	 */
101
+	protected function testDbVersion($dbAdapter,int $min,bool $test, string $DBname)
102
+	{
103
+		try
104
+		{
105
+			$query = $dbAdapter->select()
106
+			->from($this->trapController->getModuleConfig()->getDbConfigTableName(),'value')
107
+			->where('name=\'db_version\'');
108
+			$version=$dbAdapter->fetchRow($query);
109
+			if ( ($version == null) || ! property_exists($version,'value') )
110
+			{
111
+				if ($test === true) 
112
+				{
113
+					$this->testResult = array(4,$DBname);
114
+					return false;
115
+				}
116
+				$this->trapController->redirectNow('trapdirector/settings?dberror=4');
117
+				return false;
118
+			}
119
+			if ($version->value < $min)
120
+			{
121
+				if ($test === true) 
122
+				{
123
+					$this->testResult = array(5,$version->value,$min);
124
+					return false;
125
+				}
126
+				$this->trapController->redirectNow('trapdirector/settings?dberror=5');
127
+				return false;
128
+			}
129
+		}
130
+		catch (Exception $e)
131
+		{
132
+			if ($test === true) 
133
+			{
134
+				$this->testResult = array(3,$DBname,$e->getMessage());
135
+				return false;
136
+			}
137
+			$this->trapController->redirectNow('trapdirector/settings?dberror=4');
138
+			return false;
139
+		}
140
+		return true;
141
+	}
142 142
     
143
-    /**	Get Database connexion
144
-     *	@param $DBname string DB name in resource.ini_ge
145
-     *	@param $test bool if set to true, returns error code and not database
146
-     *	@param $test_version bool if set to flase, does not test database version of trapDB
147
-     *  @throws DBException if test = true and error
148
-     *	@return Selectable|null : if test=false, returns DB connexion, else array(error_num,message) or null on error.
149
-     */
150
-    protected function getDbByName($DBname , $test = false , $test_version = true)
151
-    {
152
-        try
153
-        {
154
-            $dbconn = IcingaDbConnection::fromResourceName($DBname);
155
-        }
156
-        catch (Exception $e)
157
-        {
158
-            if ($test === true) 
159
-            {
160
-                throw new DBException(array(2,$DBname));
161
-            }
162
-            $this->trapController->redirectNow('trapdirector/settings?dberror=2');
163
-            return null;
164
-        }
143
+	/**	Get Database connexion
144
+	 *	@param $DBname string DB name in resource.ini_ge
145
+	 *	@param $test bool if set to true, returns error code and not database
146
+	 *	@param $test_version bool if set to flase, does not test database version of trapDB
147
+	 *  @throws DBException if test = true and error
148
+	 *	@return Selectable|null : if test=false, returns DB connexion, else array(error_num,message) or null on error.
149
+	 */
150
+	protected function getDbByName($DBname , $test = false , $test_version = true)
151
+	{
152
+		try
153
+		{
154
+			$dbconn = IcingaDbConnection::fromResourceName($DBname);
155
+		}
156
+		catch (Exception $e)
157
+		{
158
+			if ($test === true) 
159
+			{
160
+				throw new DBException(array(2,$DBname));
161
+			}
162
+			$this->trapController->redirectNow('trapdirector/settings?dberror=2');
163
+			return null;
164
+		}
165 165
         
166
-        try
167
-        {
168
-            $dbAdapter=$dbconn->getDbAdapter();
166
+		try
167
+		{
168
+			$dbAdapter=$dbconn->getDbAdapter();
169 169
             
170
-        }
171
-        catch (Exception $e)
172
-        {
173
-            if ($test === true)
174
-            {
175
-                throw new DBException(array(3,$DBname,$e->getMessage()));
176
-            }
177
-            $this->trapController->redirectNow('trapdirector/settings?dberror=3');
178
-            return null;
179
-        }
170
+		}
171
+		catch (Exception $e)
172
+		{
173
+			if ($test === true)
174
+			{
175
+				throw new DBException(array(3,$DBname,$e->getMessage()));
176
+			}
177
+			$this->trapController->redirectNow('trapdirector/settings?dberror=3');
178
+			return null;
179
+		}
180 180
         
181
-        if ($test_version == true) {
182
-            $testRet=$this->testDbVersion($dbAdapter, $this->trapController->getModuleConfig()->getDbMinVersion(), $test, $DBname);
183
-            if ($testRet !== true) 
184
-            {
185
-                throw new DBException($this->testResult);
186
-            }
187
-        }
181
+		if ($test_version == true) {
182
+			$testRet=$this->testDbVersion($dbAdapter, $this->trapController->getModuleConfig()->getDbMinVersion(), $test, $DBname);
183
+			if ($testRet !== true) 
184
+			{
185
+				throw new DBException($this->testResult);
186
+			}
187
+		}
188 188
         
189
-        return $dbconn;
190
-    }
189
+		return $dbconn;
190
+	}
191 191
 
192
-    /**
193
-     * Get Trap database
194
-     * @return Selectable|null : returns DB connexion or null on error.
195
-     */
196
-    public function getDb()
197
-    {
198
-        if ( $this->trapDB != null ) return $this->trapDB;
192
+	/**
193
+	 * Get Trap database
194
+	 * @return Selectable|null : returns DB connexion or null on error.
195
+	 */
196
+	public function getDb()
197
+	{
198
+		if ( $this->trapDB != null ) return $this->trapDB;
199 199
         
200 200
         
201
-        $dbresource=$this->trapController->Config()->get('config', 'database');
201
+		$dbresource=$this->trapController->Config()->get('config', 'database');
202 202
         
203
-        if ( ! $dbresource )
204
-        {
205
-            $this->trapController->redirectNow('trapdirector/settings?dberror=1');
206
-            return null;
207
-        }
203
+		if ( ! $dbresource )
204
+		{
205
+			$this->trapController->redirectNow('trapdirector/settings?dberror=1');
206
+			return null;
207
+		}
208 208
 
209
-        try {
210
-            $this->trapDB = $this->getDbByName($dbresource,false,true);
211
-        } catch (DBException $e) {
212
-            return null; // Should not happen as test = false
213
-        }
209
+		try {
210
+			$this->trapDB = $this->getDbByName($dbresource,false,true);
211
+		} catch (DBException $e) {
212
+			return null; // Should not happen as test = false
213
+		}
214 214
         
215
-        //$this->trapDB->getConnection();
215
+		//$this->trapDB->getConnection();
216 216
         
217
-        return $this->trapDB;
218
-    }
217
+		return $this->trapDB;
218
+	}
219 219
 
220
-    /**
221
-     * Get Zend adapter of DB.
222
-     * @return \Zend_Db_Adapter_Abstract|null
223
-     */
224
-    public function getDbConn()
225
-    {
226
-        if ($this->getDb() == null) return null;
227
-        return $this->getDb()->getDbAdapter();
220
+	/**
221
+	 * Get Zend adapter of DB.
222
+	 * @return \Zend_Db_Adapter_Abstract|null
223
+	 */
224
+	public function getDbConn()
225
+	{
226
+		if ($this->getDb() == null) return null;
227
+		return $this->getDb()->getDbAdapter();
228 228
 //        return $this->getDb()->getConnection();
229
-    }
229
+	}
230 230
     
231
-    /**
232
-     * Test Trap database
233
-     * @param boolean $test
234
-     * @throws DBException on error.
235
-     * @return \Zend_Db_Adapter_Abstract|array|null : if test=false, returns DB connexion, else array(error_num,message) or null on error.
236
-     */
237
-    public function testGetDb()
238
-    {       
239
-        $dbresource=$this->trapController->Config()->get('config', 'database');
231
+	/**
232
+	 * Test Trap database
233
+	 * @param boolean $test
234
+	 * @throws DBException on error.
235
+	 * @return \Zend_Db_Adapter_Abstract|array|null : if test=false, returns DB connexion, else array(error_num,message) or null on error.
236
+	 */
237
+	public function testGetDb()
238
+	{       
239
+		$dbresource=$this->trapController->Config()->get('config', 'database');
240 240
         
241
-        if ( ! $dbresource )
242
-        {
243
-                throw new DBException(array(1,''));
244
-        }
241
+		if ( ! $dbresource )
242
+		{
243
+				throw new DBException(array(1,''));
244
+		}
245 245
         
246
-        $this->trapDB = $this->getDbByName($dbresource,true,true);       
247
-        return;
248
-    }
246
+		$this->trapDB = $this->getDbByName($dbresource,true,true);       
247
+		return;
248
+	}
249 249
     
250 250
 
251
-    /**
252
-     * Get IDO Database
253
-     * @return \Zend_Db_Adapter_Abstract|NULL  returns DB connexion or null on error.
254
-     */
255
-    public function getIdoDb()
256
-    {
257
-        if ( $this->idoDB != null ) return $this->idoDB;
258
-        // TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
259
-        $dbresource=$this->trapController->Config()->get('config', 'IDOdatabase');;
251
+	/**
252
+	 * Get IDO Database
253
+	 * @return \Zend_Db_Adapter_Abstract|NULL  returns DB connexion or null on error.
254
+	 */
255
+	public function getIdoDb()
256
+	{
257
+		if ( $this->idoDB != null ) return $this->idoDB;
258
+		// TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
259
+		$dbresource=$this->trapController->Config()->get('config', 'IDOdatabase');;
260 260
         
261
-        if ( ! $dbresource )
262
-        {
263
-            $this->trapController->redirectNow('trapdirector/settings?idodberror=1');
264
-            return null;
265
-        }
261
+		if ( ! $dbresource )
262
+		{
263
+			$this->trapController->redirectNow('trapdirector/settings?idodberror=1');
264
+			return null;
265
+		}
266 266
         
267
-        try
268
-        {
269
-            $dbconn = IcingaDbConnection::fromResourceName($dbresource);
270
-        }
271
-        catch (Exception $e)
272
-        {
273
-            $this->trapController->redirectNow('trapdirector/settings?idodberror=2');
274
-            return null;
275
-        }
267
+		try
268
+		{
269
+			$dbconn = IcingaDbConnection::fromResourceName($dbresource);
270
+		}
271
+		catch (Exception $e)
272
+		{
273
+			$this->trapController->redirectNow('trapdirector/settings?idodberror=2');
274
+			return null;
275
+		}
276 276
 
277
-        $this->idoDB = $dbconn;
278
-        return $this->idoDB;
279
-    }
277
+		$this->idoDB = $dbconn;
278
+		return $this->idoDB;
279
+	}
280 280
 
281 281
 
282
-    /**
283
-     * Get Zend adapter of DB.
284
-     * @return \Zend_Db_Adapter_Abstract|null
285
-     */
286
-    public function getIdoDbConn()
287
-    {
288
-        if ($this->getIdoDb() == null) return null;
289
-        return $this->getIdoDb()->getConnection();
290
-    }
282
+	/**
283
+	 * Get Zend adapter of DB.
284
+	 * @return \Zend_Db_Adapter_Abstract|null
285
+	 */
286
+	public function getIdoDbConn()
287
+	{
288
+		if ($this->getIdoDb() == null) return null;
289
+		return $this->getIdoDb()->getConnection();
290
+	}
291 291
     
292
-    /**
293
-     * Get IDO Database
294
-     * @param boolean $test
295
-     * @throws DBException on error
296
-     */
297
-    public function testGetIdoDb()
298
-    {
299
-        // TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
300
-        $dbresource=$this->trapController->Config()->get('config', 'IDOdatabase');;
292
+	/**
293
+	 * Get IDO Database
294
+	 * @param boolean $test
295
+	 * @throws DBException on error
296
+	 */
297
+	public function testGetIdoDb()
298
+	{
299
+		// TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
300
+		$dbresource=$this->trapController->Config()->get('config', 'IDOdatabase');;
301 301
         
302
-        if ( ! $dbresource )
303
-        {
304
-            throw new DBException(array(1,'No database in config.ini'));
305
-        }
302
+		if ( ! $dbresource )
303
+		{
304
+			throw new DBException(array(1,'No database in config.ini'));
305
+		}
306 306
         
307
-        try
308
-        {
309
-            $dbconn = IcingaDbConnection::fromResourceName($dbresource);
310
-        }
311
-        catch (Exception $e)
312
-        {
313
-            throw new DBException( array(2,"Database $dbresource does not exists in IcingaWeb2") );
314
-        }
307
+		try
308
+		{
309
+			$dbconn = IcingaDbConnection::fromResourceName($dbresource);
310
+		}
311
+		catch (Exception $e)
312
+		{
313
+			throw new DBException( array(2,"Database $dbresource does not exists in IcingaWeb2") );
314
+		}
315 315
                
316
-        try
317
-        {
318
-            $query = $dbconn->select()
319
-            ->from('icinga_dbversion',array('version'));
320
-            $version=$dbconn->fetchRow($query);
321
-            if ( ($version == null) || ! property_exists($version,'version') )
322
-            {
323
-                throw new DBException( array(4,"$dbresource does not look like an IDO database"));
324
-            }
325
-        }
326
-        catch (Exception $e)
327
-        {
328
-            throw new DBException( array(3,"Error connecting to $dbresource : " . $e->getMessage()));
329
-        }
316
+		try
317
+		{
318
+			$query = $dbconn->select()
319
+			->from('icinga_dbversion',array('version'));
320
+			$version=$dbconn->fetchRow($query);
321
+			if ( ($version == null) || ! property_exists($version,'version') )
322
+			{
323
+				throw new DBException( array(4,"$dbresource does not look like an IDO database"));
324
+			}
325
+		}
326
+		catch (Exception $e)
327
+		{
328
+			throw new DBException( array(3,"Error connecting to $dbresource : " . $e->getMessage()));
329
+		}
330 330
         
331
-        return;
332
-    }
331
+		return;
332
+	}
333 333
     
334 334
 }
Please login to merge, or discard this patch.
Braces   +18 added lines, -16 removed lines patch added patch discarded remove patch
@@ -126,8 +126,7 @@  discard block
 block discarded – undo
126 126
                 $this->trapController->redirectNow('trapdirector/settings?dberror=5');
127 127
                 return false;
128 128
             }
129
-        }
130
-        catch (Exception $e)
129
+        } catch (Exception $e)
131 130
         {
132 131
             if ($test === true) 
133 132
             {
@@ -152,8 +151,7 @@  discard block
 block discarded – undo
152 151
         try
153 152
         {
154 153
             $dbconn = IcingaDbConnection::fromResourceName($DBname);
155
-        }
156
-        catch (Exception $e)
154
+        } catch (Exception $e)
157 155
         {
158 156
             if ($test === true) 
159 157
             {
@@ -167,8 +165,7 @@  discard block
 block discarded – undo
167 165
         {
168 166
             $dbAdapter=$dbconn->getDbAdapter();
169 167
             
170
-        }
171
-        catch (Exception $e)
168
+        } catch (Exception $e)
172 169
         {
173 170
             if ($test === true)
174 171
             {
@@ -195,7 +192,9 @@  discard block
 block discarded – undo
195 192
      */
196 193
     public function getDb()
197 194
     {
198
-        if ( $this->trapDB != null ) return $this->trapDB;
195
+        if ( $this->trapDB != null ) {
196
+        	return $this->trapDB;
197
+        }
199 198
         
200 199
         
201 200
         $dbresource=$this->trapController->Config()->get('config', 'database');
@@ -223,7 +222,9 @@  discard block
 block discarded – undo
223 222
      */
224 223
     public function getDbConn()
225 224
     {
226
-        if ($this->getDb() == null) return null;
225
+        if ($this->getDb() == null) {
226
+        	return null;
227
+        }
227 228
         return $this->getDb()->getDbAdapter();
228 229
 //        return $this->getDb()->getConnection();
229 230
     }
@@ -254,7 +255,9 @@  discard block
 block discarded – undo
254 255
      */
255 256
     public function getIdoDb()
256 257
     {
257
-        if ( $this->idoDB != null ) return $this->idoDB;
258
+        if ( $this->idoDB != null ) {
259
+        	return $this->idoDB;
260
+        }
258 261
         // TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
259 262
         $dbresource=$this->trapController->Config()->get('config', 'IDOdatabase');;
260 263
         
@@ -267,8 +270,7 @@  discard block
 block discarded – undo
267 270
         try
268 271
         {
269 272
             $dbconn = IcingaDbConnection::fromResourceName($dbresource);
270
-        }
271
-        catch (Exception $e)
273
+        } catch (Exception $e)
272 274
         {
273 275
             $this->trapController->redirectNow('trapdirector/settings?idodberror=2');
274 276
             return null;
@@ -285,7 +287,9 @@  discard block
 block discarded – undo
285 287
      */
286 288
     public function getIdoDbConn()
287 289
     {
288
-        if ($this->getIdoDb() == null) return null;
290
+        if ($this->getIdoDb() == null) {
291
+        	return null;
292
+        }
289 293
         return $this->getIdoDb()->getConnection();
290 294
     }
291 295
     
@@ -307,8 +311,7 @@  discard block
 block discarded – undo
307 311
         try
308 312
         {
309 313
             $dbconn = IcingaDbConnection::fromResourceName($dbresource);
310
-        }
311
-        catch (Exception $e)
314
+        } catch (Exception $e)
312 315
         {
313 316
             throw new DBException( array(2,"Database $dbresource does not exists in IcingaWeb2") );
314 317
         }
@@ -322,8 +325,7 @@  discard block
 block discarded – undo
322 325
             {
323 326
                 throw new DBException( array(4,"$dbresource does not look like an IDO database"));
324 327
             }
325
-        }
326
-        catch (Exception $e)
328
+        } catch (Exception $e)
327 329
         {
328 330
             throw new DBException( array(3,"Error connecting to $dbresource : " . $e->getMessage()));
329 331
         }
Please login to merge, or discard this patch.
library/Trapdirector/Icinga2API.php 2 patches
Indentation   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -10,303 +10,303 @@
 block discarded – undo
10 10
 class Icinga2API extends IcingaApiBase
11 11
 {
12 12
     
13
-    /**
14
-     * Creates Icinga2API object
15
-     * 
16
-     * @param string $host host name or IP
17
-     * @param number $port API port
18
-     */
19
-    public function __construct($host, $port = 5665)
20
-    {
21
-        parent::__construct($host,$port);
22
-    }
23
-    /**
13
+	/**
14
+	 * Creates Icinga2API object
15
+	 * 
16
+	 * @param string $host host name or IP
17
+	 * @param number $port API port
18
+	 */
19
+	public function __construct($host, $port = 5665)
20
+	{
21
+		parent::__construct($host,$port);
22
+	}
23
+	/**
24 24
 
25 25
 /************ Host query ************/  
26 26
 
27
-    /**
28
-     * return array of host by filter
29
-     * @param string $hostfilter
30
-     * @throws Exception
31
-     * @return array objects : array('__name','name','display_name','id' (=__name), 'address', 'ip4' (=address), 'address6', 'ip6' (=address6)
32
-     */
33
-    public function getHostByFilter(string $hostfilter)
34
-    {
35
-        $hosts = $this->standardQuery(
36
-            'host',
37
-            $hostfilter,
38
-            //'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
39
-            array('__name','name','display_name','address','address6')
40
-            );
41
-        foreach ( array_keys($hosts) as $key )
42
-        {
43
-            $hosts[$key]->id = $hosts[$key]->__name;
44
-            $hosts[$key]->ip4 = $hosts[$key]->address;
45
-            $hosts[$key]->ip6 = $hosts[$key]->address6;
46
-        }
47
-        return $hosts;
48
-    }
27
+	/**
28
+	 * return array of host by filter
29
+	 * @param string $hostfilter
30
+	 * @throws Exception
31
+	 * @return array objects : array('__name','name','display_name','id' (=__name), 'address', 'ip4' (=address), 'address6', 'ip6' (=address6)
32
+	 */
33
+	public function getHostByFilter(string $hostfilter)
34
+	{
35
+		$hosts = $this->standardQuery(
36
+			'host',
37
+			$hostfilter,
38
+			//'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
39
+			array('__name','name','display_name','address','address6')
40
+			);
41
+		foreach ( array_keys($hosts) as $key )
42
+		{
43
+			$hosts[$key]->id = $hosts[$key]->__name;
44
+			$hosts[$key]->ip4 = $hosts[$key]->address;
45
+			$hosts[$key]->ip6 = $hosts[$key]->address6;
46
+		}
47
+		return $hosts;
48
+	}
49 49
     
50
-    /**
51
-     * return array of host by IP (4 or 6)
52
-     * @param string $ip
53
-     * @throws Exception
54
-     * @return array objects : array('__name','name','display_name')
55
-     */
56
-    public function getHostByIP(string $ip) 
57
-    {
58
-        return $this->getHostByFilter('match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6)');
59
-    }
50
+	/**
51
+	 * return array of host by IP (4 or 6)
52
+	 * @param string $ip
53
+	 * @throws Exception
54
+	 * @return array objects : array('__name','name','display_name')
55
+	 */
56
+	public function getHostByIP(string $ip) 
57
+	{
58
+		return $this->getHostByFilter('match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6)');
59
+	}
60 60
 
61 61
     
62
-    /**
63
-     * Get host(s) by name in API
64
-     * @param string $name
65
-     * @return array|NULL[] : see getHostByIP
66
-     */
67
-    public function getHostByName(string $name)
68
-    {
69
-        return $this->getHostByFilter('match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name)');
70
-    }
62
+	/**
63
+	 * Get host(s) by name in API
64
+	 * @param string $name
65
+	 * @return array|NULL[] : see getHostByIP
66
+	 */
67
+	public function getHostByName(string $name)
68
+	{
69
+		return $this->getHostByFilter('match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name)');
70
+	}
71 71
 
72
-    /**
73
-     * Get host(s) by name in API
74
-     * @param string $name
75
-     * @return array|NULL[] : see getHostByIP
76
-     */
77
-    public function getHostByNameOrIP(string $name)
78
-    {
79
-        return $this->getHostByFilter( 
80
-            'match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name) || match("*' . $name . '*",host.address) || match("*' . $name . '*",host.address6)');
81
-    }
72
+	/**
73
+	 * Get host(s) by name in API
74
+	 * @param string $name
75
+	 * @return array|NULL[] : see getHostByIP
76
+	 */
77
+	public function getHostByNameOrIP(string $name)
78
+	{
79
+		return $this->getHostByFilter( 
80
+			'match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name) || match("*' . $name . '*",host.address) || match("*' . $name . '*",host.address6)');
81
+	}
82 82
     
83
-    public function getHostInfoByID(string $name)
84
-    {
85
-        $host = $this->getHostByFilter(
86
-            'host.__name=="'. $name .'"');
87
-        if (isset($host[0]))
88
-            return $host[0];
89
-        else
90
-            return NULL;
91
-    }
83
+	public function getHostInfoByID(string $name)
84
+	{
85
+		$host = $this->getHostByFilter(
86
+			'host.__name=="'. $name .'"');
87
+		if (isset($host[0]))
88
+			return $host[0];
89
+		else
90
+			return NULL;
91
+	}
92 92
  
93
-    /**
94
-     * Get all host and IP from hostgroup
95
-     * @param string $hostGroup
96
-     * @throws Exception
97
-     * @return array : attributes : address, address6, name
98
-     */
99
-    public function getHostsIPByHostGroup($hostGroup)
100
-    {        
101
-        return $this->standardQuery(
102
-            'host', 
103
-            '"' . $hostGroup . '" in host.groups',
104
-            array('address','address6','name')
93
+	/**
94
+	 * Get all host and IP from hostgroup
95
+	 * @param string $hostGroup
96
+	 * @throws Exception
97
+	 * @return array : attributes : address, address6, name
98
+	 */
99
+	public function getHostsIPByHostGroup($hostGroup)
100
+	{        
101
+		return $this->standardQuery(
102
+			'host', 
103
+			'"' . $hostGroup . '" in host.groups',
104
+			array('address','address6','name')
105 105
                 
106
-        );
107
-    }
106
+		);
107
+	}
108 108
 
109 109
 
110
-    /** Get services from host in API
111
-     *	
112
-     *  @throws Exception
113
-     *	@param $id string host name
114
-     *  @param bool $active
115
-     *  @param bool $passive_svc
116
-     *	@return array display_name (of service), service_object_id
117
-     */
118
-    public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
119
-    {
120
-        $filter = 'match("' . $id . '!*", service.__name)';
121
-        if ($active === TRUE)
122
-        {
123
-            $filter .= ' && service.active==true';
124
-        }
125
-        if ($passive_svc === TRUE)
126
-        {
127
-            $filter .= ' && service.enable_passive_checks==true';
128
-        }
129
-        $services =  $this->standardQuery(
130
-            'service',
131
-            $filter,
132
-            array('__name','name','display_name','active')
133
-            );
110
+	/** Get services from host in API
111
+	 *	
112
+	 *  @throws Exception
113
+	 *	@param $id string host name
114
+	 *  @param bool $active
115
+	 *  @param bool $passive_svc
116
+	 *	@return array display_name (of service), service_object_id
117
+	 */
118
+	public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
119
+	{
120
+		$filter = 'match("' . $id . '!*", service.__name)';
121
+		if ($active === TRUE)
122
+		{
123
+			$filter .= ' && service.active==true';
124
+		}
125
+		if ($passive_svc === TRUE)
126
+		{
127
+			$filter .= ' && service.enable_passive_checks==true';
128
+		}
129
+		$services =  $this->standardQuery(
130
+			'service',
131
+			$filter,
132
+			array('__name','name','display_name','active')
133
+			);
134 134
         
135
-        foreach ( array_keys($services) as $key )
136
-        {
137
-            $services[$key]->id = $services[$key]->__name;
138
-        }
135
+		foreach ( array_keys($services) as $key )
136
+		{
137
+			$services[$key]->id = $services[$key]->__name;
138
+		}
139 139
         
140
-        return $services;
140
+		return $services;
141 141
         
142
-    }
142
+	}
143 143
 
144 144
 /************  Host group query ************/    
145
-    /**
146
-     * return array of host by IP (4 or 6) or name
147
-     * @param string $group Host group name
148
-     * @throws Exception
149
-     * @return array objects : array('name','display_name')
150
-     */
151
-    public function getHostsByGroup(string $group)
152
-    {
153
-         return $this->standardQuery(
154
-            'host',
155
-            '"' . $group . '" in host.groups',
156
-            array('name','display_name')
157
-            );
158
-    }
145
+	/**
146
+	 * return array of host by IP (4 or 6) or name
147
+	 * @param string $group Host group name
148
+	 * @throws Exception
149
+	 * @return array objects : array('name','display_name')
150
+	 */
151
+	public function getHostsByGroup(string $group)
152
+	{
153
+		 return $this->standardQuery(
154
+			'host',
155
+			'"' . $group . '" in host.groups',
156
+			array('name','display_name')
157
+			);
158
+	}
159 159
     
160
-    public function getServicesByHostGroupid(string $group)
161
-    {
162
-        $hostList = $this->getHostsByGroup($group);
163
-        //return $hostList;
164
-        $hostNum = count($hostList);
165
-        $serviceList=array();
166
-        foreach ($hostList as $curHost)
167
-        {
168
-            $services = $this->getServicesByHostid($curHost->name);
169
-            foreach ($services as $service)
170
-            {
171
-                //return $service;
172
-                if (! isset($serviceList[$service->name]))
173
-                {
174
-                    $serviceList[$service->name]=
175
-                        array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
176
-                }
177
-                else
178
-                {
179
-                    $serviceList[$service->name]['num']++;
180
-                }
181
-            }
182
-        }
183
-        $commonServices=array();
184
-        foreach ($serviceList as $key => $values)
185
-        {
186
-            if ($values['num'] >= $hostNum)
187
-            {
188
-                array_push($commonServices,array($key,$values['display_name']));
189
-            }
190
-        }
191
-        return $commonServices;
192
-    }
160
+	public function getServicesByHostGroupid(string $group)
161
+	{
162
+		$hostList = $this->getHostsByGroup($group);
163
+		//return $hostList;
164
+		$hostNum = count($hostList);
165
+		$serviceList=array();
166
+		foreach ($hostList as $curHost)
167
+		{
168
+			$services = $this->getServicesByHostid($curHost->name);
169
+			foreach ($services as $service)
170
+			{
171
+				//return $service;
172
+				if (! isset($serviceList[$service->name]))
173
+				{
174
+					$serviceList[$service->name]=
175
+						array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
176
+				}
177
+				else
178
+				{
179
+					$serviceList[$service->name]['num']++;
180
+				}
181
+			}
182
+		}
183
+		$commonServices=array();
184
+		foreach ($serviceList as $key => $values)
185
+		{
186
+			if ($values['num'] >= $hostNum)
187
+			{
188
+				array_push($commonServices,array($key,$values['display_name']));
189
+			}
190
+		}
191
+		return $commonServices;
192
+	}
193 193
  
194
-    /**
195
-     * Get all host and IP from hostgroup
196
-     * @param string $hostGroup
197
-     * @throws Exception
198
-     * @return array : attributes : address, address6, name
199
-     */
200
-    public function getHostGroupByName($name)
201
-    {
202
-        $hosts = $this->standardQuery(
203
-            'hostgroup',
204
-            'match("*' . $name . '*",hostgroup.name)',
205
-            array('__name','name','display_name')
194
+	/**
195
+	 * Get all host and IP from hostgroup
196
+	 * @param string $hostGroup
197
+	 * @throws Exception
198
+	 * @return array : attributes : address, address6, name
199
+	 */
200
+	public function getHostGroupByName($name)
201
+	{
202
+		$hosts = $this->standardQuery(
203
+			'hostgroup',
204
+			'match("*' . $name . '*",hostgroup.name)',
205
+			array('__name','name','display_name')
206 206
             
207
-            );
208
-        foreach ( array_keys($hosts) as $key )
209
-        {
210
-            $hosts[$key]->id = $hosts[$key]->__name;
211
-        }
212
-        return $hosts;
213
-    }
207
+			);
208
+		foreach ( array_keys($hosts) as $key )
209
+		{
210
+			$hosts[$key]->id = $hosts[$key]->__name;
211
+		}
212
+		return $hosts;
213
+	}
214 214
     
215
-    /**
216
-     * Get hostgroup by id (__name)
217
-     * @param string $hostGroup
218
-     * @throws Exception
219
-     * @return array : __name, name, display_name
220
-     */
221
-    public function getHostGroupById($name)
222
-    {
223
-        $hosts = $this->standardQuery(
224
-            'hostgroup',
225
-            'hostgroup.__name=="'. $name .'"',
226
-            array('__name','name','display_name')
215
+	/**
216
+	 * Get hostgroup by id (__name)
217
+	 * @param string $hostGroup
218
+	 * @throws Exception
219
+	 * @return array : __name, name, display_name
220
+	 */
221
+	public function getHostGroupById($name)
222
+	{
223
+		$hosts = $this->standardQuery(
224
+			'hostgroup',
225
+			'hostgroup.__name=="'. $name .'"',
226
+			array('__name','name','display_name')
227 227
             
228
-            );
229
-        $hosts[0]->id = $hosts[0]->__name;
230
-        return $hosts[0];
231
-    }
228
+			);
229
+		$hosts[0]->id = $hosts[0]->__name;
230
+		return $hosts[0];
231
+	}
232 232
     
233 233
 /****************   Service queries ************/
234
-    /** Get services object id by host name / service name
235
-     *	does not catch exceptions
236
-     *	@param $hostname string host name
237
-     *	@param $name string service name
238
-     *  @param bool $active : if true, return only active service
239
-     *  @param bool $passive_svc : if true, return only service accepting passive checks
240
-     *	@return array  service id
241
-     */
242
-    public function getServiceIDByName($hostname,$name,bool $active = TRUE, bool $passive_svc = TRUE)
243
-    {
244
-        $filter = 'service.__name=="' . $hostname . '!'. $name .'"';
245
-        if ($active === TRUE)
246
-        {
247
-            $filter .= ' && service.active==true';
248
-        }
249
-        if ($passive_svc === TRUE)
250
-        {
251
-            $filter .= ' && service.enable_passive_checks==true';
252
-        }
253
-        $services =  $this->standardQuery(
254
-            'service',
255
-            $filter,
256
-            array('__name','name','display_name','active','enable_passive_checks')
257
-            );
234
+	/** Get services object id by host name / service name
235
+	 *	does not catch exceptions
236
+	 *	@param $hostname string host name
237
+	 *	@param $name string service name
238
+	 *  @param bool $active : if true, return only active service
239
+	 *  @param bool $passive_svc : if true, return only service accepting passive checks
240
+	 *	@return array  service id
241
+	 */
242
+	public function getServiceIDByName($hostname,$name,bool $active = TRUE, bool $passive_svc = TRUE)
243
+	{
244
+		$filter = 'service.__name=="' . $hostname . '!'. $name .'"';
245
+		if ($active === TRUE)
246
+		{
247
+			$filter .= ' && service.active==true';
248
+		}
249
+		if ($passive_svc === TRUE)
250
+		{
251
+			$filter .= ' && service.enable_passive_checks==true';
252
+		}
253
+		$services =  $this->standardQuery(
254
+			'service',
255
+			$filter,
256
+			array('__name','name','display_name','active','enable_passive_checks')
257
+			);
258 258
         
259
-        foreach ( array_keys($services) as $key )
260
-        {
261
-            $services[$key]->id = $services[$key]->__name;
262
-        }
259
+		foreach ( array_keys($services) as $key )
260
+		{
261
+			$services[$key]->id = $services[$key]->__name;
262
+		}
263 263
         
264
-        return $services;
265
-    }
264
+		return $services;
265
+	}
266 266
  
267
-    /** Get services object by id (host!name)
268
-     *	does not catch exceptions
269
-     *	@param $name string service __name (host!name)
270
-     *	@return array  service id
271
-     */
272
-    public function getServiceById($name)
273
-    {
274
-        $filter = 'service.__name=="' .  $name .'"';
275
-        $services =  $this->standardQuery(
276
-            'service',
277
-            $filter,
278
-            array('__name','name','display_name','active','enable_passive_checks')
279
-            );
267
+	/** Get services object by id (host!name)
268
+	 *	does not catch exceptions
269
+	 *	@param $name string service __name (host!name)
270
+	 *	@return array  service id
271
+	 */
272
+	public function getServiceById($name)
273
+	{
274
+		$filter = 'service.__name=="' .  $name .'"';
275
+		$services =  $this->standardQuery(
276
+			'service',
277
+			$filter,
278
+			array('__name','name','display_name','active','enable_passive_checks')
279
+			);
280 280
         
281
-        foreach ( array_keys($services) as $key )
282
-        {
283
-            $services[$key]->id = $services[$key]->__name;
284
-        }
281
+		foreach ( array_keys($services) as $key )
282
+		{
283
+			$services[$key]->id = $services[$key]->__name;
284
+		}
285 285
         
286
-        return $services;
287
-    }
286
+		return $services;
287
+	}
288 288
 
289
-    /** Get services object by id (host!name)
290
-     *	does not catch exceptions
291
-     *	@param $name string service __name (host!name)
292
-     *	@return array  service id
293
-     */
294
-    public function getNOKService()
295
-    {
296
-        $filter = 'service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
-        $services =  $this->standardQuery(
298
-            'service',
299
-            $filter,
300
-            array('__name','name','last_check','host_name','state')
301
-            );
289
+	/** Get services object by id (host!name)
290
+	 *	does not catch exceptions
291
+	 *	@param $name string service __name (host!name)
292
+	 *	@return array  service id
293
+	 */
294
+	public function getNOKService()
295
+	{
296
+		$filter = 'service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
+		$services =  $this->standardQuery(
298
+			'service',
299
+			$filter,
300
+			array('__name','name','last_check','host_name','state')
301
+			);
302 302
         
303
-        foreach ( array_keys($services) as $key )
304
-        {
305
-            $services[$key]->id = $services[$key]->__name;
306
-        }
303
+		foreach ( array_keys($services) as $key )
304
+		{
305
+			$services[$key]->id = $services[$key]->__name;
306
+		}
307 307
         
308
-        return $services;
309
-    }
308
+		return $services;
309
+	}
310 310
     
311 311
     
312 312
 }
Please login to merge, or discard this patch.
Spacing   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -16,9 +16,9 @@  discard block
 block discarded – undo
16 16
      * @param string $host host name or IP
17 17
      * @param number $port API port
18 18
      */
19
-    public function __construct($host, $port = 5665)
19
+    public function __construct($host, $port=5665)
20 20
     {
21
-        parent::__construct($host,$port);
21
+        parent::__construct($host, $port);
22 22
     }
23 23
     /**
24 24
 
@@ -32,17 +32,17 @@  discard block
 block discarded – undo
32 32
      */
33 33
     public function getHostByFilter(string $hostfilter)
34 34
     {
35
-        $hosts = $this->standardQuery(
35
+        $hosts=$this->standardQuery(
36 36
             'host',
37 37
             $hostfilter,
38 38
             //'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
39
-            array('__name','name','display_name','address','address6')
39
+            array('__name', 'name', 'display_name', 'address', 'address6')
40 40
             );
41
-        foreach ( array_keys($hosts) as $key )
41
+        foreach (array_keys($hosts) as $key)
42 42
         {
43
-            $hosts[$key]->id = $hosts[$key]->__name;
44
-            $hosts[$key]->ip4 = $hosts[$key]->address;
45
-            $hosts[$key]->ip6 = $hosts[$key]->address6;
43
+            $hosts[$key]->id=$hosts[$key]->__name;
44
+            $hosts[$key]->ip4=$hosts[$key]->address;
45
+            $hosts[$key]->ip6=$hosts[$key]->address6;
46 46
         }
47 47
         return $hosts;
48 48
     }
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
      */
56 56
     public function getHostByIP(string $ip) 
57 57
     {
58
-        return $this->getHostByFilter('match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6)');
58
+        return $this->getHostByFilter('match("*'.$ip.'*",host.address) || match("*'.$ip.'*",host.address6)');
59 59
     }
60 60
 
61 61
     
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
      */
67 67
     public function getHostByName(string $name)
68 68
     {
69
-        return $this->getHostByFilter('match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name)');
69
+        return $this->getHostByFilter('match("*'.$name.'*",host.name) || match("*'.$name.'*",host.display_name)');
70 70
     }
71 71
 
72 72
     /**
@@ -77,13 +77,13 @@  discard block
 block discarded – undo
77 77
     public function getHostByNameOrIP(string $name)
78 78
     {
79 79
         return $this->getHostByFilter( 
80
-            'match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name) || match("*' . $name . '*",host.address) || match("*' . $name . '*",host.address6)');
80
+            'match("*'.$name.'*",host.name) || match("*'.$name.'*",host.display_name) || match("*'.$name.'*",host.address) || match("*'.$name.'*",host.address6)');
81 81
     }
82 82
     
83 83
     public function getHostInfoByID(string $name)
84 84
     {
85
-        $host = $this->getHostByFilter(
86
-            'host.__name=="'. $name .'"');
85
+        $host=$this->getHostByFilter(
86
+            'host.__name=="'.$name.'"');
87 87
         if (isset($host[0]))
88 88
             return $host[0];
89 89
         else
@@ -100,8 +100,8 @@  discard block
 block discarded – undo
100 100
     {        
101 101
         return $this->standardQuery(
102 102
             'host', 
103
-            '"' . $hostGroup . '" in host.groups',
104
-            array('address','address6','name')
103
+            '"'.$hostGroup.'" in host.groups',
104
+            array('address', 'address6', 'name')
105 105
                 
106 106
         );
107 107
     }
@@ -115,26 +115,26 @@  discard block
 block discarded – undo
115 115
      *  @param bool $passive_svc
116 116
      *	@return array display_name (of service), service_object_id
117 117
      */
118
-    public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
118
+    public function getServicesByHostid(string $id, bool $active=TRUE, bool $passive_svc=TRUE)
119 119
     {
120
-        $filter = 'match("' . $id . '!*", service.__name)';
120
+        $filter='match("'.$id.'!*", service.__name)';
121 121
         if ($active === TRUE)
122 122
         {
123
-            $filter .= ' && service.active==true';
123
+            $filter.=' && service.active==true';
124 124
         }
125 125
         if ($passive_svc === TRUE)
126 126
         {
127
-            $filter .= ' && service.enable_passive_checks==true';
127
+            $filter.=' && service.enable_passive_checks==true';
128 128
         }
129
-        $services =  $this->standardQuery(
129
+        $services=$this->standardQuery(
130 130
             'service',
131 131
             $filter,
132
-            array('__name','name','display_name','active')
132
+            array('__name', 'name', 'display_name', 'active')
133 133
             );
134 134
         
135
-        foreach ( array_keys($services) as $key )
135
+        foreach (array_keys($services) as $key)
136 136
         {
137
-            $services[$key]->id = $services[$key]->__name;
137
+            $services[$key]->id=$services[$key]->__name;
138 138
         }
139 139
         
140 140
         return $services;
@@ -152,27 +152,27 @@  discard block
 block discarded – undo
152 152
     {
153 153
          return $this->standardQuery(
154 154
             'host',
155
-            '"' . $group . '" in host.groups',
156
-            array('name','display_name')
155
+            '"'.$group.'" in host.groups',
156
+            array('name', 'display_name')
157 157
             );
158 158
     }
159 159
     
160 160
     public function getServicesByHostGroupid(string $group)
161 161
     {
162
-        $hostList = $this->getHostsByGroup($group);
162
+        $hostList=$this->getHostsByGroup($group);
163 163
         //return $hostList;
164
-        $hostNum = count($hostList);
164
+        $hostNum=count($hostList);
165 165
         $serviceList=array();
166 166
         foreach ($hostList as $curHost)
167 167
         {
168
-            $services = $this->getServicesByHostid($curHost->name);
168
+            $services=$this->getServicesByHostid($curHost->name);
169 169
             foreach ($services as $service)
170 170
             {
171 171
                 //return $service;
172
-                if (! isset($serviceList[$service->name]))
172
+                if (!isset($serviceList[$service->name]))
173 173
                 {
174 174
                     $serviceList[$service->name]=
175
-                        array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
175
+                        array('num'=> 1, '__name' => $service->__name, 'display_name' => $service->display_name);
176 176
                 }
177 177
                 else
178 178
                 {
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
         {
186 186
             if ($values['num'] >= $hostNum)
187 187
             {
188
-                array_push($commonServices,array($key,$values['display_name']));
188
+                array_push($commonServices, array($key, $values['display_name']));
189 189
             }
190 190
         }
191 191
         return $commonServices;
@@ -199,15 +199,15 @@  discard block
 block discarded – undo
199 199
      */
200 200
     public function getHostGroupByName($name)
201 201
     {
202
-        $hosts = $this->standardQuery(
202
+        $hosts=$this->standardQuery(
203 203
             'hostgroup',
204
-            'match("*' . $name . '*",hostgroup.name)',
205
-            array('__name','name','display_name')
204
+            'match("*'.$name.'*",hostgroup.name)',
205
+            array('__name', 'name', 'display_name')
206 206
             
207 207
             );
208
-        foreach ( array_keys($hosts) as $key )
208
+        foreach (array_keys($hosts) as $key)
209 209
         {
210
-            $hosts[$key]->id = $hosts[$key]->__name;
210
+            $hosts[$key]->id=$hosts[$key]->__name;
211 211
         }
212 212
         return $hosts;
213 213
     }
@@ -220,13 +220,13 @@  discard block
 block discarded – undo
220 220
      */
221 221
     public function getHostGroupById($name)
222 222
     {
223
-        $hosts = $this->standardQuery(
223
+        $hosts=$this->standardQuery(
224 224
             'hostgroup',
225
-            'hostgroup.__name=="'. $name .'"',
226
-            array('__name','name','display_name')
225
+            'hostgroup.__name=="'.$name.'"',
226
+            array('__name', 'name', 'display_name')
227 227
             
228 228
             );
229
-        $hosts[0]->id = $hosts[0]->__name;
229
+        $hosts[0]->id=$hosts[0]->__name;
230 230
         return $hosts[0];
231 231
     }
232 232
     
@@ -239,26 +239,26 @@  discard block
 block discarded – undo
239 239
      *  @param bool $passive_svc : if true, return only service accepting passive checks
240 240
      *	@return array  service id
241 241
      */
242
-    public function getServiceIDByName($hostname,$name,bool $active = TRUE, bool $passive_svc = TRUE)
242
+    public function getServiceIDByName($hostname, $name, bool $active=TRUE, bool $passive_svc=TRUE)
243 243
     {
244
-        $filter = 'service.__name=="' . $hostname . '!'. $name .'"';
244
+        $filter='service.__name=="'.$hostname.'!'.$name.'"';
245 245
         if ($active === TRUE)
246 246
         {
247
-            $filter .= ' && service.active==true';
247
+            $filter.=' && service.active==true';
248 248
         }
249 249
         if ($passive_svc === TRUE)
250 250
         {
251
-            $filter .= ' && service.enable_passive_checks==true';
251
+            $filter.=' && service.enable_passive_checks==true';
252 252
         }
253
-        $services =  $this->standardQuery(
253
+        $services=$this->standardQuery(
254 254
             'service',
255 255
             $filter,
256
-            array('__name','name','display_name','active','enable_passive_checks')
256
+            array('__name', 'name', 'display_name', 'active', 'enable_passive_checks')
257 257
             );
258 258
         
259
-        foreach ( array_keys($services) as $key )
259
+        foreach (array_keys($services) as $key)
260 260
         {
261
-            $services[$key]->id = $services[$key]->__name;
261
+            $services[$key]->id=$services[$key]->__name;
262 262
         }
263 263
         
264 264
         return $services;
@@ -271,16 +271,16 @@  discard block
 block discarded – undo
271 271
      */
272 272
     public function getServiceById($name)
273 273
     {
274
-        $filter = 'service.__name=="' .  $name .'"';
275
-        $services =  $this->standardQuery(
274
+        $filter='service.__name=="'.$name.'"';
275
+        $services=$this->standardQuery(
276 276
             'service',
277 277
             $filter,
278
-            array('__name','name','display_name','active','enable_passive_checks')
278
+            array('__name', 'name', 'display_name', 'active', 'enable_passive_checks')
279 279
             );
280 280
         
281
-        foreach ( array_keys($services) as $key )
281
+        foreach (array_keys($services) as $key)
282 282
         {
283
-            $services[$key]->id = $services[$key]->__name;
283
+            $services[$key]->id=$services[$key]->__name;
284 284
         }
285 285
         
286 286
         return $services;
@@ -293,16 +293,16 @@  discard block
 block discarded – undo
293 293
      */
294 294
     public function getNOKService()
295 295
     {
296
-        $filter = 'service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
-        $services =  $this->standardQuery(
296
+        $filter='service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
+        $services=$this->standardQuery(
298 298
             'service',
299 299
             $filter,
300
-            array('__name','name','last_check','host_name','state')
300
+            array('__name', 'name', 'last_check', 'host_name', 'state')
301 301
             );
302 302
         
303
-        foreach ( array_keys($services) as $key )
303
+        foreach (array_keys($services) as $key)
304 304
         {
305
-            $services[$key]->id = $services[$key]->__name;
305
+            $services[$key]->id=$services[$key]->__name;
306 306
         }
307 307
         
308 308
         return $services;
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/MibDatabase.php 2 patches
Indentation   +154 added lines, -154 removed lines patch added patch discarded remove patch
@@ -12,184 +12,184 @@
 block discarded – undo
12 12
  */
13 13
 trait MibDatabase
14 14
 {   
15
-    /** @var array $oidDesc MUST be overide by calling class */
16
-    //protected $oidDesc;
15
+	/** @var array $oidDesc MUST be overide by calling class */
16
+	//protected $oidDesc;
17 17
     
18
-    /** @var array $dbOidIndex MUST be overide by calling class */
19
-    //protected $dbOidIndex;
18
+	/** @var array $dbOidIndex MUST be overide by calling class */
19
+	//protected $dbOidIndex;
20 20
     
21
-    /** @return \Trapdirector\Logging */
22
-    abstract public function getLogging();
21
+	/** @return \Trapdirector\Logging */
22
+	abstract public function getLogging();
23 23
     
24
-    /** @return \Trapdirector\Database */
25
-    abstract public function getTrapsDB();
24
+	/** @return \Trapdirector\Database */
25
+	abstract public function getTrapsDB();
26 26
 
27 27
     
28
-    /**
29
-     * Update or add an OID to database uses $this->dbOidIndex for mem cache
30
-     * and $this->oidDesc doe data
31
-     * @return number : 0=unchanged, 1 = changed, 2=created
32
-     */
33
-    public function update_oid()
34
-    {
35
-        $db_conn=$this->getTrapsDB()->db_connect_trap();
36
-        // Quote description.
37
-        $this->oidDesc['description']=$db_conn->quote($this->oidDesc['description']);
28
+	/**
29
+	 * Update or add an OID to database uses $this->dbOidIndex for mem cache
30
+	 * and $this->oidDesc doe data
31
+	 * @return number : 0=unchanged, 1 = changed, 2=created
32
+	 */
33
+	public function update_oid()
34
+	{
35
+		$db_conn=$this->getTrapsDB()->db_connect_trap();
36
+		// Quote description.
37
+		$this->oidDesc['description']=$db_conn->quote($this->oidDesc['description']);
38 38
         
39
-        if (isset($this->dbOidIndex[$this->oidDesc['oid']]))
40
-        { // oid exists in db, so update
41
-            return $this->update_oid_update();
42
-        }
43
-        // create new OID.
44
-        return $this->update_oid_create();
39
+		if (isset($this->dbOidIndex[$this->oidDesc['oid']]))
40
+		{ // oid exists in db, so update
41
+			return $this->update_oid_update();
42
+		}
43
+		// create new OID.
44
+		return $this->update_oid_create();
45 45
         
46
-    }
46
+	}
47 47
     
48
-    /**
49
-     * Update object in DB with object in dbOidIndex if name/mib/type has changed.
50
-     * @return number : 0=unchanged, 1 = changed, 2=created
51
-     */
52
-    private function update_oid_update()
53
-    {
48
+	/**
49
+	 * Update object in DB with object in dbOidIndex if name/mib/type has changed.
50
+	 * @return number : 0=unchanged, 1 = changed, 2=created
51
+	 */
52
+	private function update_oid_update()
53
+	{
54 54
         
55
-        $db_conn=$this->getTrapsDB()->db_connect_trap();
55
+		$db_conn=$this->getTrapsDB()->db_connect_trap();
56 56
         
57
-        if ($this->dbOidIndex[$this->oidDesc['oid']]['key'] == -1)
58
-        { // newly created.
59
-            return 0;
60
-        }
61
-        $oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
62
-        $dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
63
-        if ( $this->oidDesc['name'] != $dbOid['name'] ||
64
-            $this->oidDesc['mib'] != $dbOid['mib'] ||
65
-            $this->oidDesc['type'] !=$dbOid['type']
66
-            )
67
-        { // Do update
68
-            $sql='UPDATE '.$this->getTrapsDB()->dbPrefix.'mib_cache SET '.
69
-                'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'.
70
-                ', syntax = :syntax, type_enum = :type_enum, description = :description '.
71
-                ' WHERE id= :id';
72
-            $sqlQuery=$db_conn->prepare($sql);
57
+		if ($this->dbOidIndex[$this->oidDesc['oid']]['key'] == -1)
58
+		{ // newly created.
59
+			return 0;
60
+		}
61
+		$oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
62
+		$dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
63
+		if ( $this->oidDesc['name'] != $dbOid['name'] ||
64
+			$this->oidDesc['mib'] != $dbOid['mib'] ||
65
+			$this->oidDesc['type'] !=$dbOid['type']
66
+			)
67
+		{ // Do update
68
+			$sql='UPDATE '.$this->getTrapsDB()->dbPrefix.'mib_cache SET '.
69
+				'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'.
70
+				', syntax = :syntax, type_enum = :type_enum, description = :description '.
71
+				' WHERE id= :id';
72
+			$sqlQuery=$db_conn->prepare($sql);
73 73
             
74
-            $sqlParam=array(
75
-                ':name' => $this->oidDesc['name'],
76
-                ':type' => $this->oidDesc['type'],
77
-                ':mib' => $this->oidDesc['mib'],
78
-                ':tc' =>  $this->oidDesc['textconv']??'null',
79
-                ':display_hint' => $this->oidDesc['dispHint']??'null' ,
80
-                ':syntax' => $this->oidDesc['syntax']==null??'null',
81
-                ':type_enum' => $this->oidDesc['type_enum']??'null',
82
-                ':description' => $this->oidDesc['description']??'null',
83
-                ':id' => $this->dbOidIndex[$this->oidDesc['oid']]['id']
74
+			$sqlParam=array(
75
+				':name' => $this->oidDesc['name'],
76
+				':type' => $this->oidDesc['type'],
77
+				':mib' => $this->oidDesc['mib'],
78
+				':tc' =>  $this->oidDesc['textconv']??'null',
79
+				':display_hint' => $this->oidDesc['dispHint']??'null' ,
80
+				':syntax' => $this->oidDesc['syntax']==null??'null',
81
+				':type_enum' => $this->oidDesc['type_enum']??'null',
82
+				':description' => $this->oidDesc['description']??'null',
83
+				':id' => $this->dbOidIndex[$this->oidDesc['oid']]['id']
84 84
 //                ':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
85
-            );
85
+			);
86 86
             
87
-            if ($sqlQuery->execute($sqlParam) === false) {
88
-                $this->getLogging()->log('Error in query : ' . $sql,ERROR,'');
89
-            }
90
-            $this->getLogging()->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
91
-            return 1;
92
-        }
93
-        else
94
-        {
95
-            $this->getLogging()->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
96
-            return 0;
97
-        }
98
-    }
87
+			if ($sqlQuery->execute($sqlParam) === false) {
88
+				$this->getLogging()->log('Error in query : ' . $sql,ERROR,'');
89
+			}
90
+			$this->getLogging()->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
91
+			return 1;
92
+		}
93
+		else
94
+		{
95
+			$this->getLogging()->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
96
+			return 0;
97
+		}
98
+	}
99 99
 
100
-    /**
101
-     * Create object in DB with object in dbOidIndex
102
-     * @return number : 0=unchanged, 1 = changed, 2=created
103
-     */
104
-    private function update_oid_create()
105
-    {
106
-        // Insert data
100
+	/**
101
+	 * Create object in DB with object in dbOidIndex
102
+	 * @return number : 0=unchanged, 1 = changed, 2=created
103
+	 */
104
+	private function update_oid_create()
105
+	{
106
+		// Insert data
107 107
         
108
-        $db_conn=$this->getTrapsDB()->db_connect_trap();
109
-        $sql='INSERT INTO '.$this->getTrapsDB()->dbPrefix.'mib_cache '.
110
-            '(oid, name, type , mib, textual_convention, display_hint '.
111
-            ', syntax, type_enum , description ) ' .
112
-            'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
113
-            ', :syntax, :type_enum, :description )';
108
+		$db_conn=$this->getTrapsDB()->db_connect_trap();
109
+		$sql='INSERT INTO '.$this->getTrapsDB()->dbPrefix.'mib_cache '.
110
+			'(oid, name, type , mib, textual_convention, display_hint '.
111
+			', syntax, type_enum , description ) ' .
112
+			'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
113
+			', :syntax, :type_enum, :description )';
114 114
         
115
-        if ($this->getTrapsDB()->trapDBType == 'pgsql') $sql .= 'RETURNING id';
115
+		if ($this->getTrapsDB()->trapDBType == 'pgsql') $sql .= 'RETURNING id';
116 116
         
117
-        $sqlQuery=$db_conn->prepare($sql);
117
+		$sqlQuery=$db_conn->prepare($sql);
118 118
         
119
-        $sqlParam=array(
120
-            ':oid' => $this->oidDesc['oid'],
121
-            ':name' => $this->oidDesc['name'],
122
-            ':type' => $this->oidDesc['type'],
123
-            ':mib' => $this->oidDesc['mib'],
124
-            ':tc' =>  $this->oidDesc['textconv']??'null',
125
-            ':display_hint' => $this->oidDesc['dispHint']??'null',
126
-            ':syntax' => $this->oidDesc['syntax']??'null',
127
-            ':type_enum' => $this->oidDesc['type_enum']??'null',
128
-            ':description' => $this->oidDesc['description']??'null'
129
-        );
119
+		$sqlParam=array(
120
+			':oid' => $this->oidDesc['oid'],
121
+			':name' => $this->oidDesc['name'],
122
+			':type' => $this->oidDesc['type'],
123
+			':mib' => $this->oidDesc['mib'],
124
+			':tc' =>  $this->oidDesc['textconv']??'null',
125
+			':display_hint' => $this->oidDesc['dispHint']??'null',
126
+			':syntax' => $this->oidDesc['syntax']??'null',
127
+			':type_enum' => $this->oidDesc['type_enum']??'null',
128
+			':description' => $this->oidDesc['description']??'null'
129
+		);
130 130
         
131
-        if ($sqlQuery->execute($sqlParam) === false) {
132
-            $this->getLogging()->log('Error in query : ' . $sql,1,'');
133
-        }
131
+		if ($sqlQuery->execute($sqlParam) === false) {
132
+			$this->getLogging()->log('Error in query : ' . $sql,1,'');
133
+		}
134 134
         
135
-        switch ($this->getTrapsDB()->trapDBType)
136
-        {
137
-            case 'pgsql':
138
-                // Get last id to insert oid/values in secondary table
139
-                if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
140
-                    $this->getLogging()->log('Error getting id - pgsql - ',1,'');
141
-                }
142
-                if (! isset($inserted_id_ret['id'])) {
143
-                    $this->getLogging()->log('Error getting id - pgsql - empty.',ERROR);
144
-                    return 0;
145
-                }
146
-                $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
147
-                break;
148
-            case 'mysql':
149
-                // Get last id to insert oid/values in secondary table
150
-                $sql='SELECT LAST_INSERT_ID();';
151
-                if (($ret_code=$db_conn->query($sql)) === false) {
152
-                    $this->getLogging()->log('Erreur getting id - mysql - ',ERROR);
153
-                    return 0;
154
-                }
135
+		switch ($this->getTrapsDB()->trapDBType)
136
+		{
137
+			case 'pgsql':
138
+				// Get last id to insert oid/values in secondary table
139
+				if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
140
+					$this->getLogging()->log('Error getting id - pgsql - ',1,'');
141
+				}
142
+				if (! isset($inserted_id_ret['id'])) {
143
+					$this->getLogging()->log('Error getting id - pgsql - empty.',ERROR);
144
+					return 0;
145
+				}
146
+				$this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
147
+				break;
148
+			case 'mysql':
149
+				// Get last id to insert oid/values in secondary table
150
+				$sql='SELECT LAST_INSERT_ID();';
151
+				if (($ret_code=$db_conn->query($sql)) === false) {
152
+					$this->getLogging()->log('Erreur getting id - mysql - ',ERROR);
153
+					return 0;
154
+				}
155 155
                 
156
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
157
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
158
-                $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
159
-                break;
160
-            default:
161
-                $this->getLogging()->log('Error SQL type Unknown : '.$this->getTrapsDB()->trapDBType,ERROR);
162
-                return 0;
163
-        }
156
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
157
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
158
+				$this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
159
+				break;
160
+			default:
161
+				$this->getLogging()->log('Error SQL type Unknown : '.$this->getTrapsDB()->trapDBType,ERROR);
162
+				return 0;
163
+		}
164 164
         
165
-        // Set as newly created.
166
-        $this->dbOidIndex[$this->oidDesc['oid']]['key']=-1;
167
-        return 2;
168
-    }
165
+		// Set as newly created.
166
+		$this->dbOidIndex[$this->oidDesc['oid']]['key']=-1;
167
+		return 2;
168
+	}
169 169
 
170
-    /**
171
-     * get all objects for a trap.
172
-     * @param integer $trapId
173
-     * @return array : array of cached objects
174
-     */
175
-    private function cache_db_objects($trapId)
176
-    {
177
-        $dbObjects=array(); // cache of objects for trap in db
178
-        $db_conn=$this->getTrapsDB()->db_connect_trap();
179
-        // Get all objects
180
-        $sql='SELECT * FROM '.$this->getTrapsDB()->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
181
-        $this->getLogging()->log('SQL query get all traps: '.$sql,DEBUG );
182
-        if (($ret_code=$db_conn->query($sql)) === false) {
183
-            $this->getLogging()->log('No result in query : ' . $sql,1,'');
184
-        }
185
-        $dbObjectsRaw=$ret_code->fetchAll();
170
+	/**
171
+	 * get all objects for a trap.
172
+	 * @param integer $trapId
173
+	 * @return array : array of cached objects
174
+	 */
175
+	private function cache_db_objects($trapId)
176
+	{
177
+		$dbObjects=array(); // cache of objects for trap in db
178
+		$db_conn=$this->getTrapsDB()->db_connect_trap();
179
+		// Get all objects
180
+		$sql='SELECT * FROM '.$this->getTrapsDB()->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
181
+		$this->getLogging()->log('SQL query get all traps: '.$sql,DEBUG );
182
+		if (($ret_code=$db_conn->query($sql)) === false) {
183
+			$this->getLogging()->log('No result in query : ' . $sql,1,'');
184
+		}
185
+		$dbObjectsRaw=$ret_code->fetchAll();
186 186
         
187
-        foreach ($dbObjectsRaw as $val)
188
-        {
189
-            $dbObjects[$val['object_id']]=1;
190
-        }
191
-        return $dbObjects;
192
-    }
187
+		foreach ($dbObjectsRaw as $val)
188
+		{
189
+			$dbObjects[$val['object_id']]=1;
190
+		}
191
+		return $dbObjects;
192
+	}
193 193
     
194 194
 
195 195
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -60,9 +60,9 @@  discard block
 block discarded – undo
60 60
         }
61 61
         $oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
62 62
         $dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
63
-        if ( $this->oidDesc['name'] != $dbOid['name'] ||
63
+        if ($this->oidDesc['name'] != $dbOid['name'] ||
64 64
             $this->oidDesc['mib'] != $dbOid['mib'] ||
65
-            $this->oidDesc['type'] !=$dbOid['type']
65
+            $this->oidDesc['type'] != $dbOid['type']
66 66
             )
67 67
         { // Do update
68 68
             $sql='UPDATE '.$this->getTrapsDB()->dbPrefix.'mib_cache SET '.
@@ -75,24 +75,24 @@  discard block
 block discarded – undo
75 75
                 ':name' => $this->oidDesc['name'],
76 76
                 ':type' => $this->oidDesc['type'],
77 77
                 ':mib' => $this->oidDesc['mib'],
78
-                ':tc' =>  $this->oidDesc['textconv']??'null',
79
-                ':display_hint' => $this->oidDesc['dispHint']??'null' ,
80
-                ':syntax' => $this->oidDesc['syntax']==null??'null',
81
-                ':type_enum' => $this->oidDesc['type_enum']??'null',
82
-                ':description' => $this->oidDesc['description']??'null',
78
+                ':tc' =>  $this->oidDesc['textconv'] ?? 'null',
79
+                ':display_hint' => $this->oidDesc['dispHint'] ?? 'null',
80
+                ':syntax' => $this->oidDesc['syntax'] == null ?? 'null',
81
+                ':type_enum' => $this->oidDesc['type_enum'] ?? 'null',
82
+                ':description' => $this->oidDesc['description'] ?? 'null',
83 83
                 ':id' => $this->dbOidIndex[$this->oidDesc['oid']]['id']
84 84
 //                ':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
85 85
             );
86 86
             
87 87
             if ($sqlQuery->execute($sqlParam) === false) {
88
-                $this->getLogging()->log('Error in query : ' . $sql,ERROR,'');
88
+                $this->getLogging()->log('Error in query : '.$sql, ERROR, '');
89 89
             }
90
-            $this->getLogging()->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
90
+            $this->getLogging()->log('Trap updated : '.$this->oidDesc['name'].' / OID : '.$this->oidDesc['oid'], DEBUG);
91 91
             return 1;
92 92
         }
93 93
         else
94 94
         {
95
-            $this->getLogging()->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
95
+            $this->getLogging()->log('Trap unchanged : '.$this->oidDesc['name'].' / OID : '.$this->oidDesc['oid'], DEBUG);
96 96
             return 0;
97 97
         }
98 98
     }
@@ -108,11 +108,11 @@  discard block
 block discarded – undo
108 108
         $db_conn=$this->getTrapsDB()->db_connect_trap();
109 109
         $sql='INSERT INTO '.$this->getTrapsDB()->dbPrefix.'mib_cache '.
110 110
             '(oid, name, type , mib, textual_convention, display_hint '.
111
-            ', syntax, type_enum , description ) ' .
111
+            ', syntax, type_enum , description ) '.
112 112
             'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
113 113
             ', :syntax, :type_enum, :description )';
114 114
         
115
-        if ($this->getTrapsDB()->trapDBType == 'pgsql') $sql .= 'RETURNING id';
115
+        if ($this->getTrapsDB()->trapDBType == 'pgsql') $sql.='RETURNING id';
116 116
         
117 117
         $sqlQuery=$db_conn->prepare($sql);
118 118
         
@@ -121,15 +121,15 @@  discard block
 block discarded – undo
121 121
             ':name' => $this->oidDesc['name'],
122 122
             ':type' => $this->oidDesc['type'],
123 123
             ':mib' => $this->oidDesc['mib'],
124
-            ':tc' =>  $this->oidDesc['textconv']??'null',
125
-            ':display_hint' => $this->oidDesc['dispHint']??'null',
126
-            ':syntax' => $this->oidDesc['syntax']??'null',
127
-            ':type_enum' => $this->oidDesc['type_enum']??'null',
128
-            ':description' => $this->oidDesc['description']??'null'
124
+            ':tc' =>  $this->oidDesc['textconv'] ?? 'null',
125
+            ':display_hint' => $this->oidDesc['dispHint'] ?? 'null',
126
+            ':syntax' => $this->oidDesc['syntax'] ?? 'null',
127
+            ':type_enum' => $this->oidDesc['type_enum'] ?? 'null',
128
+            ':description' => $this->oidDesc['description'] ?? 'null'
129 129
         );
130 130
         
131 131
         if ($sqlQuery->execute($sqlParam) === false) {
132
-            $this->getLogging()->log('Error in query : ' . $sql,1,'');
132
+            $this->getLogging()->log('Error in query : '.$sql, 1, '');
133 133
         }
134 134
         
135 135
         switch ($this->getTrapsDB()->trapDBType)
@@ -137,10 +137,10 @@  discard block
 block discarded – undo
137 137
             case 'pgsql':
138 138
                 // Get last id to insert oid/values in secondary table
139 139
                 if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
140
-                    $this->getLogging()->log('Error getting id - pgsql - ',1,'');
140
+                    $this->getLogging()->log('Error getting id - pgsql - ', 1, '');
141 141
                 }
142
-                if (! isset($inserted_id_ret['id'])) {
143
-                    $this->getLogging()->log('Error getting id - pgsql - empty.',ERROR);
142
+                if (!isset($inserted_id_ret['id'])) {
143
+                    $this->getLogging()->log('Error getting id - pgsql - empty.', ERROR);
144 144
                     return 0;
145 145
                 }
146 146
                 $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
@@ -149,16 +149,16 @@  discard block
 block discarded – undo
149 149
                 // Get last id to insert oid/values in secondary table
150 150
                 $sql='SELECT LAST_INSERT_ID();';
151 151
                 if (($ret_code=$db_conn->query($sql)) === false) {
152
-                    $this->getLogging()->log('Erreur getting id - mysql - ',ERROR);
152
+                    $this->getLogging()->log('Erreur getting id - mysql - ', ERROR);
153 153
                     return 0;
154 154
                 }
155 155
                 
156 156
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
157
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
157
+                if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
158 158
                 $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
159 159
                 break;
160 160
             default:
161
-                $this->getLogging()->log('Error SQL type Unknown : '.$this->getTrapsDB()->trapDBType,ERROR);
161
+                $this->getLogging()->log('Error SQL type Unknown : '.$this->getTrapsDB()->trapDBType, ERROR);
162 162
                 return 0;
163 163
         }
164 164
         
@@ -178,9 +178,9 @@  discard block
 block discarded – undo
178 178
         $db_conn=$this->getTrapsDB()->db_connect_trap();
179 179
         // Get all objects
180 180
         $sql='SELECT * FROM '.$this->getTrapsDB()->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
181
-        $this->getLogging()->log('SQL query get all traps: '.$sql,DEBUG );
181
+        $this->getLogging()->log('SQL query get all traps: '.$sql, DEBUG);
182 182
         if (($ret_code=$db_conn->query($sql)) === false) {
183
-            $this->getLogging()->log('No result in query : ' . $sql,1,'');
183
+            $this->getLogging()->log('No result in query : '.$sql, 1, '');
184 184
         }
185 185
         $dbObjectsRaw=$ret_code->fetchAll();
186 186
         
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/TrapConfig.php 3 patches
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -15,197 +15,197 @@
 block discarded – undo
15 15
 trait TrapConfig
16 16
 {
17 17
 
18
-    /** @return \Trapdirector\Logging   */
19
-    abstract public function getLogging();
20
-    /** @return \Trapdirector\TrapApi   */
21
-    abstract public function getTrapApi();
18
+	/** @return \Trapdirector\Logging   */
19
+	abstract public function getLogging();
20
+	/** @return \Trapdirector\TrapApi   */
21
+	abstract public function getTrapApi();
22 22
 
23
-    // TODO : Get default values from TrapModuleConfig 
24
-    /** @var bool	Use SnmpTrapAddess as source adress */
25
-    public $useSnmpTrapAddess=TRUE;
26
-    /** @var string	Special OID to get IP source address of trap emitter */
27
-    public $snmpTrapAddressOID='.1.3.6.1.6.3.18.1.3';
23
+	// TODO : Get default values from TrapModuleConfig 
24
+	/** @var bool	Use SnmpTrapAddess as source adress */
25
+	public $useSnmpTrapAddess=TRUE;
26
+	/** @var string	Special OID to get IP source address of trap emitter */
27
+	public $snmpTrapAddressOID='.1.3.6.1.6.3.18.1.3';
28 28
     
29
-    /**
30
-     * Get option from array of ini file, send message if empty
31
-     * @param string $option_array Array of ini file
32
-     * @param string $option_category category in ini file
33
-     * @param string $option_name name of option in category
34
-     * @param mixed $option_var variable to fill if found, left untouched if not found
35
-     * @param integer $log_level default 2 (warning)
36
-     * @param string $message warning message if not found
37
-     * @return boolean true if found, or false
38
-     */
39
-    protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = WARN, $message = null)
40
-    {
41
-        if (!isset($option_array[$option_category][$option_name]))
42
-        {
43
-            if ($message === null)
44
-            {
45
-                $message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
46
-            }
47
-            $this->getLogging()->log($message,$log_level);
48
-            return false;
49
-        }
50
-        else
51
-        {
52
-            $option_var=$option_array[$option_category][$option_name];
53
-            return true;
54
-        }
55
-    }
29
+	/**
30
+	 * Get option from array of ini file, send message if empty
31
+	 * @param string $option_array Array of ini file
32
+	 * @param string $option_category category in ini file
33
+	 * @param string $option_name name of option in category
34
+	 * @param mixed $option_var variable to fill if found, left untouched if not found
35
+	 * @param integer $log_level default 2 (warning)
36
+	 * @param string $message warning message if not found
37
+	 * @return boolean true if found, or false
38
+	 */
39
+	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = WARN, $message = null)
40
+	{
41
+		if (!isset($option_array[$option_category][$option_name]))
42
+		{
43
+			if ($message === null)
44
+			{
45
+				$message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
46
+			}
47
+			$this->getLogging()->log($message,$log_level);
48
+			return false;
49
+		}
50
+		else
51
+		{
52
+			$option_var=$option_array[$option_category][$option_name];
53
+			return true;
54
+		}
55
+	}
56 56
 
57
-    /**
58
-     * Get options in database
59
-     */
60
-    protected function getDatabaseOptions()
61
-    {
62
-        // Database options
63
-        if ($this->logSetup === false) // Only if logging was no setup in constructor
64
-        {
65
-            $this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
66
-            $this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
67
-            $this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
68
-        }
69
-        
70
-        $tmpVal = -1; // Get boolean coded in database as 1/0
71
-        $this->getDBConfigIfSet('use_SnmpTrapAddess', $tmpVal);
72
-        if ($tmpVal != -1) $this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
73
-        
74
-        $this->getDBConfigIfSet('SnmpTrapAddess_oid', $this->snmpTrapAddressOID); // Get oid then replace '.' with '\.' to use in regexp whrn reading traps
75
-        $this->snmpTrapAddressOID = preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
76
-    }
77
-        
78
-    /** Set $variable to value if $element found in database config table
79
-     * @param string $element
80
-     * @param string $variable
81
-     */
82
-    protected function getDBConfigIfSet($element,&$variable)
83
-    {
84
-        $value=$this->getDBConfig($element);
85
-        if ($value != null) $variable=$value;
86
-    }
57
+	/**
58
+	 * Get options in database
59
+	 */
60
+	protected function getDatabaseOptions()
61
+	{
62
+		// Database options
63
+		if ($this->logSetup === false) // Only if logging was no setup in constructor
64
+		{
65
+			$this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
66
+			$this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
67
+			$this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
68
+		}
69
+        
70
+		$tmpVal = -1; // Get boolean coded in database as 1/0
71
+		$this->getDBConfigIfSet('use_SnmpTrapAddess', $tmpVal);
72
+		if ($tmpVal != -1) $this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
73
+        
74
+		$this->getDBConfigIfSet('SnmpTrapAddess_oid', $this->snmpTrapAddressOID); // Get oid then replace '.' with '\.' to use in regexp whrn reading traps
75
+		$this->snmpTrapAddressOID = preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
76
+	}
77
+        
78
+	/** Set $variable to value if $element found in database config table
79
+	 * @param string $element
80
+	 * @param string $variable
81
+	 */
82
+	protected function getDBConfigIfSet($element,&$variable)
83
+	{
84
+		$value=$this->getDBConfig($element);
85
+		if ($value != null) $variable=$value;
86
+	}
87 87
     
88
-    /**
89
-     *   Get data from db_config
90
-     *	@param $element string name of param
91
-     *	@return mixed : value (or null)
92
-     */
93
-    protected function getDBConfig($element)  // TODO : put this in DB class
94
-    {
95
-        $db_conn=$this->trapsDB->db_connect_trap();
96
-        $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
97
-        if (($ret_code=$db_conn->query($sql)) === false) {
98
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
99
-            return null;
100
-        }
101
-        $value=$ret_code->fetch();
102
-        if ($value != null && isset($value['value']))
103
-        {
104
-            return $value['value'];
105
-        }
106
-        return null;
107
-    }
88
+	/**
89
+	 *   Get data from db_config
90
+	 *	@param $element string name of param
91
+	 *	@return mixed : value (or null)
92
+	 */
93
+	protected function getDBConfig($element)  // TODO : put this in DB class
94
+	{
95
+		$db_conn=$this->trapsDB->db_connect_trap();
96
+		$sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
97
+		if (($ret_code=$db_conn->query($sql)) === false) {
98
+			$this->logging->log('No result in query : ' . $sql,WARN,'');
99
+			return null;
100
+		}
101
+		$value=$ret_code->fetch();
102
+		if ($value != null && isset($value['value']))
103
+		{
104
+			return $value['value'];
105
+		}
106
+		return null;
107
+	}
108 108
     
109
-    /**
110
-     * Get options from ini file
111
-     * @param array $trap_config : ini file array
112
-     */
113
-    protected function getMainOptions($trapConfig)
114
-    {
115
-        
116
-        $nodeStatus='';
117
-        $this->getOptionIfSet($trapConfig,'config','node', $nodeStatus);
118
-        if ($this->getTrapApi()->setStatus($nodeStatus) === FALSE)
119
-        {
120
-            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
121
-            $this->getTrapApi()->setStatusMaster();
122
-        }
123
-        else 
124
-        {
125
-            if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
126
-            {
127
-                // Get options to connect to API
128
-                $IP = $port = $user =  $pass = null;
129
-                $this->getOptionIfSet($trapConfig,'config','masterIP', $IP, ERROR);
130
-                $this->getOptionIfSet($trapConfig,'config','masterPort', $port, ERROR);
131
-                $this->getOptionIfSet($trapConfig,'config','masterUser', $user, ERROR);
132
-                $this->getOptionIfSet($trapConfig,'config','masterPass', $pass, ERROR);
133
-                $this->getTrapApi()->setParams($IP, $port, $user, $pass);
134
-                return;
135
-            }
136
-        }
137
-        
138
-        // Snmptranslate binary path
139
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
140
-        
141
-        // mibs path
142
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
143
-        
144
-        // icinga2cmd path
145
-        $this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
146
-        
147
-        // table prefix
148
-        $this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
149
-        
150
-        // API options
151
-        if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
152
-        {
153
-            $this->apiUse=true;
154
-            // Get API options or throw exception as not configured correctly
155
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort,ERROR);
156
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername,ERROR);
157
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword,ERROR);
158
-        }
159
-    }
109
+	/**
110
+	 * Get options from ini file
111
+	 * @param array $trap_config : ini file array
112
+	 */
113
+	protected function getMainOptions($trapConfig)
114
+	{
115
+        
116
+		$nodeStatus='';
117
+		$this->getOptionIfSet($trapConfig,'config','node', $nodeStatus);
118
+		if ($this->getTrapApi()->setStatus($nodeStatus) === FALSE)
119
+		{
120
+			$this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
121
+			$this->getTrapApi()->setStatusMaster();
122
+		}
123
+		else 
124
+		{
125
+			if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
126
+			{
127
+				// Get options to connect to API
128
+				$IP = $port = $user =  $pass = null;
129
+				$this->getOptionIfSet($trapConfig,'config','masterIP', $IP, ERROR);
130
+				$this->getOptionIfSet($trapConfig,'config','masterPort', $port, ERROR);
131
+				$this->getOptionIfSet($trapConfig,'config','masterUser', $user, ERROR);
132
+				$this->getOptionIfSet($trapConfig,'config','masterPass', $pass, ERROR);
133
+				$this->getTrapApi()->setParams($IP, $port, $user, $pass);
134
+				return;
135
+			}
136
+		}
137
+        
138
+		// Snmptranslate binary path
139
+		$this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
140
+        
141
+		// mibs path
142
+		$this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
143
+        
144
+		// icinga2cmd path
145
+		$this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
146
+        
147
+		// table prefix
148
+		$this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
149
+        
150
+		// API options
151
+		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
152
+		{
153
+			$this->apiUse=true;
154
+			// Get API options or throw exception as not configured correctly
155
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort,ERROR);
156
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername,ERROR);
157
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword,ERROR);
158
+		}
159
+	}
160 160
     
161
-    /**
162
-     * Create and setup database class for trap & ido (if no api) db
163
-     * @param array $trap_config : ini file array
164
-     */
165
-    protected function setupDatabase($trapConfig)
166
-    {
167
-        // Trap database
168
-        if (!array_key_exists('database',$trapConfig['config']))
169
-        {
170
-            $this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
171
-            return;
172
-        }
173
-        $dbTrapName=$trapConfig['config']['database'];
174
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
175
-        
176
-        if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
177
-        {
178
-            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
179
-            return;
180
-        }
181
-        if (!array_key_exists($dbTrapName,$dbConfig))
182
-        {
183
-            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
184
-            return;
185
-        }
186
-        
187
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
188
-        
189
-        $this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG );
190
-        
191
-        //TODO enable this again when API queries are all done :
192
-        if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
193
-        
194
-        // IDO Database
195
-        if (!array_key_exists('IDOdatabase',$trapConfig['config']))
196
-        {
197
-            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
198
-        }
199
-        $dbIdoName=$trapConfig['config']['IDOdatabase'];
200
-        
201
-        $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
202
-        if (!array_key_exists($dbIdoName,$dbConfig))
203
-        {
204
-            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
205
-            return;
206
-        }
207
-        
208
-        $this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
209
-    }
161
+	/**
162
+	 * Create and setup database class for trap & ido (if no api) db
163
+	 * @param array $trap_config : ini file array
164
+	 */
165
+	protected function setupDatabase($trapConfig)
166
+	{
167
+		// Trap database
168
+		if (!array_key_exists('database',$trapConfig['config']))
169
+		{
170
+			$this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
171
+			return;
172
+		}
173
+		$dbTrapName=$trapConfig['config']['database'];
174
+		$this->logging->log("Found database in config file: ".$dbTrapName,INFO );
175
+        
176
+		if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
177
+		{
178
+			$this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
179
+			return;
180
+		}
181
+		if (!array_key_exists($dbTrapName,$dbConfig))
182
+		{
183
+			$this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
184
+			return;
185
+		}
186
+        
187
+		$this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
188
+        
189
+		$this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG );
190
+        
191
+		//TODO enable this again when API queries are all done :
192
+		if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
193
+        
194
+		// IDO Database
195
+		if (!array_key_exists('IDOdatabase',$trapConfig['config']))
196
+		{
197
+			$this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
198
+		}
199
+		$dbIdoName=$trapConfig['config']['IDOdatabase'];
200
+        
201
+		$this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
202
+		if (!array_key_exists($dbIdoName,$dbConfig))
203
+		{
204
+			$this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
205
+			return;
206
+		}
207
+        
208
+		$this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
209
+	}
210 210
     
211 211
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -36,15 +36,15 @@  discard block
 block discarded – undo
36 36
      * @param string $message warning message if not found
37 37
      * @return boolean true if found, or false
38 38
      */
39
-    protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = WARN, $message = null)
39
+    protected function getOptionIfSet($option_array, $option_category, $option_name, &$option_var, $log_level=WARN, $message=null)
40 40
     {
41 41
         if (!isset($option_array[$option_category][$option_name]))
42 42
         {
43 43
             if ($message === null)
44 44
             {
45
-                $message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
45
+                $message='No '.$option_name.' in config file: '.$this->trapModuleConfig;
46 46
             }
47
-            $this->getLogging()->log($message,$log_level);
47
+            $this->getLogging()->log($message, $log_level);
48 48
             return false;
49 49
         }
50 50
         else
@@ -62,24 +62,24 @@  discard block
 block discarded – undo
62 62
         // Database options
63 63
         if ($this->logSetup === false) // Only if logging was no setup in constructor
64 64
         {
65
-            $this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
66
-            $this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
67
-            $this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
65
+            $this->getDBConfigIfSet('log_level', $this->getLogging()->debugLevel);
66
+            $this->getDBConfigIfSet('log_destination', $this->getLogging()->outputMode);
67
+            $this->getDBConfigIfSet('log_file', $this->getLogging()->outputFile);
68 68
         }
69 69
         
70
-        $tmpVal = -1; // Get boolean coded in database as 1/0
70
+        $tmpVal=-1; // Get boolean coded in database as 1/0
71 71
         $this->getDBConfigIfSet('use_SnmpTrapAddess', $tmpVal);
72
-        if ($tmpVal != -1) $this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
72
+        if ($tmpVal != -1) $this->useSnmpTrapAddess=($tmpVal == 1) ? TRUE : FALSE;
73 73
         
74 74
         $this->getDBConfigIfSet('SnmpTrapAddess_oid', $this->snmpTrapAddressOID); // Get oid then replace '.' with '\.' to use in regexp whrn reading traps
75
-        $this->snmpTrapAddressOID = preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
75
+        $this->snmpTrapAddressOID=preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
76 76
     }
77 77
         
78 78
     /** Set $variable to value if $element found in database config table
79 79
      * @param string $element
80 80
      * @param string $variable
81 81
      */
82
-    protected function getDBConfigIfSet($element,&$variable)
82
+    protected function getDBConfigIfSet($element, &$variable)
83 83
     {
84 84
         $value=$this->getDBConfig($element);
85 85
         if ($value != null) $variable=$value;
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
         $db_conn=$this->trapsDB->db_connect_trap();
96 96
         $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
97 97
         if (($ret_code=$db_conn->query($sql)) === false) {
98
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
98
+            $this->logging->log('No result in query : '.$sql, WARN, '');
99 99
             return null;
100 100
         }
101 101
         $value=$ret_code->fetch();
@@ -114,10 +114,10 @@  discard block
 block discarded – undo
114 114
     {
115 115
         
116 116
         $nodeStatus='';
117
-        $this->getOptionIfSet($trapConfig,'config','node', $nodeStatus);
117
+        $this->getOptionIfSet($trapConfig, 'config', 'node', $nodeStatus);
118 118
         if ($this->getTrapApi()->setStatus($nodeStatus) === FALSE)
119 119
         {
120
-            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
120
+            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER', WARN);
121 121
             $this->getTrapApi()->setStatusMaster();
122 122
         }
123 123
         else 
@@ -125,36 +125,36 @@  discard block
 block discarded – undo
125 125
             if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
126 126
             {
127 127
                 // Get options to connect to API
128
-                $IP = $port = $user =  $pass = null;
129
-                $this->getOptionIfSet($trapConfig,'config','masterIP', $IP, ERROR);
130
-                $this->getOptionIfSet($trapConfig,'config','masterPort', $port, ERROR);
131
-                $this->getOptionIfSet($trapConfig,'config','masterUser', $user, ERROR);
132
-                $this->getOptionIfSet($trapConfig,'config','masterPass', $pass, ERROR);
128
+                $IP=$port=$user=$pass=null;
129
+                $this->getOptionIfSet($trapConfig, 'config', 'masterIP', $IP, ERROR);
130
+                $this->getOptionIfSet($trapConfig, 'config', 'masterPort', $port, ERROR);
131
+                $this->getOptionIfSet($trapConfig, 'config', 'masterUser', $user, ERROR);
132
+                $this->getOptionIfSet($trapConfig, 'config', 'masterPass', $pass, ERROR);
133 133
                 $this->getTrapApi()->setParams($IP, $port, $user, $pass);
134 134
                 return;
135 135
             }
136 136
         }
137 137
         
138 138
         // Snmptranslate binary path
139
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
139
+        $this->getOptionIfSet($trapConfig, 'config', 'snmptranslate', $this->snmptranslate);
140 140
         
141 141
         // mibs path
142
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
142
+        $this->getOptionIfSet($trapConfig, 'config', 'snmptranslate_dirs', $this->snmptranslate_dirs);
143 143
         
144 144
         // icinga2cmd path
145
-        $this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
145
+        $this->getOptionIfSet($trapConfig, 'config', 'icingacmd', $this->icinga2cmd);
146 146
         
147 147
         // table prefix
148
-        $this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
148
+        $this->getOptionIfSet($trapConfig, 'config', 'database_prefix', $this->dbPrefix);
149 149
         
150 150
         // API options
151
-        if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
151
+        if ($this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_host', $this->apiHostname))
152 152
         {
153 153
             $this->apiUse=true;
154 154
             // Get API options or throw exception as not configured correctly
155
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort,ERROR);
156
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername,ERROR);
157
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword,ERROR);
155
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_port', $this->apiPort, ERROR);
156
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_user', $this->apiUsername, ERROR);
157
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_password', $this->apiPassword, ERROR);
158 158
         }
159 159
     }
160 160
     
@@ -165,43 +165,43 @@  discard block
 block discarded – undo
165 165
     protected function setupDatabase($trapConfig)
166 166
     {
167 167
         // Trap database
168
-        if (!array_key_exists('database',$trapConfig['config']))
168
+        if (!array_key_exists('database', $trapConfig['config']))
169 169
         {
170
-            $this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
170
+            $this->logging->log("No database in config file: ".$this->trapModuleConfig, ERROR, '');
171 171
             return;
172 172
         }
173 173
         $dbTrapName=$trapConfig['config']['database'];
174
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
174
+        $this->logging->log("Found database in config file: ".$dbTrapName, INFO);
175 175
         
176
-        if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
176
+        if (($dbConfig=parse_ini_file($this->icingaweb2Ressources, true)) === false)
177 177
         {
178
-            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
178
+            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources, ERROR, '');
179 179
             return;
180 180
         }
181
-        if (!array_key_exists($dbTrapName,$dbConfig))
181
+        if (!array_key_exists($dbTrapName, $dbConfig))
182 182
         {
183
-            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
183
+            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources, ERROR, '');
184 184
             return;
185 185
         }
186 186
         
187
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
187
+        $this->trapsDB=new Database($this->logging, $dbConfig[$dbTrapName], $this->dbPrefix);
188 188
         
189
-        $this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG );
189
+        $this->logging->log("API Use : ".print_r($this->apiUse, true), DEBUG);
190 190
         
191 191
         //TODO enable this again when API queries are all done :
192 192
         if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
193 193
         
194 194
         // IDO Database
195
-        if (!array_key_exists('IDOdatabase',$trapConfig['config']))
195
+        if (!array_key_exists('IDOdatabase', $trapConfig['config']))
196 196
         {
197
-            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
197
+            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig, ERROR, '');
198 198
         }
199 199
         $dbIdoName=$trapConfig['config']['IDOdatabase'];
200 200
         
201
-        $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
202
-        if (!array_key_exists($dbIdoName,$dbConfig))
201
+        $this->logging->log("Found IDO database in config file: ".$dbIdoName, INFO);
202
+        if (!array_key_exists($dbIdoName, $dbConfig))
203 203
         {
204
-            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
204
+            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources, ERROR, '');
205 205
             return;
206 206
         }
207 207
         
Please login to merge, or discard this patch.
Braces   +15 added lines, -8 removed lines patch added patch discarded remove patch
@@ -46,8 +46,7 @@  discard block
 block discarded – undo
46 46
             }
47 47
             $this->getLogging()->log($message,$log_level);
48 48
             return false;
49
-        }
50
-        else
49
+        } else
51 50
         {
52 51
             $option_var=$option_array[$option_category][$option_name];
53 52
             return true;
@@ -60,16 +59,20 @@  discard block
 block discarded – undo
60 59
     protected function getDatabaseOptions()
61 60
     {
62 61
         // Database options
63
-        if ($this->logSetup === false) // Only if logging was no setup in constructor
62
+        if ($this->logSetup === false) {
63
+        	// Only if logging was no setup in constructor
64 64
         {
65 65
             $this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
66
+        }
66 67
             $this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
67 68
             $this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
68 69
         }
69 70
         
70 71
         $tmpVal = -1; // Get boolean coded in database as 1/0
71 72
         $this->getDBConfigIfSet('use_SnmpTrapAddess', $tmpVal);
72
-        if ($tmpVal != -1) $this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
73
+        if ($tmpVal != -1) {
74
+        	$this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
75
+        }
73 76
         
74 77
         $this->getDBConfigIfSet('SnmpTrapAddess_oid', $this->snmpTrapAddressOID); // Get oid then replace '.' with '\.' to use in regexp whrn reading traps
75 78
         $this->snmpTrapAddressOID = preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
@@ -82,7 +85,9 @@  discard block
 block discarded – undo
82 85
     protected function getDBConfigIfSet($element,&$variable)
83 86
     {
84 87
         $value=$this->getDBConfig($element);
85
-        if ($value != null) $variable=$value;
88
+        if ($value != null) {
89
+        	$variable=$value;
90
+        }
86 91
     }
87 92
     
88 93
     /**
@@ -119,8 +124,7 @@  discard block
 block discarded – undo
119 124
         {
120 125
             $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
121 126
             $this->getTrapApi()->setStatusMaster();
122
-        }
123
-        else 
127
+        } else 
124 128
         {
125 129
             if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
126 130
             {
@@ -189,7 +193,10 @@  discard block
 block discarded – undo
189 193
         $this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG );
190 194
         
191 195
         //TODO enable this again when API queries are all done :
192
-        if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
196
+        if ($this->apiUse === true) {
197
+        	return;
198
+        }
199
+        // In case of API use, no IDO is necessary
193 200
         
194 201
         // IDO Database
195 202
         if (!array_key_exists('IDOdatabase',$trapConfig['config']))
Please login to merge, or discard this patch.