Passed
Pull Request — master (#78)
by
unknown
03:51
created
application/controllers/StatusController.php 1 patch
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.
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 1 patch
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.
application/clicommands/MibCommand.php 1 patch
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.
library/Trapdirector/TrapsActions/UIDatabase.php 1 patch
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.
library/Trapdirector/Icinga2API.php 1 patch
Indentation   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -10,303 +10,303 @@
 block discarded – undo
10 10
 class Icinga2API extends IcingaApiBase
11 11
 {
12 12
     
13
-    /**
14
-     * Creates Icinga2API object
15
-     * 
16
-     * @param string $host host name or IP
17
-     * @param number $port API port
18
-     */
19
-    public function __construct($host, $port = 5665)
20
-    {
21
-        parent::__construct($host,$port);
22
-    }
23
-    /**
13
+	/**
14
+	 * Creates Icinga2API object
15
+	 * 
16
+	 * @param string $host host name or IP
17
+	 * @param number $port API port
18
+	 */
19
+	public function __construct($host, $port = 5665)
20
+	{
21
+		parent::__construct($host,$port);
22
+	}
23
+	/**
24 24
 
25 25
 /************ Host query ************/  
26 26
 
27
-    /**
28
-     * return array of host by filter
29
-     * @param string $hostfilter
30
-     * @throws Exception
31
-     * @return array objects : array('__name','name','display_name','id' (=__name), 'address', 'ip4' (=address), 'address6', 'ip6' (=address6)
32
-     */
33
-    public function getHostByFilter(string $hostfilter)
34
-    {
35
-        $hosts = $this->standardQuery(
36
-            'host',
37
-            $hostfilter,
38
-            //'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
39
-            array('__name','name','display_name','address','address6')
40
-            );
41
-        foreach ( array_keys($hosts) as $key )
42
-        {
43
-            $hosts[$key]->id = $hosts[$key]->__name;
44
-            $hosts[$key]->ip4 = $hosts[$key]->address;
45
-            $hosts[$key]->ip6 = $hosts[$key]->address6;
46
-        }
47
-        return $hosts;
48
-    }
27
+	/**
28
+	 * return array of host by filter
29
+	 * @param string $hostfilter
30
+	 * @throws Exception
31
+	 * @return array objects : array('__name','name','display_name','id' (=__name), 'address', 'ip4' (=address), 'address6', 'ip6' (=address6)
32
+	 */
33
+	public function getHostByFilter(string $hostfilter)
34
+	{
35
+		$hosts = $this->standardQuery(
36
+			'host',
37
+			$hostfilter,
38
+			//'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
39
+			array('__name','name','display_name','address','address6')
40
+			);
41
+		foreach ( array_keys($hosts) as $key )
42
+		{
43
+			$hosts[$key]->id = $hosts[$key]->__name;
44
+			$hosts[$key]->ip4 = $hosts[$key]->address;
45
+			$hosts[$key]->ip6 = $hosts[$key]->address6;
46
+		}
47
+		return $hosts;
48
+	}
49 49
     
50
-    /**
51
-     * return array of host by IP (4 or 6)
52
-     * @param string $ip
53
-     * @throws Exception
54
-     * @return array objects : array('__name','name','display_name')
55
-     */
56
-    public function getHostByIP(string $ip) 
57
-    {
58
-        return $this->getHostByFilter('match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6)');
59
-    }
50
+	/**
51
+	 * return array of host by IP (4 or 6)
52
+	 * @param string $ip
53
+	 * @throws Exception
54
+	 * @return array objects : array('__name','name','display_name')
55
+	 */
56
+	public function getHostByIP(string $ip) 
57
+	{
58
+		return $this->getHostByFilter('match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6)');
59
+	}
60 60
 
61 61
     
62
-    /**
63
-     * Get host(s) by name in API
64
-     * @param string $name
65
-     * @return array|NULL[] : see getHostByIP
66
-     */
67
-    public function getHostByName(string $name)
68
-    {
69
-        return $this->getHostByFilter('match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name)');
70
-    }
62
+	/**
63
+	 * Get host(s) by name in API
64
+	 * @param string $name
65
+	 * @return array|NULL[] : see getHostByIP
66
+	 */
67
+	public function getHostByName(string $name)
68
+	{
69
+		return $this->getHostByFilter('match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name)');
70
+	}
71 71
 
72
-    /**
73
-     * Get host(s) by name in API
74
-     * @param string $name
75
-     * @return array|NULL[] : see getHostByIP
76
-     */
77
-    public function getHostByNameOrIP(string $name)
78
-    {
79
-        return $this->getHostByFilter( 
80
-            'match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name) || match("*' . $name . '*",host.address) || match("*' . $name . '*",host.address6)');
81
-    }
72
+	/**
73
+	 * Get host(s) by name in API
74
+	 * @param string $name
75
+	 * @return array|NULL[] : see getHostByIP
76
+	 */
77
+	public function getHostByNameOrIP(string $name)
78
+	{
79
+		return $this->getHostByFilter( 
80
+			'match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name) || match("*' . $name . '*",host.address) || match("*' . $name . '*",host.address6)');
81
+	}
82 82
     
83
-    public function getHostInfoByID(string $name)
84
-    {
85
-        $host = $this->getHostByFilter(
86
-            'host.__name=="'. $name .'"');
87
-        if (isset($host[0]))
88
-            return $host[0];
89
-        else
90
-            return NULL;
91
-    }
83
+	public function getHostInfoByID(string $name)
84
+	{
85
+		$host = $this->getHostByFilter(
86
+			'host.__name=="'. $name .'"');
87
+		if (isset($host[0]))
88
+			return $host[0];
89
+		else
90
+			return NULL;
91
+	}
92 92
  
93
-    /**
94
-     * Get all host and IP from hostgroup
95
-     * @param string $hostGroup
96
-     * @throws Exception
97
-     * @return array : attributes : address, address6, name
98
-     */
99
-    public function getHostsIPByHostGroup($hostGroup)
100
-    {        
101
-        return $this->standardQuery(
102
-            'host', 
103
-            '"' . $hostGroup . '" in host.groups',
104
-            array('address','address6','name')
93
+	/**
94
+	 * Get all host and IP from hostgroup
95
+	 * @param string $hostGroup
96
+	 * @throws Exception
97
+	 * @return array : attributes : address, address6, name
98
+	 */
99
+	public function getHostsIPByHostGroup($hostGroup)
100
+	{        
101
+		return $this->standardQuery(
102
+			'host', 
103
+			'"' . $hostGroup . '" in host.groups',
104
+			array('address','address6','name')
105 105
                 
106
-        );
107
-    }
106
+		);
107
+	}
108 108
 
109 109
 
110
-    /** Get services from host in API
111
-     *	
112
-     *  @throws Exception
113
-     *	@param $id string host name
114
-     *  @param bool $active
115
-     *  @param bool $passive_svc
116
-     *	@return array display_name (of service), service_object_id
117
-     */
118
-    public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
119
-    {
120
-        $filter = 'match("' . $id . '!*", service.__name)';
121
-        if ($active === TRUE)
122
-        {
123
-            $filter .= ' && service.active==true';
124
-        }
125
-        if ($passive_svc === TRUE)
126
-        {
127
-            $filter .= ' && service.enable_passive_checks==true';
128
-        }
129
-        $services =  $this->standardQuery(
130
-            'service',
131
-            $filter,
132
-            array('__name','name','display_name','active')
133
-            );
110
+	/** Get services from host in API
111
+	 *	
112
+	 *  @throws Exception
113
+	 *	@param $id string host name
114
+	 *  @param bool $active
115
+	 *  @param bool $passive_svc
116
+	 *	@return array display_name (of service), service_object_id
117
+	 */
118
+	public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
119
+	{
120
+		$filter = 'match("' . $id . '!*", service.__name)';
121
+		if ($active === TRUE)
122
+		{
123
+			$filter .= ' && service.active==true';
124
+		}
125
+		if ($passive_svc === TRUE)
126
+		{
127
+			$filter .= ' && service.enable_passive_checks==true';
128
+		}
129
+		$services =  $this->standardQuery(
130
+			'service',
131
+			$filter,
132
+			array('__name','name','display_name','active')
133
+			);
134 134
         
135
-        foreach ( array_keys($services) as $key )
136
-        {
137
-            $services[$key]->id = $services[$key]->__name;
138
-        }
135
+		foreach ( array_keys($services) as $key )
136
+		{
137
+			$services[$key]->id = $services[$key]->__name;
138
+		}
139 139
         
140
-        return $services;
140
+		return $services;
141 141
         
142
-    }
142
+	}
143 143
 
144 144
 /************  Host group query ************/    
145
-    /**
146
-     * return array of host by IP (4 or 6) or name
147
-     * @param string $group Host group name
148
-     * @throws Exception
149
-     * @return array objects : array('name','display_name')
150
-     */
151
-    public function getHostsByGroup(string $group)
152
-    {
153
-         return $this->standardQuery(
154
-            'host',
155
-            '"' . $group . '" in host.groups',
156
-            array('name','display_name')
157
-            );
158
-    }
145
+	/**
146
+	 * return array of host by IP (4 or 6) or name
147
+	 * @param string $group Host group name
148
+	 * @throws Exception
149
+	 * @return array objects : array('name','display_name')
150
+	 */
151
+	public function getHostsByGroup(string $group)
152
+	{
153
+		 return $this->standardQuery(
154
+			'host',
155
+			'"' . $group . '" in host.groups',
156
+			array('name','display_name')
157
+			);
158
+	}
159 159
     
160
-    public function getServicesByHostGroupid(string $group)
161
-    {
162
-        $hostList = $this->getHostsByGroup($group);
163
-        //return $hostList;
164
-        $hostNum = count($hostList);
165
-        $serviceList=array();
166
-        foreach ($hostList as $curHost)
167
-        {
168
-            $services = $this->getServicesByHostid($curHost->name);
169
-            foreach ($services as $service)
170
-            {
171
-                //return $service;
172
-                if (! isset($serviceList[$service->name]))
173
-                {
174
-                    $serviceList[$service->name]=
175
-                        array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
176
-                }
177
-                else
178
-                {
179
-                    $serviceList[$service->name]['num']++;
180
-                }
181
-            }
182
-        }
183
-        $commonServices=array();
184
-        foreach ($serviceList as $key => $values)
185
-        {
186
-            if ($values['num'] >= $hostNum)
187
-            {
188
-                array_push($commonServices,array($key,$values['display_name']));
189
-            }
190
-        }
191
-        return $commonServices;
192
-    }
160
+	public function getServicesByHostGroupid(string $group)
161
+	{
162
+		$hostList = $this->getHostsByGroup($group);
163
+		//return $hostList;
164
+		$hostNum = count($hostList);
165
+		$serviceList=array();
166
+		foreach ($hostList as $curHost)
167
+		{
168
+			$services = $this->getServicesByHostid($curHost->name);
169
+			foreach ($services as $service)
170
+			{
171
+				//return $service;
172
+				if (! isset($serviceList[$service->name]))
173
+				{
174
+					$serviceList[$service->name]=
175
+						array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
176
+				}
177
+				else
178
+				{
179
+					$serviceList[$service->name]['num']++;
180
+				}
181
+			}
182
+		}
183
+		$commonServices=array();
184
+		foreach ($serviceList as $key => $values)
185
+		{
186
+			if ($values['num'] >= $hostNum)
187
+			{
188
+				array_push($commonServices,array($key,$values['display_name']));
189
+			}
190
+		}
191
+		return $commonServices;
192
+	}
193 193
  
194
-    /**
195
-     * Get all host and IP from hostgroup
196
-     * @param string $hostGroup
197
-     * @throws Exception
198
-     * @return array : attributes : address, address6, name
199
-     */
200
-    public function getHostGroupByName($name)
201
-    {
202
-        $hosts = $this->standardQuery(
203
-            'hostgroup',
204
-            'match("*' . $name . '*",hostgroup.name)',
205
-            array('__name','name','display_name')
194
+	/**
195
+	 * Get all host and IP from hostgroup
196
+	 * @param string $hostGroup
197
+	 * @throws Exception
198
+	 * @return array : attributes : address, address6, name
199
+	 */
200
+	public function getHostGroupByName($name)
201
+	{
202
+		$hosts = $this->standardQuery(
203
+			'hostgroup',
204
+			'match("*' . $name . '*",hostgroup.name)',
205
+			array('__name','name','display_name')
206 206
             
207
-            );
208
-        foreach ( array_keys($hosts) as $key )
209
-        {
210
-            $hosts[$key]->id = $hosts[$key]->__name;
211
-        }
212
-        return $hosts;
213
-    }
207
+			);
208
+		foreach ( array_keys($hosts) as $key )
209
+		{
210
+			$hosts[$key]->id = $hosts[$key]->__name;
211
+		}
212
+		return $hosts;
213
+	}
214 214
     
215
-    /**
216
-     * Get hostgroup by id (__name)
217
-     * @param string $hostGroup
218
-     * @throws Exception
219
-     * @return array : __name, name, display_name
220
-     */
221
-    public function getHostGroupById($name)
222
-    {
223
-        $hosts = $this->standardQuery(
224
-            'hostgroup',
225
-            'hostgroup.__name=="'. $name .'"',
226
-            array('__name','name','display_name')
215
+	/**
216
+	 * Get hostgroup by id (__name)
217
+	 * @param string $hostGroup
218
+	 * @throws Exception
219
+	 * @return array : __name, name, display_name
220
+	 */
221
+	public function getHostGroupById($name)
222
+	{
223
+		$hosts = $this->standardQuery(
224
+			'hostgroup',
225
+			'hostgroup.__name=="'. $name .'"',
226
+			array('__name','name','display_name')
227 227
             
228
-            );
229
-        $hosts[0]->id = $hosts[0]->__name;
230
-        return $hosts[0];
231
-    }
228
+			);
229
+		$hosts[0]->id = $hosts[0]->__name;
230
+		return $hosts[0];
231
+	}
232 232
     
233 233
 /****************   Service queries ************/
234
-    /** Get services object id by host name / service name
235
-     *	does not catch exceptions
236
-     *	@param $hostname string host name
237
-     *	@param $name string service name
238
-     *  @param bool $active : if true, return only active service
239
-     *  @param bool $passive_svc : if true, return only service accepting passive checks
240
-     *	@return array  service id
241
-     */
242
-    public function getServiceIDByName($hostname,$name,bool $active = TRUE, bool $passive_svc = TRUE)
243
-    {
244
-        $filter = 'service.__name=="' . $hostname . '!'. $name .'"';
245
-        if ($active === TRUE)
246
-        {
247
-            $filter .= ' && service.active==true';
248
-        }
249
-        if ($passive_svc === TRUE)
250
-        {
251
-            $filter .= ' && service.enable_passive_checks==true';
252
-        }
253
-        $services =  $this->standardQuery(
254
-            'service',
255
-            $filter,
256
-            array('__name','name','display_name','active','enable_passive_checks')
257
-            );
234
+	/** Get services object id by host name / service name
235
+	 *	does not catch exceptions
236
+	 *	@param $hostname string host name
237
+	 *	@param $name string service name
238
+	 *  @param bool $active : if true, return only active service
239
+	 *  @param bool $passive_svc : if true, return only service accepting passive checks
240
+	 *	@return array  service id
241
+	 */
242
+	public function getServiceIDByName($hostname,$name,bool $active = TRUE, bool $passive_svc = TRUE)
243
+	{
244
+		$filter = 'service.__name=="' . $hostname . '!'. $name .'"';
245
+		if ($active === TRUE)
246
+		{
247
+			$filter .= ' && service.active==true';
248
+		}
249
+		if ($passive_svc === TRUE)
250
+		{
251
+			$filter .= ' && service.enable_passive_checks==true';
252
+		}
253
+		$services =  $this->standardQuery(
254
+			'service',
255
+			$filter,
256
+			array('__name','name','display_name','active','enable_passive_checks')
257
+			);
258 258
         
259
-        foreach ( array_keys($services) as $key )
260
-        {
261
-            $services[$key]->id = $services[$key]->__name;
262
-        }
259
+		foreach ( array_keys($services) as $key )
260
+		{
261
+			$services[$key]->id = $services[$key]->__name;
262
+		}
263 263
         
264
-        return $services;
265
-    }
264
+		return $services;
265
+	}
266 266
  
267
-    /** Get services object by id (host!name)
268
-     *	does not catch exceptions
269
-     *	@param $name string service __name (host!name)
270
-     *	@return array  service id
271
-     */
272
-    public function getServiceById($name)
273
-    {
274
-        $filter = 'service.__name=="' .  $name .'"';
275
-        $services =  $this->standardQuery(
276
-            'service',
277
-            $filter,
278
-            array('__name','name','display_name','active','enable_passive_checks')
279
-            );
267
+	/** Get services object by id (host!name)
268
+	 *	does not catch exceptions
269
+	 *	@param $name string service __name (host!name)
270
+	 *	@return array  service id
271
+	 */
272
+	public function getServiceById($name)
273
+	{
274
+		$filter = 'service.__name=="' .  $name .'"';
275
+		$services =  $this->standardQuery(
276
+			'service',
277
+			$filter,
278
+			array('__name','name','display_name','active','enable_passive_checks')
279
+			);
280 280
         
281
-        foreach ( array_keys($services) as $key )
282
-        {
283
-            $services[$key]->id = $services[$key]->__name;
284
-        }
281
+		foreach ( array_keys($services) as $key )
282
+		{
283
+			$services[$key]->id = $services[$key]->__name;
284
+		}
285 285
         
286
-        return $services;
287
-    }
286
+		return $services;
287
+	}
288 288
 
289
-    /** Get services object by id (host!name)
290
-     *	does not catch exceptions
291
-     *	@param $name string service __name (host!name)
292
-     *	@return array  service id
293
-     */
294
-    public function getNOKService()
295
-    {
296
-        $filter = 'service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
-        $services =  $this->standardQuery(
298
-            'service',
299
-            $filter,
300
-            array('__name','name','last_check','host_name','state')
301
-            );
289
+	/** Get services object by id (host!name)
290
+	 *	does not catch exceptions
291
+	 *	@param $name string service __name (host!name)
292
+	 *	@return array  service id
293
+	 */
294
+	public function getNOKService()
295
+	{
296
+		$filter = 'service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
+		$services =  $this->standardQuery(
298
+			'service',
299
+			$filter,
300
+			array('__name','name','last_check','host_name','state')
301
+			);
302 302
         
303
-        foreach ( array_keys($services) as $key )
304
-        {
305
-            $services[$key]->id = $services[$key]->__name;
306
-        }
303
+		foreach ( array_keys($services) as $key )
304
+		{
305
+			$services[$key]->id = $services[$key]->__name;
306
+		}
307 307
         
308
-        return $services;
309
-    }
308
+		return $services;
309
+	}
310 310
     
311 311
     
312 312
 }
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/MibDatabase.php 1 patch
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.
library/Trapdirector/TrapsProcess/TrapConfig.php 1 patch
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.
library/Trapdirector/TrapsProcess/Trap.php 1 patch
Indentation   +836 added lines, -836 removed lines patch added patch discarded remove patch
@@ -17,855 +17,855 @@  discard block
 block discarded – undo
17 17
  */
18 18
 class Trap
19 19
 {
20
-    use TrapConfig;
20
+	use TrapConfig;
21 21
     
22
-    // Configuration files and dirs
23
-    /** @var string Icinga etc path */
24
-    protected $icingaweb2Etc;
25
-    /** @var string $trapModuleConfig config.ini of module */
26
-    protected $trapModuleConfig;
27
-    /** @var string $icingaweb2Ressources resources.ini of icingaweb2 */
28
-    protected $icingaweb2Ressources;
29
-    // Options from config.ini (default values)
30
-    /** @var string $snmptranslate */
31
-    protected $snmptranslate='/usr/bin/snmptranslate';
32
-    /** @var string $snmptranslate_dirs */
33
-    protected $snmptranslate_dirs='/usr/share/icingaweb2/modules/trapdirector/mibs';
34
-    /** @var string $icinga2cmd */
35
-    protected $icinga2cmd='/var/run/icinga2/cmd/icinga2.cmd';
36
-    /** @var string $dbPrefix */
37
-    protected $dbPrefix='traps_';
22
+	// Configuration files and dirs
23
+	/** @var string Icinga etc path */
24
+	protected $icingaweb2Etc;
25
+	/** @var string $trapModuleConfig config.ini of module */
26
+	protected $trapModuleConfig;
27
+	/** @var string $icingaweb2Ressources resources.ini of icingaweb2 */
28
+	protected $icingaweb2Ressources;
29
+	// Options from config.ini (default values)
30
+	/** @var string $snmptranslate */
31
+	protected $snmptranslate='/usr/bin/snmptranslate';
32
+	/** @var string $snmptranslate_dirs */
33
+	protected $snmptranslate_dirs='/usr/share/icingaweb2/modules/trapdirector/mibs';
34
+	/** @var string $icinga2cmd */
35
+	protected $icinga2cmd='/var/run/icinga2/cmd/icinga2.cmd';
36
+	/** @var string $dbPrefix */
37
+	protected $dbPrefix='traps_';
38 38
     
39
-    // API
40
-    /** @var boolean $apiUse */
41
-    protected $apiUse=false;
42
-    /** @var Icinga2API $icinga2api */
43
-    protected $icinga2api=null;
44
-    /** @var string $apiHostname */
45
-    protected $apiHostname='';
46
-    /** @var integer $apiPort */
47
-    protected $apiPort=0;
48
-    /** @var string $apiUsername */
49
-    protected $apiUsername='';
50
-    /** @var string $apiPassword */
51
-    protected $apiPassword='';
39
+	// API
40
+	/** @var boolean $apiUse */
41
+	protected $apiUse=false;
42
+	/** @var Icinga2API $icinga2api */
43
+	protected $icinga2api=null;
44
+	/** @var string $apiHostname */
45
+	protected $apiHostname='';
46
+	/** @var integer $apiPort */
47
+	protected $apiPort=0;
48
+	/** @var string $apiUsername */
49
+	protected $apiUsername='';
50
+	/** @var string $apiPassword */
51
+	protected $apiPassword='';
52 52
     
53
-    // Logs
54
-    /** @var Logging Logging class. */
55
-    public $logging;    //< Logging class.
56
-    /** @var bool true if log was setup in constructor */
57
-    protected $logSetup;   //< bool true if log was setup in constructor
53
+	// Logs
54
+	/** @var Logging Logging class. */
55
+	public $logging;    //< Logging class.
56
+	/** @var bool true if log was setup in constructor */
57
+	protected $logSetup;   //< bool true if log was setup in constructor
58 58
     
59
-    // Databases
60
-    /** @var Database $trapsDB  Database class*/
61
-    public $trapsDB = null;
59
+	// Databases
60
+	/** @var Database $trapsDB  Database class*/
61
+	public $trapsDB = null;
62 62
     
63
-    // Trap received data
64
-    protected $receivingHost;
65
-    /** @var array	Main trap data (oid, source...) */
66
-    public $trapData=array();
67
-    /** @var array $trapDataExt Additional trap data objects (oid/value).*/
68
-    public $trapDataExt=array(); 
69
-    /** @var int $trapId trap_id after sql insert*/
70
-    public $trapId=null;
71
-    /** @var string $trapAction trap action for final write*/
72
-    public $trapAction=null;
73
-    /** @var boolean $trapToDb log trap to DB */
74
-    protected $trapToDb=true;
63
+	// Trap received data
64
+	protected $receivingHost;
65
+	/** @var array	Main trap data (oid, source...) */
66
+	public $trapData=array();
67
+	/** @var array $trapDataExt Additional trap data objects (oid/value).*/
68
+	public $trapDataExt=array(); 
69
+	/** @var int $trapId trap_id after sql insert*/
70
+	public $trapId=null;
71
+	/** @var string $trapAction trap action for final write*/
72
+	public $trapAction=null;
73
+	/** @var boolean $trapToDb log trap to DB */
74
+	protected $trapToDb=true;
75 75
     
76
-    /** @var Mib mib class */
77
-    public $mibClass = null;
76
+	/** @var Mib mib class */
77
+	public $mibClass = null;
78 78
     
79
-    /** @var Rule rule class */
80
-    public $ruleClass = null;
79
+	/** @var Rule rule class */
80
+	public $ruleClass = null;
81 81
     
82
-    /** @var Plugins plugins manager **/
83
-    public $pluginClass = null;
82
+	/** @var Plugins plugins manager **/
83
+	public $pluginClass = null;
84 84
     
85
-    /** @var TrapApi $trapApiClass */
86
-    public $trapApiClass = null;
85
+	/** @var TrapApi $trapApiClass */
86
+	public $trapApiClass = null;
87 87
     
88
-    function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
89
-    {
90
-        // Paths of ini files
91
-        $this->icingaweb2Etc=$etcDir;
92
-        $this->trapModuleConfig=$this->icingaweb2Etc."/modules/trapdirector/config.ini";
93
-        $this->icingaweb2Ressources=$this->icingaweb2Etc."/resources.ini";
88
+	function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
89
+	{
90
+		// Paths of ini files
91
+		$this->icingaweb2Etc=$etcDir;
92
+		$this->trapModuleConfig=$this->icingaweb2Etc."/modules/trapdirector/config.ini";
93
+		$this->icingaweb2Ressources=$this->icingaweb2Etc."/resources.ini";
94 94
 
95
-        // Setup logging
96
-        $this->logging = new Logging();
97
-        if ($baseLogLevel != null)
98
-        {
99
-            $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
100
-            $this->logSetup=true;
101
-        }
102
-        else
103
-        {
104
-            $this->logSetup=false;
105
-        }
106
-        $this->logging->log('Loggin started', INFO);
107
-        
108
-        
109
-        // Create distributed API object
110
-        
111
-        $this->trapApiClass = new TrapApi($this->logging);
112
-        
113
-        // Get options from ini files
114
-        if (! is_file($this->trapModuleConfig))
115
-        {
116
-            throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
117
-        }
118
-        $trapConfig=parse_ini_file($this->trapModuleConfig,true);
119
-        if ($trapConfig == false)
120
-        {
121
-            $this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
122
-            throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
123
-        }
124
-        $this->getMainOptions($trapConfig); // Get main options from ini file
125
-        
126
-        // Setup database class & get options
127
-        $this->setupDatabase($trapConfig);
128
-        
129
-        $this->getDatabaseOptions(); // Get options in database
130
-        
131
-        // Setup API
132
-        if ($this->apiUse === true) $this->getAPI(); // Setup API
133
-        
134
-        // Setup MIB
135
-        $this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
136
-        
137
-        // Setup Rule
138
-        $this->ruleClass = new Rule($this); //< Create Rule class
139
-        
140
-        $this->trapData=array(  // TODO : put this in a reset function (DAEMON_MODE)
141
-            'source_ip'	=> 'unknown',
142
-            'source_port'	=> 'unknown',
143
-            'destination_ip'	=> 'unknown',
144
-            'destination_port'	=> 'unknown',
145
-            'trap_oid'	=> 'unknown'
146
-        );
147
-        
148
-        // Setup Plugins
149
-        //Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
150
-        $this->pluginClass = new Plugins($this);
95
+		// Setup logging
96
+		$this->logging = new Logging();
97
+		if ($baseLogLevel != null)
98
+		{
99
+			$this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
100
+			$this->logSetup=true;
101
+		}
102
+		else
103
+		{
104
+			$this->logSetup=false;
105
+		}
106
+		$this->logging->log('Loggin started', INFO);
107
+        
108
+        
109
+		// Create distributed API object
110
+        
111
+		$this->trapApiClass = new TrapApi($this->logging);
112
+        
113
+		// Get options from ini files
114
+		if (! is_file($this->trapModuleConfig))
115
+		{
116
+			throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
117
+		}
118
+		$trapConfig=parse_ini_file($this->trapModuleConfig,true);
119
+		if ($trapConfig == false)
120
+		{
121
+			$this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
122
+			throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
123
+		}
124
+		$this->getMainOptions($trapConfig); // Get main options from ini file
125
+        
126
+		// Setup database class & get options
127
+		$this->setupDatabase($trapConfig);
128
+        
129
+		$this->getDatabaseOptions(); // Get options in database
130
+        
131
+		// Setup API
132
+		if ($this->apiUse === true) $this->getAPI(); // Setup API
133
+        
134
+		// Setup MIB
135
+		$this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
136
+        
137
+		// Setup Rule
138
+		$this->ruleClass = new Rule($this); //< Create Rule class
139
+        
140
+		$this->trapData=array(  // TODO : put this in a reset function (DAEMON_MODE)
141
+			'source_ip'	=> 'unknown',
142
+			'source_port'	=> 'unknown',
143
+			'destination_ip'	=> 'unknown',
144
+			'destination_port'	=> 'unknown',
145
+			'trap_oid'	=> 'unknown'
146
+		);
147
+        
148
+		// Setup Plugins
149
+		//Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
150
+		$this->pluginClass = new Plugins($this);
151 151
             
152 152
             
153
-    }
153
+	}
154 154
 
155
-    /** @return \Trapdirector\Logging   */
156
-    public function getLogging()
157
-    {
158
-        return $this->logging;
159
-    }
155
+	/** @return \Trapdirector\Logging   */
156
+	public function getLogging()
157
+	{
158
+		return $this->logging;
159
+	}
160 160
 
161
-    /** @return \Trapdirector\TrapApi   */
162
-    public function getTrapApi()
163
-    {
164
-        return $this->trapApiClass;
165
-    }
161
+	/** @return \Trapdirector\TrapApi   */
162
+	public function getTrapApi()
163
+	{
164
+		return $this->trapApiClass;
165
+	}
166 166
     
167
-    /** @return \Trapdirector\Database */
168
-    public function getTrapsDB()
169
-    {
170
-        return $this->trapsDB;
171
-    }
167
+	/** @return \Trapdirector\Database */
168
+	public function getTrapsDB()
169
+	{
170
+		return $this->trapsDB;
171
+	}
172 172
     
173
-    /** OBSOLETE Send log. Throws exception on critical error
174
-     *	@param	string $message Message to log
175
-     *	@param	int $level 1=critical 2=warning 3=trace 4=debug
176
-     *	@param  string $destination file/syslog/display
177
-     *	@return void
178
-     **/
179
-    public function trapLog( $message, $level, $destination ='') // OBSOLETE
180
-    {
181
-        // TODO : replace ref with $this->logging->log
182
-        $this->logging->log($message, $level, $destination);
183
-    }
173
+	/** OBSOLETE Send log. Throws exception on critical error
174
+	 *	@param	string $message Message to log
175
+	 *	@param	int $level 1=critical 2=warning 3=trace 4=debug
176
+	 *	@param  string $destination file/syslog/display
177
+	 *	@return void
178
+	 **/
179
+	public function trapLog( $message, $level, $destination ='') // OBSOLETE
180
+	{
181
+		// TODO : replace ref with $this->logging->log
182
+		$this->logging->log($message, $level, $destination);
183
+	}
184 184
     
185
-    public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
186
-    {
187
-        $this->logging->setLogging($debugLvl, $outputType,$outputOption);
188
-    }
185
+	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
186
+	{
187
+		$this->logging->setLogging($debugLvl, $outputType,$outputOption);
188
+	}
189 189
     
190
-    /**
191
-     * Returns or create new IcingaAPI object
192
-     * @return \Icinga\Module\Trapdirector\Icinga2API
193
-     */
194
-    protected function getAPI()
195
-    {
196
-        if ($this->icinga2api == null)
197
-        {
198
-            $this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
199
-        }
200
-        return $this->icinga2api;
201
-    }
190
+	/**
191
+	 * Returns or create new IcingaAPI object
192
+	 * @return \Icinga\Module\Trapdirector\Icinga2API
193
+	 */
194
+	protected function getAPI()
195
+	{
196
+		if ($this->icinga2api == null)
197
+		{
198
+			$this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
199
+		}
200
+		return $this->icinga2api;
201
+	}
202 202
     
203 203
     
204
-    /**
205
-     * read data from stream
206
-     *	@param $stream string input stream, defaults to "php://stdin"
207
-     *	@return mixed array trap data or exception with error
208
-     */
209
-    public function read_trap($stream='php://stdin')
210
-    {
211
-        //Read data from snmptrapd from stdin
212
-        $input_stream=fopen($stream, 'r');
213
-        
214
-        if ($input_stream === false)
215
-        {
216
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
217
-            $this->logging->log("Error reading stdin !",ERROR,'');
218
-            return null; // note : exception thrown by logging
219
-        }
220
-        
221
-        // line 1 : host
222
-        $this->receivingHost=chop(fgets($input_stream));
223
-        if ($this->receivingHost === false)
224
-        {
225
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
226
-            $this->logging->log("Error reading Host !",ERROR,'');
227
-        }
228
-        // line 2 IP:port=>IP:port
229
-        $IP=chop(fgets($input_stream));
230
-        if ($IP === false)
231
-        {
232
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
233
-            $this->logging->log("Error reading IP !",ERROR,'');
234
-        }
235
-        $matches=array();
236
-        $ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
237
-        if ($ret_code===0 || $ret_code===false)
238
-        {
239
-            $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
240
-            $this->logging->log('Error parsing IP : '.$IP,ERROR,'');
241
-        }
242
-        else
243
-        {
244
-            $this->trapData['source_ip']=$matches[1];
245
-            $this->trapData['destination_ip']=$matches[3];
246
-            $this->trapData['source_port']=$matches[2];
247
-            $this->trapData['destination_port']=$matches[4];
248
-        }
249
-        
250
-        while (($vars=fgets($input_stream)) !==false)
251
-        {
252
-            $vars=chop($vars);
253
-            $ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
254
-            if ($ret_code===0 || $ret_code===false)
255
-            {
256
-                $this->logging->log('No match on trap data : '.$vars,WARN,'');
257
-                continue;
258
-            }
259
-            if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
260
-            {
261
-                $this->trapData['trap_oid']=$matches[2];
262
-                continue;
263
-            }
264
-            if ( $this->useSnmpTrapAddess === TRUE &&  preg_match('/'.$this->snmpTrapAddressOID.'/', $matches[1]) == 1)
265
-            {
266
-                $this->logging->log('Found relayed trap from ' . $matches[2] . ' relayed by ' .$this->trapData['source_ip'],DEBUG);
267
-                if (preg_match('/^[0-9\.]+$/',$matches[2]) == 0 && preg_match('/^[0-9a-fA-F:]+$/',$matches[2]) == 0)
268
-                {
269
-                    $this->logging->log('Value of SnmpTrapAddess ('.$this->snmpTrapAddressOID.') is not IP : ' .$matches[2],WARN,'');
270
-                    continue;
271
-                }
272
-                $this->trapData['source_ip'] = $matches[2];
273
-                continue;
274
-            }
275
-            $object= new stdClass;
276
-            $object->oid =$matches[1];
277
-            $object->value = $matches[2];
278
-            array_push($this->trapDataExt,$object);
279
-        }
280
-        
281
-        if ($this->trapData['trap_oid']=='unknown')
282
-        {
283
-            $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trapData['source_ip']);
284
-            $this->logging->log('no trap oid found',ERROR,'');
285
-        }
286
-        
287
-        // Translate oids.
288
-        
289
-        $retArray=$this->translateOID($this->trapData['trap_oid']);
290
-        if ($retArray != null)
291
-        {
292
-            $this->trapData['trap_name']=$retArray['trap_name'];
293
-            $this->trapData['trap_name_mib']=$retArray['trap_name_mib'];
294
-        }
295
-        foreach ($this->trapDataExt as $key => $val)
296
-        {
297
-            $retArray=$this->translateOID($val->oid);
298
-            if ($retArray != null)
299
-            {
300
-                $this->trapDataExt[$key]->oid_name=$retArray['trap_name'];
301
-                $this->trapDataExt[$key]->oid_name_mib=$retArray['trap_name_mib'];
302
-            }
303
-        }
304
-        
305
-        
306
-        $this->trapData['status']= 'waiting';
307
-        
308
-        return $this->trapData;
309
-    }
204
+	/**
205
+	 * read data from stream
206
+	 *	@param $stream string input stream, defaults to "php://stdin"
207
+	 *	@return mixed array trap data or exception with error
208
+	 */
209
+	public function read_trap($stream='php://stdin')
210
+	{
211
+		//Read data from snmptrapd from stdin
212
+		$input_stream=fopen($stream, 'r');
213
+        
214
+		if ($input_stream === false)
215
+		{
216
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
217
+			$this->logging->log("Error reading stdin !",ERROR,'');
218
+			return null; // note : exception thrown by logging
219
+		}
220
+        
221
+		// line 1 : host
222
+		$this->receivingHost=chop(fgets($input_stream));
223
+		if ($this->receivingHost === false)
224
+		{
225
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
226
+			$this->logging->log("Error reading Host !",ERROR,'');
227
+		}
228
+		// line 2 IP:port=>IP:port
229
+		$IP=chop(fgets($input_stream));
230
+		if ($IP === false)
231
+		{
232
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
233
+			$this->logging->log("Error reading IP !",ERROR,'');
234
+		}
235
+		$matches=array();
236
+		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
237
+		if ($ret_code===0 || $ret_code===false)
238
+		{
239
+			$this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
240
+			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
241
+		}
242
+		else
243
+		{
244
+			$this->trapData['source_ip']=$matches[1];
245
+			$this->trapData['destination_ip']=$matches[3];
246
+			$this->trapData['source_port']=$matches[2];
247
+			$this->trapData['destination_port']=$matches[4];
248
+		}
249
+        
250
+		while (($vars=fgets($input_stream)) !==false)
251
+		{
252
+			$vars=chop($vars);
253
+			$ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
254
+			if ($ret_code===0 || $ret_code===false)
255
+			{
256
+				$this->logging->log('No match on trap data : '.$vars,WARN,'');
257
+				continue;
258
+			}
259
+			if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
260
+			{
261
+				$this->trapData['trap_oid']=$matches[2];
262
+				continue;
263
+			}
264
+			if ( $this->useSnmpTrapAddess === TRUE &&  preg_match('/'.$this->snmpTrapAddressOID.'/', $matches[1]) == 1)
265
+			{
266
+				$this->logging->log('Found relayed trap from ' . $matches[2] . ' relayed by ' .$this->trapData['source_ip'],DEBUG);
267
+				if (preg_match('/^[0-9\.]+$/',$matches[2]) == 0 && preg_match('/^[0-9a-fA-F:]+$/',$matches[2]) == 0)
268
+				{
269
+					$this->logging->log('Value of SnmpTrapAddess ('.$this->snmpTrapAddressOID.') is not IP : ' .$matches[2],WARN,'');
270
+					continue;
271
+				}
272
+				$this->trapData['source_ip'] = $matches[2];
273
+				continue;
274
+			}
275
+			$object= new stdClass;
276
+			$object->oid =$matches[1];
277
+			$object->value = $matches[2];
278
+			array_push($this->trapDataExt,$object);
279
+		}
280
+        
281
+		if ($this->trapData['trap_oid']=='unknown')
282
+		{
283
+			$this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trapData['source_ip']);
284
+			$this->logging->log('no trap oid found',ERROR,'');
285
+		}
286
+        
287
+		// Translate oids.
288
+        
289
+		$retArray=$this->translateOID($this->trapData['trap_oid']);
290
+		if ($retArray != null)
291
+		{
292
+			$this->trapData['trap_name']=$retArray['trap_name'];
293
+			$this->trapData['trap_name_mib']=$retArray['trap_name_mib'];
294
+		}
295
+		foreach ($this->trapDataExt as $key => $val)
296
+		{
297
+			$retArray=$this->translateOID($val->oid);
298
+			if ($retArray != null)
299
+			{
300
+				$this->trapDataExt[$key]->oid_name=$retArray['trap_name'];
301
+				$this->trapDataExt[$key]->oid_name_mib=$retArray['trap_name_mib'];
302
+			}
303
+		}
304
+        
305
+        
306
+		$this->trapData['status']= 'waiting';
307
+        
308
+		return $this->trapData;
309
+	}
310 310
     
311
-    /**
312
-     * Translate oid into array(MIB,Name)
313
-     * @param $oid string oid to translate
314
-     * @return mixed : null if not found or array(MIB,Name)
315
-     */
316
-    public function translateOID($oid)
317
-    {
318
-        // try from database
319
-        $db_conn=$this->trapsDB->db_connect_trap();
320
-        
321
-        $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
322
-        $this->logging->log('SQL query : '.$sql,DEBUG );
323
-        if (($ret_code=$db_conn->query($sql)) === false) {
324
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
325
-        }
326
-        else {
327
-            if (($name=$ret_code->fetch()) !== false)
328
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
329
-        }
330
-        
331
-        // Also check if it is an instance of OID
332
-        $oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
333
-        
334
-        $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
335
-        $this->logging->log('SQL query : '.$sql,DEBUG );
336
-        if (($ret_code=$db_conn->query($sql)) === false) {
337
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
338
-        }
339
-        else {
340
-            if (($name=$ret_code->fetch()) !== false)
341
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
342
-        }
343
-        
344
-        // Try to get oid name from snmptranslate
345
-        $translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
346
-            ' '.$oid);
347
-        $matches=array();
348
-        $ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
349
-        if ($ret_code===0 || $ret_code === false) {
350
-            return NULL;
351
-        } else {
352
-            $this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
353
-            return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
354
-        }
355
-    }
311
+	/**
312
+	 * Translate oid into array(MIB,Name)
313
+	 * @param $oid string oid to translate
314
+	 * @return mixed : null if not found or array(MIB,Name)
315
+	 */
316
+	public function translateOID($oid)
317
+	{
318
+		// try from database
319
+		$db_conn=$this->trapsDB->db_connect_trap();
320
+        
321
+		$sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
322
+		$this->logging->log('SQL query : '.$sql,DEBUG );
323
+		if (($ret_code=$db_conn->query($sql)) === false) {
324
+			$this->logging->log('No result in query : ' . $sql,ERROR,'');
325
+		}
326
+		else {
327
+			if (($name=$ret_code->fetch()) !== false)
328
+				return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
329
+		}
330
+        
331
+		// Also check if it is an instance of OID
332
+		$oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
333
+        
334
+		$sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
335
+		$this->logging->log('SQL query : '.$sql,DEBUG );
336
+		if (($ret_code=$db_conn->query($sql)) === false) {
337
+			$this->logging->log('No result in query : ' . $sql,ERROR,'');
338
+		}
339
+		else {
340
+			if (($name=$ret_code->fetch()) !== false)
341
+				return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
342
+		}
343
+        
344
+		// Try to get oid name from snmptranslate
345
+		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
346
+			' '.$oid);
347
+		$matches=array();
348
+		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
349
+		if ($ret_code===0 || $ret_code === false) {
350
+			return NULL;
351
+		} else {
352
+			$this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
353
+			return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
354
+		}
355
+	}
356 356
     
357
-    /**
358
-     * Erase old trap records
359
-     *	@param integer $days : erase traps when more than $days old
360
-     *	@return integer : number of lines deleted
361
-     **/
362
-    public function eraseOldTraps($days=0)
363
-    {
364
-        if ($days==0)
365
-        {
366
-            if (($days=$this->getDBConfig('db_remove_days')) == null)
367
-            {
368
-                $this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
369
-                return;
370
-            }
371
-        }
372
-        $db_conn=$this->trapsDB->db_connect_trap();
373
-        $daysago = strtotime("-".$days." day");
374
-        $sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
375
-        if ($db_conn->query($sql) === false) {
376
-            $this->logging->log('Error erasing traps : '.$sql,ERROR,'');
377
-        }
378
-        $this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
379
-    }
357
+	/**
358
+	 * Erase old trap records
359
+	 *	@param integer $days : erase traps when more than $days old
360
+	 *	@return integer : number of lines deleted
361
+	 **/
362
+	public function eraseOldTraps($days=0)
363
+	{
364
+		if ($days==0)
365
+		{
366
+			if (($days=$this->getDBConfig('db_remove_days')) == null)
367
+			{
368
+				$this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
369
+				return;
370
+			}
371
+		}
372
+		$db_conn=$this->trapsDB->db_connect_trap();
373
+		$daysago = strtotime("-".$days." day");
374
+		$sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
375
+		if ($db_conn->query($sql) === false) {
376
+			$this->logging->log('Error erasing traps : '.$sql,ERROR,'');
377
+		}
378
+		$this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
379
+	}
380 380
     
381
-    /** Write error to received trap database
382
-     */
383
-    public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
384
-    {
385
-        
386
-        $db_conn=$this->trapsDB->db_connect_trap();
387
-        
388
-        // add date time
389
-        $insert_col ='date_received,status';
390
-        $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
391
-        
392
-        if ($sourceIP !=null)
393
-        {
394
-            $insert_col .=',source_ip';
395
-            $insert_val .=",'". $sourceIP ."'";
396
-        }
397
-        if ($trapoid !=null)
398
-        {
399
-            $insert_col .=',trap_oid';
400
-            $insert_val .=",'". $trapoid ."'";
401
-        }
402
-        $insert_col .=',status_detail';
403
-        $insert_val .=",'". $message ."'";
404
-        
405
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
406
-        
407
-        switch ($this->trapsDB->trapDBType)
408
-        {
409
-            case 'pgsql':
410
-                $sql .= ' RETURNING id;';
411
-                $this->logging->log('sql : '.$sql,INFO);
412
-                if (($ret_code=$db_conn->query($sql)) === false) {
413
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
414
-                }
415
-                $this->logging->log('SQL insertion OK',INFO );
416
-                // Get last id to insert oid/values in secondary table
417
-                if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
381
+	/** Write error to received trap database
382
+	 */
383
+	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
384
+	{
385
+        
386
+		$db_conn=$this->trapsDB->db_connect_trap();
387
+        
388
+		// add date time
389
+		$insert_col ='date_received,status';
390
+		$insert_val = "'" . date("Y-m-d H:i:s")."','error'";
391
+        
392
+		if ($sourceIP !=null)
393
+		{
394
+			$insert_col .=',source_ip';
395
+			$insert_val .=",'". $sourceIP ."'";
396
+		}
397
+		if ($trapoid !=null)
398
+		{
399
+			$insert_col .=',trap_oid';
400
+			$insert_val .=",'". $trapoid ."'";
401
+		}
402
+		$insert_col .=',status_detail';
403
+		$insert_val .=",'". $message ."'";
404
+        
405
+		$sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
406
+        
407
+		switch ($this->trapsDB->trapDBType)
408
+		{
409
+			case 'pgsql':
410
+				$sql .= ' RETURNING id;';
411
+				$this->logging->log('sql : '.$sql,INFO);
412
+				if (($ret_code=$db_conn->query($sql)) === false) {
413
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
414
+				}
415
+				$this->logging->log('SQL insertion OK',INFO );
416
+				// Get last id to insert oid/values in secondary table
417
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
418 418
                     
419
-                    $this->logging->log('Erreur recuperation id',1,'');
420
-                }
421
-                if (! isset($inserted_id_ret['id'])) {
422
-                    $this->logging->log('Error getting id',1,'');
423
-                }
424
-                $this->trapId=$inserted_id_ret['id'];
425
-                break;
426
-            case 'mysql':
427
-                $sql .= ';';
428
-                $this->logging->log('sql : '.$sql,INFO );
429
-                if ($db_conn->query($sql) === false) {
430
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
431
-                }
432
-                $this->logging->log('SQL insertion OK',INFO );
433
-                // Get last id to insert oid/values in secondary table
434
-                $sql='SELECT LAST_INSERT_ID();';
435
-                if (($ret_code=$db_conn->query($sql)) === false) {
436
-                    $this->logging->log('Erreur recuperation id',1,'');
437
-                }
419
+					$this->logging->log('Erreur recuperation id',1,'');
420
+				}
421
+				if (! isset($inserted_id_ret['id'])) {
422
+					$this->logging->log('Error getting id',1,'');
423
+				}
424
+				$this->trapId=$inserted_id_ret['id'];
425
+				break;
426
+			case 'mysql':
427
+				$sql .= ';';
428
+				$this->logging->log('sql : '.$sql,INFO );
429
+				if ($db_conn->query($sql) === false) {
430
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
431
+				}
432
+				$this->logging->log('SQL insertion OK',INFO );
433
+				// Get last id to insert oid/values in secondary table
434
+				$sql='SELECT LAST_INSERT_ID();';
435
+				if (($ret_code=$db_conn->query($sql)) === false) {
436
+					$this->logging->log('Erreur recuperation id',1,'');
437
+				}
438 438
                 
439
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
440
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
441
-                $this->trapId=$inserted_id;
442
-                break;
443
-            default:
444
-                $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
445
-        }
446
-        
447
-        $this->logging->log('id found: '. $this->trapId,INFO );
448
-    }
439
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
440
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
441
+				$this->trapId=$inserted_id;
442
+				break;
443
+			default:
444
+				$this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
445
+		}
446
+        
447
+		$this->logging->log('id found: '. $this->trapId,INFO );
448
+	}
449 449
     
450
-    /** Write trap data to trap database
451
-     */
452
-    public function writeTrapToDB()
453
-    {
454
-        
455
-        // If action is ignore -> don't send t DB
456
-        if ($this->trapToDb === false) return;
457
-        
458
-        
459
-        $db_conn=$this->trapsDB->db_connect_trap();
460
-        
461
-        $insert_col='';
462
-        $insert_val='';
463
-        // add date time
464
-        $this->trapData['date_received'] = date("Y-m-d H:i:s");
465
-        
466
-        $firstcol=1;
467
-        foreach ($this->trapData as $col => $val)
468
-        {
469
-            if ($firstcol==0)
470
-            {
471
-                $insert_col .=',';
472
-                $insert_val .=',';
473
-            }
474
-            $insert_col .= $col ;
475
-            $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
476
-            $firstcol=0;
477
-        }
478
-        
479
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
480
-        switch ($this->trapsDB->trapDBType)
481
-        {
482
-            case 'pgsql':
483
-                $sql .= ' RETURNING id;';
484
-                $this->logging->log('sql : '.$sql,INFO );
485
-                if (($ret_code=$db_conn->query($sql)) === false) {
486
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
487
-                }
488
-                $this->logging->log('SQL insertion OK',INFO );
489
-                // Get last id to insert oid/values in secondary table
490
-                if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
450
+	/** Write trap data to trap database
451
+	 */
452
+	public function writeTrapToDB()
453
+	{
454
+        
455
+		// If action is ignore -> don't send t DB
456
+		if ($this->trapToDb === false) return;
457
+        
458
+        
459
+		$db_conn=$this->trapsDB->db_connect_trap();
460
+        
461
+		$insert_col='';
462
+		$insert_val='';
463
+		// add date time
464
+		$this->trapData['date_received'] = date("Y-m-d H:i:s");
465
+        
466
+		$firstcol=1;
467
+		foreach ($this->trapData as $col => $val)
468
+		{
469
+			if ($firstcol==0)
470
+			{
471
+				$insert_col .=',';
472
+				$insert_val .=',';
473
+			}
474
+			$insert_col .= $col ;
475
+			$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
476
+			$firstcol=0;
477
+		}
478
+        
479
+		$sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
480
+		switch ($this->trapsDB->trapDBType)
481
+		{
482
+			case 'pgsql':
483
+				$sql .= ' RETURNING id;';
484
+				$this->logging->log('sql : '.$sql,INFO );
485
+				if (($ret_code=$db_conn->query($sql)) === false) {
486
+					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
487
+				}
488
+				$this->logging->log('SQL insertion OK',INFO );
489
+				// Get last id to insert oid/values in secondary table
490
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
491 491
                     
492
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
493
-                }
494
-                if (! isset($inserted_id_ret['id'])) {
495
-                    $this->logging->log('Error getting id',ERROR,'');
496
-                }
497
-                $this->trapId=$inserted_id_ret['id'];
498
-                break;
499
-            case 'mysql':
500
-                $sql .= ';';
501
-                $this->logging->log('sql : '.$sql,INFO );
502
-                if ($db_conn->query($sql) === false) {
503
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
504
-                }
505
-                $this->logging->log('SQL insertion OK',INFO );
506
-                // Get last id to insert oid/values in secondary table
507
-                $sql='SELECT LAST_INSERT_ID();';
508
-                if (($ret_code=$db_conn->query($sql)) === false) {
509
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
510
-                }
492
+					$this->logging->log('Erreur recuperation id',ERROR,'');
493
+				}
494
+				if (! isset($inserted_id_ret['id'])) {
495
+					$this->logging->log('Error getting id',ERROR,'');
496
+				}
497
+				$this->trapId=$inserted_id_ret['id'];
498
+				break;
499
+			case 'mysql':
500
+				$sql .= ';';
501
+				$this->logging->log('sql : '.$sql,INFO );
502
+				if ($db_conn->query($sql) === false) {
503
+					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
504
+				}
505
+				$this->logging->log('SQL insertion OK',INFO );
506
+				// Get last id to insert oid/values in secondary table
507
+				$sql='SELECT LAST_INSERT_ID();';
508
+				if (($ret_code=$db_conn->query($sql)) === false) {
509
+					$this->logging->log('Erreur recuperation id',ERROR,'');
510
+				}
511 511
                 
512
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
513
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
514
-                $this->trapId=$inserted_id;
515
-                break;
516
-            default:
517
-                $this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
518
-        }
519
-        $this->logging->log('id found: '.$this->trapId,INFO );
520
-        
521
-        // Fill trap extended data table
522
-        foreach ($this->trapDataExt as $value) {
523
-            // TODO : detect if trap value is encoded and decode it to UTF-8 for database
524
-            $firstcol=1;
525
-            $value->trap_id = $this->trapId;
526
-            $insert_col='';
527
-            $insert_val='';
528
-            foreach ($value as $col => $val)
529
-            {
530
-                if ($firstcol==0)
531
-                {
532
-                    $insert_col .=',';
533
-                    $insert_val .=',';
534
-                }
535
-                $insert_col .= $col;
536
-                $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
537
-                $firstcol=0;
538
-            }
512
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
513
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
514
+				$this->trapId=$inserted_id;
515
+				break;
516
+			default:
517
+				$this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
518
+		}
519
+		$this->logging->log('id found: '.$this->trapId,INFO );
520
+        
521
+		// Fill trap extended data table
522
+		foreach ($this->trapDataExt as $value) {
523
+			// TODO : detect if trap value is encoded and decode it to UTF-8 for database
524
+			$firstcol=1;
525
+			$value->trap_id = $this->trapId;
526
+			$insert_col='';
527
+			$insert_val='';
528
+			foreach ($value as $col => $val)
529
+			{
530
+				if ($firstcol==0)
531
+				{
532
+					$insert_col .=',';
533
+					$insert_val .=',';
534
+				}
535
+				$insert_col .= $col;
536
+				$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
537
+				$firstcol=0;
538
+			}
539 539
             
540
-            $sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
540
+			$sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
541 541
             
542
-            if ($db_conn->query($sql) === false) {
543
-                $this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
544
-            }
545
-        }
546
-    }
542
+			if ($db_conn->query($sql) === false) {
543
+				$this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
544
+			}
545
+		}
546
+	}
547 547
     
548
-    /** Get rules from rule database with ip and oid
549
-     *	@param $ip string ipv4 or ipv6
550
-     *	@param $oid string oid in numeric
551
-     *	@return mixed|boolean : PDO object or false
552
-     */
553
-    protected function getRules($ip,$oid)
554
-    {
555
-        $db_conn=$this->trapsDB->db_connect_trap();
556
-        // fetch rules based on IP in rule and OID
557
-        $sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
558
-        $this->logging->log('SQL query : '.$sql,DEBUG );
559
-        if (($ret_code=$db_conn->query($sql)) === false) {
560
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
561
-            return false;
562
-        }
563
-        $rules_all=$ret_code->fetchAll();
564
-        //echo "rule all :\n";print_r($rules_all);echo "\n";
565
-        $rules_ret=array();
566
-        $rule_ret_key=0;
567
-        foreach ($rules_all as $key => $rule)
568
-        {
569
-            if ($rule['ip4']==$ip || $rule['ip6']==$ip)
570
-            {
571
-                $rules_ret[$rule_ret_key]=$rules_all[$key];
572
-                //TODO : get host name by API (and check if correct in rule).
573
-                $rule_ret_key++;
574
-                continue;
575
-            }
548
+	/** Get rules from rule database with ip and oid
549
+	 *	@param $ip string ipv4 or ipv6
550
+	 *	@param $oid string oid in numeric
551
+	 *	@return mixed|boolean : PDO object or false
552
+	 */
553
+	protected function getRules($ip,$oid)
554
+	{
555
+		$db_conn=$this->trapsDB->db_connect_trap();
556
+		// fetch rules based on IP in rule and OID
557
+		$sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
558
+		$this->logging->log('SQL query : '.$sql,DEBUG );
559
+		if (($ret_code=$db_conn->query($sql)) === false) {
560
+			$this->logging->log('No result in query : ' . $sql,WARN,'');
561
+			return false;
562
+		}
563
+		$rules_all=$ret_code->fetchAll();
564
+		//echo "rule all :\n";print_r($rules_all);echo "\n";
565
+		$rules_ret=array();
566
+		$rule_ret_key=0;
567
+		foreach ($rules_all as $key => $rule)
568
+		{
569
+			if ($rule['ip4']==$ip || $rule['ip6']==$ip)
570
+			{
571
+				$rules_ret[$rule_ret_key]=$rules_all[$key];
572
+				//TODO : get host name by API (and check if correct in rule).
573
+				$rule_ret_key++;
574
+				continue;
575
+			}
576 576
 
577
-            if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
578
-            { // get ips of group members by oid
579
-                if ($this->apiUse === false)
580
-                {
581
-                    $db_conn2=$this->trapsDB->db_connect_ido();
582
-                    $sql="SELECT m.host_object_id, a.address, a.address6, b.name1 as name
577
+			if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
578
+			{ // get ips of group members by oid
579
+				if ($this->apiUse === false)
580
+				{
581
+					$db_conn2=$this->trapsDB->db_connect_ido();
582
+					$sql="SELECT m.host_object_id, a.address, a.address6, b.name1 as name
583 583
 						FROM icinga_objects as o
584 584
 						LEFT JOIN icinga_hostgroups as h ON o.object_id=h.hostgroup_object_id
585 585
 						LEFT JOIN icinga_hostgroup_members as m ON h.hostgroup_id=m.hostgroup_id
586 586
 						LEFT JOIN icinga_hosts as a ON a.host_object_id = m.host_object_id
587 587
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
588 588
 						WHERE o.name1='".$rule['host_group_name']."';";
589
-                    if (($ret_code2=$db_conn2->query($sql)) === false) {
590
-                        $this->logging->log('No result in query : ' . $sql,WARN,'');
591
-                        continue;
592
-                    }
593
-                    $grouphosts=$ret_code2->fetchAll();
594
-                }else{
595
-                    $api = $this->getAPI();
596
-                    $api->setCredentials($this->apiUsername, $this->apiPassword);
597
-                    $grouphosts=$api->getHostsIPByHostGroup($rule['host_group_name']);
598
-                }
599
-                //echo "rule grp :\n";print_r($grouphosts);echo "\n";
600
-                foreach ( $grouphosts as $host)
601
-                {
602
-                    if( is_object( $host ) ) $host=(array)$host;
603
-                    //echo $host['address']."\n";
604
-                    if ($host['address']==$ip || $host['address6']==$ip)
605
-                    {
606
-                        //echo "Rule added \n";
607
-                        $rules_ret[$rule_ret_key]=$rules_all[$key];
608
-                        $rules_ret[$rule_ret_key]['host_name']=$host['name'];
609
-                        $rule_ret_key++;
610
-                    }
611
-                }
612
-            }
589
+					if (($ret_code2=$db_conn2->query($sql)) === false) {
590
+						$this->logging->log('No result in query : ' . $sql,WARN,'');
591
+						continue;
592
+					}
593
+					$grouphosts=$ret_code2->fetchAll();
594
+				}else{
595
+					$api = $this->getAPI();
596
+					$api->setCredentials($this->apiUsername, $this->apiPassword);
597
+					$grouphosts=$api->getHostsIPByHostGroup($rule['host_group_name']);
598
+				}
599
+				//echo "rule grp :\n";print_r($grouphosts);echo "\n";
600
+				foreach ( $grouphosts as $host)
601
+				{
602
+					if( is_object( $host ) ) $host=(array)$host;
603
+					//echo $host['address']."\n";
604
+					if ($host['address']==$ip || $host['address6']==$ip)
605
+					{
606
+						//echo "Rule added \n";
607
+						$rules_ret[$rule_ret_key]=$rules_all[$key];
608
+						$rules_ret[$rule_ret_key]['host_name']=$host['name'];
609
+						$rule_ret_key++;
610
+					}
611
+				}
612
+			}
613 613
 
614
-        }
615
-        //echo "rule rest :\n";print_r($rules_ret);echo "\n";exit(0);
616
-        return $rules_ret;
617
-    }
614
+		}
615
+		//echo "rule rest :\n";print_r($rules_ret);echo "\n";exit(0);
616
+		return $rules_ret;
617
+	}
618 618
     
619
-    /** Add rule match to rule
620
-     *	@param id int : rule id
621
-     *   @param set int : value to set
622
-     */
623
-    protected function add_rule_match($id, $set)
624
-    {
625
-        $db_conn=$this->trapsDB->db_connect_trap();
626
-        $sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
627
-        if ($db_conn->query($sql) === false) {
628
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
629
-        }
630
-    }
619
+	/** Add rule match to rule
620
+	 *	@param id int : rule id
621
+	 *   @param set int : value to set
622
+	 */
623
+	protected function add_rule_match($id, $set)
624
+	{
625
+		$db_conn=$this->trapsDB->db_connect_trap();
626
+		$sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
627
+		if ($db_conn->query($sql) === false) {
628
+			$this->logging->log('Error in update query : ' . $sql,WARN,'');
629
+		}
630
+	}
631 631
     
632
-    /** Send SERVICE_CHECK_RESULT with icinga2cmd or API
633
-     *
634
-     * @param string $host
635
-     * @param string $service
636
-     * @param integer $state numerical staus
637
-     * @param string $display
638
-     * @returnn bool true is service check was sent without error
639
-     */
640
-    public function serviceCheckResult($host,$service,$state,$display)
641
-    {
642
-        if ($this->apiUse === false)
643
-        {
644
-            $send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
645
-                $host.';' .$service .';' . $state . ';'.$display;
646
-                $this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
632
+	/** Send SERVICE_CHECK_RESULT with icinga2cmd or API
633
+	 *
634
+	 * @param string $host
635
+	 * @param string $service
636
+	 * @param integer $state numerical staus
637
+	 * @param string $display
638
+	 * @returnn bool true is service check was sent without error
639
+	 */
640
+	public function serviceCheckResult($host,$service,$state,$display)
641
+	{
642
+		if ($this->apiUse === false)
643
+		{
644
+			$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
645
+				$host.';' .$service .';' . $state . ';'.$display;
646
+				$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
647 647
                 
648
-                // TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
649
-                exec('echo "'.$send.'" > ' .$this->icinga2cmd);
650
-                return true;
651
-        }
652
-        else
653
-        {
654
-            // Get perfdata if found
655
-            $matches=array();
656
-            if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
657
-            {
658
-                $display=$matches[1];
659
-                $perfdata=$matches[2];
660
-            }
661
-            else
662
-            {
663
-                $perfdata='';
664
-            }
648
+				// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
649
+				exec('echo "'.$send.'" > ' .$this->icinga2cmd);
650
+				return true;
651
+		}
652
+		else
653
+		{
654
+			// Get perfdata if found
655
+			$matches=array();
656
+			if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
657
+			{
658
+				$display=$matches[1];
659
+				$perfdata=$matches[2];
660
+			}
661
+			else
662
+			{
663
+				$perfdata='';
664
+			}
665 665
             
666
-            $api = $this->getAPI();
667
-            $api->setCredentials($this->apiUsername, $this->apiPassword);
668
-            list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
669
-            if ($retcode == false)
670
-            {
671
-                $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
672
-                return false;
673
-            }
674
-            else
675
-            {
676
-                $this->logging->log( "Sent result : " .$retmessage,INFO );
677
-                return true;
678
-            }
679
-        }
680
-    }
666
+			$api = $this->getAPI();
667
+			$api->setCredentials($this->apiUsername, $this->apiPassword);
668
+			list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
669
+			if ($retcode == false)
670
+			{
671
+				$this->logging->log( "Error sending result : " .$retmessage,WARN,'');
672
+				return false;
673
+			}
674
+			else
675
+			{
676
+				$this->logging->log( "Sent result : " .$retmessage,INFO );
677
+				return true;
678
+			}
679
+		}
680
+	}
681 681
     
682
-    public function getHostByIP($ip)
683
-    {
684
-        $api = $this->getAPI();
685
-        $api->setCredentials($this->apiUsername, $this->apiPassword);
686
-        return $api->getHostByIP($ip);
687
-    }
682
+	public function getHostByIP($ip)
683
+	{
684
+		$api = $this->getAPI();
685
+		$api->setCredentials($this->apiUsername, $this->apiPassword);
686
+		return $api->getHostByIP($ip);
687
+	}
688 688
     
689
-    /** Resolve display.
690
-     *	Changes _OID(<oid>) to value if found or text "<not in trap>"
691
-     *	@param $display string
692
-     *	@return string display
693
-     */
694
-    protected function applyDisplay($display)
695
-    {
696
-        $matches=array();
697
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$display,$matches) == 1)
698
-        {
699
-            $oid=$matches[1];
700
-            $found=0;
701
-            // Test and transform regexp
702
-            $oidR = $this->ruleClass->regexp_eval($oid);
689
+	/** Resolve display.
690
+	 *	Changes _OID(<oid>) to value if found or text "<not in trap>"
691
+	 *	@param $display string
692
+	 *	@return string display
693
+	 */
694
+	protected function applyDisplay($display)
695
+	{
696
+		$matches=array();
697
+		while (preg_match('/_OID\(([0-9\.\*]+)\)/',$display,$matches) == 1)
698
+		{
699
+			$oid=$matches[1];
700
+			$found=0;
701
+			// Test and transform regexp
702
+			$oidR = $this->ruleClass->regexp_eval($oid);
703 703
             
704
-            foreach($this->trapDataExt as $val)
705
-            {
706
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
707
-                {
708
-                    $val->value=preg_replace('/"/','',$val->value);
709
-                    $rep=0;
710
-                    $display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
711
-                    if ($rep==0)
712
-                    {
713
-                        $this->logging->log("Error in display",WARN,'');
714
-                        return $display;
715
-                    }
716
-                    $found=1;
717
-                    break;
718
-                }
719
-            }
720
-            if ($found==0)
721
-            {
722
-                $display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
723
-                if ($rep==0)
724
-                {
725
-                    $this->logging->log("Error in display",WARN,'');
726
-                    return $display;
727
-                }
728
-            }
729
-        }
730
-        return $display;
731
-    }
704
+			foreach($this->trapDataExt as $val)
705
+			{
706
+				if (preg_match("/^$oidR$/",$val->oid) == 1)
707
+				{
708
+					$val->value=preg_replace('/"/','',$val->value);
709
+					$rep=0;
710
+					$display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
711
+					if ($rep==0)
712
+					{
713
+						$this->logging->log("Error in display",WARN,'');
714
+						return $display;
715
+					}
716
+					$found=1;
717
+					break;
718
+				}
719
+			}
720
+			if ($found==0)
721
+			{
722
+				$display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
723
+				if ($rep==0)
724
+				{
725
+					$this->logging->log("Error in display",WARN,'');
726
+					return $display;
727
+				}
728
+			}
729
+		}
730
+		return $display;
731
+	}
732 732
     
733
-    /** Match rules for current trap and do action
734
-     */
735
-    public function applyRules()
736
-    {
737
-        $rules = $this->getRules($this->trapData['source_ip'],$this->trapData['trap_oid']);
738
-        
739
-        if ($rules===false || count($rules)==0)
740
-        {
741
-            $this->logging->log('No rules found for this trap',INFO );
742
-            $this->trapData['status']='unknown';
743
-            $this->trapToDb=true;
744
-            return;
745
-        }
746
-        //print_r($rules);
747
-        // Evaluate all rules in sequence
748
-        $this->trapAction=null;
749
-        foreach ($rules as $rule)
750
-        {
733
+	/** Match rules for current trap and do action
734
+	 */
735
+	public function applyRules()
736
+	{
737
+		$rules = $this->getRules($this->trapData['source_ip'],$this->trapData['trap_oid']);
738
+        
739
+		if ($rules===false || count($rules)==0)
740
+		{
741
+			$this->logging->log('No rules found for this trap',INFO );
742
+			$this->trapData['status']='unknown';
743
+			$this->trapToDb=true;
744
+			return;
745
+		}
746
+		//print_r($rules);
747
+		// Evaluate all rules in sequence
748
+		$this->trapAction=null;
749
+		foreach ($rules as $rule)
750
+		{
751 751
             
752
-            $host_name=$rule['host_name'];
753
-            $service_name=$rule['service_name'];
752
+			$host_name=$rule['host_name'];
753
+			$service_name=$rule['service_name'];
754 754
             
755
-            $display=$this->applyDisplay($rule['display']);
756
-            $this->trapAction = ($this->trapAction==null)? '' : $this->trapAction . ', ';
757
-            try
758
-            {
759
-                $this->logging->log('Rule to eval : '.$rule['rule'],INFO );
760
-                $evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt) ;
761
-                //->eval_rule($rule['rule']);
755
+			$display=$this->applyDisplay($rule['display']);
756
+			$this->trapAction = ($this->trapAction==null)? '' : $this->trapAction . ', ';
757
+			try
758
+			{
759
+				$this->logging->log('Rule to eval : '.$rule['rule'],INFO );
760
+				$evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt) ;
761
+				//->eval_rule($rule['rule']);
762 762
                 
763
-                if ($evalr == true)
764
-                {
765
-                    //$this->logging->log('rules OOK: '.print_r($rule),INFO );
766
-                    $action=$rule['action_match'];
767
-                    $this->logging->log('action OK : '.$action,INFO );
768
-                    if ($action >= 0)
769
-                    {
770
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
771
-                        {
772
-                            $this->trapAction.='Error sending status : check cmd/API';
773
-                        }
774
-                        else
775
-                        {
776
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
777
-                            $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
778
-                        }
779
-                    }
780
-                    else
781
-                    {
782
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
783
-                    }
784
-                    $this->trapToDb=($action==-2)?false:true;
785
-                }
786
-                else
787
-                {
788
-                    //$this->logging->log('rules KOO : '.print_r($rule),INFO );
763
+				if ($evalr == true)
764
+				{
765
+					//$this->logging->log('rules OOK: '.print_r($rule),INFO );
766
+					$action=$rule['action_match'];
767
+					$this->logging->log('action OK : '.$action,INFO );
768
+					if ($action >= 0)
769
+					{
770
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
771
+						{
772
+							$this->trapAction.='Error sending status : check cmd/API';
773
+						}
774
+						else
775
+						{
776
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
777
+							$this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
778
+						}
779
+					}
780
+					else
781
+					{
782
+						$this->add_rule_match($rule['id'],$rule['num_match']+1);
783
+					}
784
+					$this->trapToDb=($action==-2)?false:true;
785
+				}
786
+				else
787
+				{
788
+					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
789 789
                     
790
-                    $action=$rule['action_nomatch'];
791
-                    $this->logging->log('action NOK : '.$action,INFO );
792
-                    if ($action >= 0)
793
-                    {
794
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
795
-                        {
796
-                            $this->trapAction.='Error sending status : check cmd/API';
797
-                        }
798
-                        else
799
-                        {
800
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
801
-                            $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
802
-                        }
803
-                    }
804
-                    else
805
-                    {
806
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
807
-                    }
808
-                    $this->trapToDb=($action==-2)?false:true;
809
-                }
810
-                // Put name in source_name
811
-                if (!isset($this->trapData['source_name']))
812
-                {
813
-                    $this->trapData['source_name']=$rule['host_name'];
814
-                }
815
-                else
816
-                {
817
-                    if (!preg_match('/'.$rule['host_name'].'/',$this->trapData['source_name']))
818
-                    { // only add if not present
819
-                        $this->trapData['source_name'].=','.$rule['host_name'];
820
-                    }
821
-                }
822
-            }
823
-            catch (Exception $e)
824
-            {
825
-                $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
826
-                $this->trapAction.=' ERR : '.$e->getMessage();
827
-                $this->trapData['status']='error';
828
-            }
790
+					$action=$rule['action_nomatch'];
791
+					$this->logging->log('action NOK : '.$action,INFO );
792
+					if ($action >= 0)
793
+					{
794
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
795
+						{
796
+							$this->trapAction.='Error sending status : check cmd/API';
797
+						}
798
+						else
799
+						{
800
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
801
+							$this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
802
+						}
803
+					}
804
+					else
805
+					{
806
+						$this->add_rule_match($rule['id'],$rule['num_match']+1);
807
+					}
808
+					$this->trapToDb=($action==-2)?false:true;
809
+				}
810
+				// Put name in source_name
811
+				if (!isset($this->trapData['source_name']))
812
+				{
813
+					$this->trapData['source_name']=$rule['host_name'];
814
+				}
815
+				else
816
+				{
817
+					if (!preg_match('/'.$rule['host_name'].'/',$this->trapData['source_name']))
818
+					{ // only add if not present
819
+						$this->trapData['source_name'].=','.$rule['host_name'];
820
+					}
821
+				}
822
+			}
823
+			catch (Exception $e)
824
+			{
825
+				$this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
826
+				$this->trapAction.=' ERR : '.$e->getMessage();
827
+				$this->trapData['status']='error';
828
+			}
829 829
             
830
-        }
831
-        if ($this->trapData['status']=='error')
832
-        {
833
-            $this->trapToDb=true; // Always put errors in DB for the use can see
834
-        }
835
-        else
836
-        {
837
-            $this->trapData['status']='done';
838
-        }
839
-    }
830
+		}
831
+		if ($this->trapData['status']=='error')
832
+		{
833
+			$this->trapToDb=true; // Always put errors in DB for the use can see
834
+		}
835
+		else
836
+		{
837
+			$this->trapData['status']='done';
838
+		}
839
+	}
840 840
     
841
-    /** Add Time a action to rule
842
-     *	@param string $time : time to process to insert in SQL
843
-     */
844
-    public function add_rule_final($time)
845
-    {
846
-        $db_conn=$this->trapsDB->db_connect_trap();
847
-        if ($this->trapAction==null)
848
-        {
849
-            $this->trapAction='No action';
850
-        }
851
-        $sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trapAction."'  WHERE (id = '".$this->trapId."');";
852
-        if ($db_conn->query($sql) === false) {
853
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
854
-        }
855
-    }
841
+	/** Add Time a action to rule
842
+	 *	@param string $time : time to process to insert in SQL
843
+	 */
844
+	public function add_rule_final($time)
845
+	{
846
+		$db_conn=$this->trapsDB->db_connect_trap();
847
+		if ($this->trapAction==null)
848
+		{
849
+			$this->trapAction='No action';
850
+		}
851
+		$sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trapAction."'  WHERE (id = '".$this->trapId."');";
852
+		if ($db_conn->query($sql) === false) {
853
+			$this->logging->log('Error in update query : ' . $sql,WARN,'');
854
+		}
855
+	}
856 856
     
857
-    /*********** UTILITIES *********************/
857
+	/*********** UTILITIES *********************/
858 858
     
859
-    /** reset service to OK after time defined in rule
860
-     *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better
861
-     *	@return integer : not in use
862
-     **/
863
-    public function reset_services()
864
-    {
865
-        // Get all services not in 'ok' state
866
-        if ($this->apiUse === false)
867
-        {
868
-            $sql_query="SELECT s.service_object_id,
859
+	/** reset service to OK after time defined in rule
860
+	 *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better
861
+	 *	@return integer : not in use
862
+	 **/
863
+	public function reset_services()
864
+	{
865
+		// Get all services not in 'ok' state
866
+		if ($this->apiUse === false)
867
+		{
868
+			$sql_query="SELECT s.service_object_id,
869 869
                                 UNIX_TIMESTAMP(s.last_check) AS last_check,
870 870
                                 s.current_state as state,
871 871
                                 v.name1 as host_name,
@@ -873,49 +873,49 @@  discard block
 block discarded – undo
873 873
                                 FROM icinga_servicestatus AS s
874 874
                                 LEFT JOIN icinga_objects as v ON s.service_object_id=v.object_id
875 875
                                 WHERE s.current_state != 0;";
876
-            $db_conn=$this->trapsDB->db_connect_ido();
877
-            if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
878
-                $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
879
-                return 0;
880
-            }
881
-            $services=$services_db->fetchAll();
882
-        }else{
883
-            $api = $this->getAPI();
884
-            $api->setCredentials($this->apiUsername, $this->apiPassword);
885
-            $services=$api->getNOKservice();
886
-        }
887
-        
888
-        // Get all rules
889
-        $sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
890
-        $db_conn2=$this->trapsDB->db_connect_trap();
891
-        if (($rules_db=$db_conn2->query($sql_query)) === false) {
892
-            $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
893
-            return 0;
894
-        }
895
-        $rules=$rules_db->fetchAll();
896
-        
897
-        $now=date('U');
898
-        
899
-        $numreset=0;
900
-        foreach ($rules as $rule)
901
-        {
902
-            if( is_object( $services ) ) $services=(array)$services;
903
-            foreach ($services as $service)
904
-            {
905
-                if ($service['name'] == $rule['service_name'] &&
906
-                    $service['host_name'] == $rule['host_name'] &&
907
-                    ($service['last_check'] + $rule['revert_ok']) < $now)
908
-                {
909
-                    $this->serviceCheckResult($service['host_name'],$service['name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
910
-                    $numreset++;
911
-                }
912
-            }
913
-        }
914
-        echo "\n";
915
-        echo $numreset . " service(s) reset to OK\n";
916
-        return 0;
917
-        
918
-    }
876
+			$db_conn=$this->trapsDB->db_connect_ido();
877
+			if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
878
+				$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
879
+				return 0;
880
+			}
881
+			$services=$services_db->fetchAll();
882
+		}else{
883
+			$api = $this->getAPI();
884
+			$api->setCredentials($this->apiUsername, $this->apiPassword);
885
+			$services=$api->getNOKservice();
886
+		}
887
+        
888
+		// Get all rules
889
+		$sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
890
+		$db_conn2=$this->trapsDB->db_connect_trap();
891
+		if (($rules_db=$db_conn2->query($sql_query)) === false) {
892
+			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
893
+			return 0;
894
+		}
895
+		$rules=$rules_db->fetchAll();
896
+        
897
+		$now=date('U');
898
+        
899
+		$numreset=0;
900
+		foreach ($rules as $rule)
901
+		{
902
+			if( is_object( $services ) ) $services=(array)$services;
903
+			foreach ($services as $service)
904
+			{
905
+				if ($service['name'] == $rule['service_name'] &&
906
+					$service['host_name'] == $rule['host_name'] &&
907
+					($service['last_check'] + $rule['revert_ok']) < $now)
908
+				{
909
+					$this->serviceCheckResult($service['host_name'],$service['name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
910
+					$numreset++;
911
+				}
912
+			}
913
+		}
914
+		echo "\n";
915
+		echo $numreset . " service(s) reset to OK\n";
916
+		return 0;
917
+        
918
+	}
919 919
     
920 920
     
921 921
 }
Please login to merge, or discard this patch.