Passed
Pull Request — master (#78)
by
unknown
03:51
created
application/controllers/StatusController.php 1 patch
Spacing   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -21,19 +21,19 @@  discard block
 block discarded – undo
21 21
 		/************  Trapdb ***********/
22 22
 		try
23 23
 		{
24
-		    $dbConn = $this->getUIDatabase()->getDbConn();
24
+		    $dbConn=$this->getUIDatabase()->getDbConn();
25 25
 		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
26
-			$query = $dbConn->select()->from(
26
+			$query=$dbConn->select()->from(
27 27
 				$this->getModuleConfig()->getTrapTableName(),
28 28
 				array('COUNT(*)')
29 29
 			);			
30 30
 			$this->view->trap_count=$dbConn->fetchOne($query);
31
-			$query = $dbConn->select()->from(
31
+			$query=$dbConn->select()->from(
32 32
 				$this->getModuleConfig()->getTrapDataTableName(),
33 33
 				array('COUNT(*)')
34 34
 			);			
35 35
 			$this->view->trap_object_count=$dbConn->fetchOne($query);
36
-			$query = $dbConn->select()->from(
36
+			$query=$dbConn->select()->from(
37 37
 				$this->getModuleConfig()->getTrapRuleName(),
38 38
 				array('COUNT(*)')
39 39
 			);			
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 		}
45 45
 		catch (Exception $e)
46 46
 		{
47
-			$this->displayExitError('status',$e->getMessage());
47
+			$this->displayExitError('status', $e->getMessage());
48 48
 		}
49 49
 		
50 50
 		/*************** Log destination *******************/
@@ -59,20 +59,20 @@  discard block
 block discarded – undo
59 59
 		}
60 60
 		catch (Exception $e)
61 61
 		{
62
-			$this->displayExitError('status',$e->getMessage());
62
+			$this->displayExitError('status', $e->getMessage());
63 63
 		}
64 64
 		
65 65
 		/*************** SNMP configuration ****************/
66 66
 		try
67 67
 		{
68
-		    $this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
68
+		    $this->view->useSnmpTrapAddess=($this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1) ? TRUE : FALSE;
69 69
 		    $this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
-		    $this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
70
+		    $this->view->SnmpTrapAddressOIDDefault=($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid']) ? TRUE : FALSE;
71 71
 		    
72 72
 		}
73 73
 		catch (Exception $e)
74 74
 		{
75
-		    $this->displayExitError('status',$e->getMessage());
75
+		    $this->displayExitError('status', $e->getMessage());
76 76
 		}		
77 77
 		
78 78
 	} 
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 				if ($action == 'update_mib_db')
99 99
 				{ // Do the update in background
100 100
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
101
-					if (preg_match('/OK/',$return))
101
+					if (preg_match('/OK/', $return))
102 102
 					{
103 103
 					    $this->_helper->json(array('status'=>'OK'));
104 104
 					}
@@ -107,32 +107,32 @@  discard block
 block discarded – undo
107 107
 				}
108 108
 				if ($action == 'check_update')
109 109
 				{
110
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
110
+				    $file=@fopen('/tmp/trapdirector_update.pid', 'r');
111 111
 				    if ($file == false)
112 112
 				    {   // process is dead
113
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
113
+				        $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'Cannot open file'));
114 114
 				        return;
115 115
 				    }
116 116
 				    $pid=fgets($file);
117 117
 				    $output=array();
118 118
 				    $retVal=0;
119
-					exec('ps '.$pid,$output,$retVal);
119
+					exec('ps '.$pid, $output, $retVal);
120 120
 					if ($retVal == 0)
121 121
 					{ // process is alive
122 122
 						$this->_helper->json(array('status'=>'Alive and kicking'));
123 123
 					}
124 124
 					else
125 125
 					{ // process is dead
126
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
126
+					    $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'no proc'.$pid));
127 127
 					}
128 128
 				}
129
-				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
129
+				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible'));
130 130
 			}
131 131
 			/** Check for mib file UPLOAD */
132 132
 			if (isset($_FILES['mibfile']))
133 133
 			{
134 134
 				$name=htmlspecialchars($_FILES['mibfile']['name']);
135
-				$DirConf=explode(':',$this->Config()->get('config', 'snmptranslate_dirs'));
135
+				$DirConf=explode(':', $this->Config()->get('config', 'snmptranslate_dirs'));
136 136
 				$destDir=array_shift($DirConf);
137 137
 				if (!is_dir($destDir))
138 138
 				{
@@ -146,9 +146,9 @@  discard block
 block discarded – undo
146 146
 				    }
147 147
 				    else
148 148
 				    {
149
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
149
+				        $destination=$destDir.'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150 150
 				        $sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']);
151
-				        if (move_uploaded_file($sourceTmpNam,$destination)===false)
151
+				        if (move_uploaded_file($sourceTmpNam, $destination) === false)
152 152
     				    {
153 153
     				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154 154
     				    }
@@ -164,16 +164,16 @@  discard block
 block discarded – undo
164 164
 		}
165 165
 		
166 166
 		// snmptranslate tests
167
-		$snmptranslate = $this->Config()->get('config', 'snmptranslate');
167
+		$snmptranslate=$this->Config()->get('config', 'snmptranslate');
168 168
 		$this->view->snmptranslate_bin=$snmptranslate;
169 169
 		$this->view->snmptranslate_state='warn';
170
-		if (is_executable ( $snmptranslate ))
170
+		if (is_executable($snmptranslate))
171 171
 		{
172
-			$translate=exec($snmptranslate . ' 1');
173
-			if (preg_match('/iso/',$translate))
172
+			$translate=exec($snmptranslate.' 1');
173
+			if (preg_match('/iso/', $translate))
174 174
 			{
175
-			    $translate=exec($snmptranslate . ' 1.3.6.1.4');
176
-			    if (preg_match('/private/',$translate))
175
+			    $translate=exec($snmptranslate.' 1.3.6.1.4');
176
+			    if (preg_match('/private/', $translate))
177 177
 			    {		    
178 178
     				$this->view->snmptranslate='works fine';
179 179
     				$this->view->snmptranslate_state='ok';
@@ -196,46 +196,46 @@  discard block
 block discarded – undo
196 196
 		// mib database
197 197
 		
198 198
 		$this->view->mibDbCount=$this->getMIB()->countObjects();
199
-		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null,21);
199
+		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null, 21);
200 200
 		
201 201
 		// mib dirs
202 202
 		$DirConf=$this->Config()->get('config', 'snmptranslate_dirs');
203
-		$dirArray=explode(':',$DirConf);
203
+		$dirArray=explode(':', $DirConf);
204 204
 
205 205
 		// Get base directories from net-snmp-config
206 206
 		$output=$matches=array();
207 207
 		$retVal=0;
208
-		$sysDirs=exec('net-snmp-config --default-mibdirs',$output,$retVal);
209
-		if ($retVal==0)
208
+		$sysDirs=exec('net-snmp-config --default-mibdirs', $output, $retVal);
209
+		if ($retVal == 0)
210 210
 		{
211
-			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
211
+			$dirArray=array_merge($dirArray, explode(':', $sysDirs));
212 212
 		}
213 213
 		else
214 214
 		{
215
-			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
216
-			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
215
+			$translateOut=exec($this->Config()->get('config', 'snmptranslate').' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
216
+			if (preg_match('/MIBDIRS.*\'([^\']+)\'/', $translateOut, $matches))
217 217
 			{
218
-				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
218
+				$dirArray=array_merge($dirArray, explode(':', $matches[1]));
219 219
 			}
220 220
 			else
221 221
 			{
222
-				array_push($dirArray,'Install net-snmp-config to see system directories');
222
+				array_push($dirArray, 'Install net-snmp-config to see system directories');
223 223
 			}
224 224
 		}
225 225
 		
226 226
 		$this->view->dirArray=$dirArray;
227 227
 		
228 228
 		$output=null;
229
-		foreach (explode(':',$DirConf) as $mibdir)
229
+		foreach (explode(':', $DirConf) as $mibdir)
230 230
 		{
231
-			exec('ls '.$mibdir.' | grep -v traplist.txt',$output);
231
+			exec('ls '.$mibdir.' | grep -v traplist.txt', $output);
232 232
 		}
233 233
 		//$i=0;$listFiles='';while (isset($output[$i])) $listFiles.=$output[$i++];
234 234
 		//$this->view->fileList=explode(' ',$listFiles);
235 235
 		$this->view->fileList=$output;
236 236
 		
237 237
 		// Zend form 
238
-		$this->view->form= new UploadForm();
238
+		$this->view->form=new UploadForm();
239 239
 		//$this->view->form= new Form('upload-form');
240 240
 		
241 241
 		
@@ -250,9 +250,9 @@  discard block
 block discarded – undo
250 250
 	    $this->view->setOKMsg='';
251 251
 	    
252 252
 	    //max_rows=25&row_update=update
253
-	    if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
253
+	    if ($this->getRequest()->getParam('max_rows', NULL) !== NULL)
254 254
 	    {
255
-	        $maxRows = $this->getRequest()->getParam('max_rows');
255
+	        $maxRows=$this->getRequest()->getParam('max_rows');
256 256
 	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257 257
 	        {
258 258
 	            $this->view->setError='Max rows must be a number';
@@ -260,21 +260,21 @@  discard block
 block discarded – undo
260 260
 	        else
261 261
 	        {
262 262
 	            $this->setitemListDisplay($maxRows);
263
-	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
263
+	            $this->view->setOKMsg='Set max rows to '.$maxRows;
264 264
 	        }
265 265
 	    }
266 266
 	    
267
-	    if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
267
+	    if ($this->getRequest()->getParam('add_category', NULL) !== NULL)
268 268
 	    {
269
-	        $addCat = $this->getRequest()->getParam('add_category');
269
+	        $addCat=$this->getRequest()->getParam('add_category');
270 270
             $this->addHandlersCategory($addCat);
271 271
 	    }
272 272
 	    
273
-	    if ( $this->getRequest()->getPost('type',NULL) !== NULL )
273
+	    if ($this->getRequest()->getPost('type', NULL) !== NULL)
274 274
 	    {
275
-	        $type = $this->getRequest()->getPost('type',NULL);
276
-	        $index = $this->getRequest()->getPost('index',NULL);
277
-	        $newname = $this->getRequest()->getPost('newname',NULL);
275
+	        $type=$this->getRequest()->getPost('type', NULL);
276
+	        $index=$this->getRequest()->getPost('index', NULL);
277
+	        $newname=$this->getRequest()->getPost('newname', NULL);
278 278
 
279 279
 	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280 280
 	            $this->_helper->json(array('status'=>'Bad index'));
@@ -298,9 +298,9 @@  discard block
 block discarded – undo
298 298
 	        }
299 299
 	    }
300 300
 	    
301
-	    $this->view->maxRows = $this->itemListDisplay();
301
+	    $this->view->maxRows=$this->itemListDisplay();
302 302
 	    
303
-	    $this->view->categories = $this->getHandlersCategory();
303
+	    $this->view->categories=$this->getHandlersCategory();
304 304
 	    
305 305
 	    
306 306
 	    
@@ -324,18 +324,18 @@  discard block
 block discarded – undo
324 324
 		$this->view->templateForm_output='';
325 325
 		if (isset($postData['template_name']) && isset($postData['template_revert_time']))
326 326
 		{
327
-			$template_create = 'icingacli director service create --json \'{ "check_command": "dummy", ';
328
-			$template_create .= '"check_interval": "' .$postData['template_revert_time']. '", "check_timeout": "20", "disabled": false, "enable_active_checks": true, "enable_event_handler": true, "enable_notifications": true, "enable_passive_checks": true, "enable_perfdata": true, "max_check_attempts": "1", ';
329
-			$template_create .= '"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
327
+			$template_create='icingacli director service create --json \'{ "check_command": "dummy", ';
328
+			$template_create.='"check_interval": "'.$postData['template_revert_time'].'", "check_timeout": "20", "disabled": false, "enable_active_checks": true, "enable_event_handler": true, "enable_notifications": true, "enable_passive_checks": true, "enable_perfdata": true, "max_check_attempts": "1", ';
329
+			$template_create.='"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
330 330
 			$output=array();
331 331
 			$ret_code=0;
332
-			exec($template_create,$output,$ret_code);
332
+			exec($template_create, $output, $ret_code);
333 333
 			if ($ret_code != 0)
334 334
 			{
335
-				$this->displayExitError("Status -> Services","Error creating template : ".$output[0].'<br>Command was : '.$template_create);
335
+				$this->displayExitError("Status -> Services", "Error creating template : ".$output[0].'<br>Command was : '.$template_create);
336 336
 			}
337
-			exec('icingacli director config deploy',$output,$ret_code);
338
-			$this->view->templateForm_output='Template '.$postData['template_name']. ' created';
337
+			exec('icingacli director config deploy', $output, $ret_code);
338
+			$this->view->templateForm_output='Template '.$postData['template_name'].' created';
339 339
 		}
340 340
 		
341 341
 		// template creation form
@@ -351,15 +351,15 @@  discard block
 block discarded – undo
351 351
 	{
352 352
 	    $this->prepareTabs()->activate('plugins');
353 353
 	    
354
-	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
354
+	    require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
355 355
 	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
356
-	    $Trap = new Trap($icingaweb2_etc,4);
356
+	    $Trap=new Trap($icingaweb2_etc, 4);
357 357
 	    
358
-	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
358
+	    $this->view->pluginLoaded=htmlentities($Trap->pluginClass->registerAllPlugins(false));
359 359
 	    
360
-	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
360
+	    $enabledPlugins=$Trap->pluginClass->getEnabledPlugins();
361 361
 
362
-	    $pluginList = $Trap->pluginClass->pluginList();
362
+	    $pluginList=$Trap->pluginClass->pluginList();
363 363
 	    
364 364
 	    // Plugin list and fill function name list
365 365
 	    $functionList=array();
@@ -367,16 +367,16 @@  discard block
 block discarded – undo
367 367
 	    foreach ($pluginList as $plugin)
368 368
 	    {
369 369
 	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
370
-	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
371
-	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
372
-	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
373
-	        $pluginDetails->description = htmlentities($pluginDetails->description);
374
-	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
370
+	        $pluginDetails->enabled=(in_array($plugin, $enabledPlugins)) ? true : false;
371
+	        $pluginDetails->catchAllTraps=($pluginDetails->catchAllTraps === true) ? 'Yes' : 'No';
372
+	        $pluginDetails->processTraps=($pluginDetails->processTraps === true) ? 'Yes' : 'No';
373
+	        $pluginDetails->description=htmlentities($pluginDetails->description);
374
+	        $pluginDetails->description=preg_replace('/\n/', '<br>', $pluginDetails->description);
375 375
 	        array_push($this->view->pluginArray, $pluginDetails);
376 376
 	        // Get functions for function details
377 377
 	        foreach ($pluginDetails->funcArray as $function)
378 378
 	        {
379
-	            array_push($functionList,$function);
379
+	            array_push($functionList, $function);
380 380
 	        }
381 381
 	    }
382 382
 	    
@@ -384,10 +384,10 @@  discard block
 block discarded – undo
384 384
 	    $this->view->functionList=array();
385 385
 	    foreach ($functionList as $function)
386 386
 	    {
387
-	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
388
-	        $functionDetail->params = htmlentities($functionDetail->params);
389
-	        $functionDetail->description = htmlentities($functionDetail->description);
390
-	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
387
+	        $functionDetail=$Trap->pluginClass->getFunctionDetails($function);
388
+	        $functionDetail->params=htmlentities($functionDetail->params);
389
+	        $functionDetail->description=htmlentities($functionDetail->description);
390
+	        $functionDetail->description=preg_replace('/\n/', '<br>', $functionDetail->description);
391 391
 	        array_push($this->view->functionList, $functionDetail);
392 392
 	    }
393 393
 
@@ -399,43 +399,43 @@  discard block
 block discarded – undo
399 399
 	public function debugAction()
400 400
 	{
401 401
 	    $this->view->answer='No answer';
402
-	    $this->view->input1 = '';
402
+	    $this->view->input1='';
403 403
 	    
404 404
 	    $postData=$this->getRequest()->getPost();
405 405
 	    if (isset($postData['input1']))
406 406
 	    {
407
-	        $input1 = $postData['input1'];
408
-	        $input2 = $postData['input2'];
409
-	        $input3 = $postData['input3'];
410
-	        $this->view->input1 = $input1;
407
+	        $input1=$postData['input1'];
408
+	        $input2=$postData['input2'];
409
+	        $input3=$postData['input3'];
410
+	        $this->view->input1=$input1;
411 411
 	        //$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
412 412
 	        try {
413
-	            $this->view->answer = 'Answer : ';
414
-	            $API = $this->getIdoConn();
415
-	            $DB = $this->getUIDatabase();
413
+	            $this->view->answer='Answer : ';
414
+	            $API=$this->getIdoConn();
415
+	            $DB=$this->getUIDatabase();
416 416
 
417 417
 	            //$hosts = $DB->getServicesByHostGroupid($input1);
418 418
 	            //$this->view->answer .= 'services : '.print_r($hosts,true);
419 419
 	            
420
-	            $hosts = $API->getServicesByHostGroupid($input1);
421
-	            $this->view->answer .= 'services : '.print_r($hosts,true);
420
+	            $hosts=$API->getServicesByHostGroupid($input1);
421
+	            $this->view->answer.='services : '.print_r($hosts, true);
422 422
 	            
423 423
 
424 424
 	            
425 425
 	            return;
426
-	            $hosts = $API->getHostByIP($input1);
427
-	            $this->view->answer .= 'Host : '. print_r($hosts,true);
428
-	            $hosts = $API->getHostGroupByName($input1);
429
-	            $this->view->answer .= 'Group : '.print_r($hosts,true);
430
-	            $hosts = $API->getServicesByHostid($input1);
431
-	            $this->view->answer .= 'service : '.print_r($hosts,true);
426
+	            $hosts=$API->getHostByIP($input1);
427
+	            $this->view->answer.='Host : '.print_r($hosts, true);
428
+	            $hosts=$API->getHostGroupByName($input1);
429
+	            $this->view->answer.='Group : '.print_r($hosts, true);
430
+	            $hosts=$API->getServicesByHostid($input1);
431
+	            $this->view->answer.='service : '.print_r($hosts, true);
432 432
 	            
433 433
 	            /* $hosts = $API->getHostsIPByHostGroup($input1);
434 434
 	            $this->view->answer .= "\n Hostgrp : " . print_r($hosts,true); */
435 435
 	            
436 436
 	        } catch (Exception $e)
437 437
 	        {
438
-	            $this->view->answer = "Exception : " . print_r($e);
438
+	            $this->view->answer="Exception : ".print_r($e);
439 439
 	        }
440 440
 	        
441 441
 	    }
@@ -446,19 +446,19 @@  discard block
 block discarded – undo
446 446
 	{
447 447
 		return $this->getTabs()->add('status', array(
448 448
 			'label' => $this->translate('Status'),
449
-			'url'   => $this->getModuleConfig()->urlPath() . '/status')
449
+			'url'   => $this->getModuleConfig()->urlPath().'/status')
450 450
 		)->add('mib', array(
451 451
 			'label' => $this->translate('MIB Management'),
452
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
452
+			'url'   => $this->getModuleConfig()->urlPath().'/status/mib')
453 453
 	    )->add('uimgt', array(
454 454
 	        'label' => $this->translate('UI Configuration'),
455
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
455
+	        'url'   => $this->getModuleConfig()->urlPath().'/status/uimgt')
456 456
         )->add('services', array(
457 457
 			'label' => $this->translate('Services management'),
458
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
458
+			'url'   => $this->getModuleConfig()->urlPath().'/status/services')
459 459
 	    )->add('plugins', array(
460 460
 	        'label' => $this->translate('Plugins management'),
461
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
461
+	        'url'   => $this->getModuleConfig()->urlPath().'/status/plugins')
462 462
 	    );
463 463
 	} 
464 464
 }
@@ -466,7 +466,7 @@  discard block
 block discarded – undo
466 466
 // TODO : see if useless 
467 467
 class UploadForm extends Form
468 468
 { 
469
-    public function __construct($options = null) 
469
+    public function __construct($options=null) 
470 470
     {
471 471
         parent::__construct($options);
472 472
         $this->addElements2();
@@ -475,11 +475,11 @@  discard block
 block discarded – undo
475 475
     public function addElements2()
476 476
     {
477 477
         // File Input
478
-        $file = new File('mib-file');
478
+        $file=new File('mib-file');
479 479
         $file->setLabel('Mib upload');
480 480
              //->setAttrib('multiple', null);
481 481
         $this->addElement($file);
482
-		$button = new Submit("upload",array('ignore'=>false));
483
-		$this->addElement($button);//->setIgnore(false);
482
+		$button=new Submit("upload", array('ignore'=>false));
483
+		$this->addElement($button); //->setIgnore(false);
484 484
     }
485 485
 }
Please login to merge, or discard this patch.
application/controllers/SettingsController.php 1 patch
Spacing   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -72,23 +72,23 @@  discard block
 block discarded – undo
72 72
   private function check_db()
73 73
   {
74 74
       $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
-          0	=>	array('Database configuration OK','',''),
76
-          1	=>	array('Database set in config.ini','No database in config.ini',''),
77
-          2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
75
+          0	=>	array('Database configuration OK', '', ''),
76
+          1	=>	array('Database set in config.ini', 'No database in config.ini', ''),
77
+          2	=>	array('Database exists in Icingaweb2 config', 'Database does not exist in Icingaweb2 : ',
78 78
               Url::fromPath('config/resource')),
79
-          3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
79
+          3	=>	array('Database credentials OK', 'Database does not exist/invalid credentials/no schema : ',
80 80
               Url::fromPath('trapdirector/settings/createschema')),
81
-          4	=>	array('Schema is set','Schema is not set for ',
81
+          4	=>	array('Schema is set', 'Schema is not set for ',
82 82
               Url::fromPath('trapdirector/settings/createschema')),
83
-          5	=>	array('Schema is up to date','Schema is outdated :',
83
+          5	=>	array('Schema is up to date', 'Schema is outdated :',
84 84
               Url::fromPath('trapdirector/settings/updateschema')),
85 85
       );
86 86
       
87 87
       try {
88 88
           $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
-          $dberror=array(0,'');
89
+          $dberror=array(0, '');
90 90
       } catch (DBException $e) {
91
-          $dberror = $e->getArray();
91
+          $dberror=$e->getArray();
92 92
       }
93 93
       
94 94
       $this->view->db_error=$dberror[0];
@@ -96,13 +96,13 @@  discard block
 block discarded – undo
96 96
       {
97 97
           case 2:
98 98
           case 4:
99
-              $db_message[$dberror[0]][1] .= $dberror[1];
99
+              $db_message[$dberror[0]][1].=$dberror[1];
100 100
               break;
101 101
           case 3:
102
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
102
+              $db_message[$dberror[0]][1].=$dberror[1].', Message : '.$dberror[2];
103 103
               break;
104 104
           case 5:
105
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
105
+              $db_message[$dberror[0]][1].=' version '.$dberror[1].', version needed : '.$dberror[2];
106 106
               break;
107 107
           case 0:
108 108
           case 1:
@@ -114,14 +114,14 @@  discard block
 block discarded – undo
114 114
       
115 115
       try {
116 116
           $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
-          $dberror=array(0,'');
117
+          $dberror=array(0, '');
118 118
       } catch (DBException $e) {
119
-          $dberror = $e->getArray();
119
+          $dberror=$e->getArray();
120 120
       }
121 121
       
122 122
       $this->view->ido_db_error=$dberror[0];
123
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
124
-      $this->view->ido_message .='<br />=&gt; Default to API use. Make sure it is configured and check is returning OK!';
123
+      $this->view->ido_message='IDO Database : '.$dberror[1];
124
+      $this->view->ido_message.='<br />=&gt; Default to API use. Make sure it is configured and check is returning OK!';
125 125
   }
126 126
   
127 127
   /**
@@ -133,13 +133,13 @@  discard block
 block discarded – undo
133 133
   {
134 134
       if ($this->Config()->get('config', 'icingaAPI_host') != '')
135 135
       {
136
-          $apitest=new Icinga2API($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
136
+          $apitest=new Icinga2API($this->Config()->get('config', 'icingaAPI_host'), $this->Config()->get('config', 'icingaAPI_port'));
137 137
           $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
138 138
           try {
139
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
139
+              list($this->view->apimessageError, $this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
140 140
               //$this->view->apimessageError=false;
141 141
           } catch (RuntimeException $e) {
142
-              $this->view->apimessage='API config : ' . $e->getMessage();
142
+              $this->view->apimessage='API config : '.$e->getMessage();
143 143
               $this->view->apimessageError=true;
144 144
           }
145 145
       }
@@ -164,10 +164,10 @@  discard block
 block discarded – undo
164 164
       {
165 165
           $output=array();
166 166
           
167
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
167
+          exec('cat '.$this->module->getBaseDir().'/bin/trap_in.php | grep "\$icingaweb2Etc=" ', $output);
168 168
           
169 169
           
170
-          if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
170
+          if (!isset($output[0]) || !preg_match('#"'.$icingaweb2_etc.'"#', $output[0]))
171 171
           {
172 172
               $this->view->icingaEtcWarn=1;
173 173
               $this->view->icingaweb2_etc=$icingaweb2_etc;
@@ -183,12 +183,12 @@  discard block
 block discarded – undo
183 183
    */
184 184
   private function get_db_list($allowed)
185 185
   {
186
-      $resources = array();
186
+      $resources=array();
187 187
       foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
188 188
       {
189 189
           if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
190 190
           {
191
-              $resources[$name] = $name;
191
+              $resources[$name]=$name;
192 192
           }
193 193
       }
194 194
       return $resources;
@@ -200,18 +200,18 @@  discard block
 block discarded – undo
200 200
    */
201 201
   private function get_php_binary()
202 202
   {
203
-      $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
203
+      $phpBinary=array(PHP_BINARY, PHP_BINDIR."/php", '/usr/bin/php');
204 204
 
205
-      foreach ($phpBinary as $phpBin )
205
+      foreach ($phpBinary as $phpBin)
206 206
       {
207 207
           $output=array();
208 208
           $retCode=255;
209 209
           $input="154865134987aaaa";
210
-          exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
210
+          exec("$phpBin -r \"echo '$input';\"", $output, $retCode);
211 211
           
212
-          if (! isset($output[0])) $output[0]="NO OUT";
212
+          if (!isset($output[0])) $output[0]="NO OUT";
213 213
           
214
-          if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
214
+          if ($retCode == 0 && preg_match("/$input/", $output[0]) == 1)
215 215
           {
216 216
               return $phpBin;
217 217
           }          
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
 	// But check read permission
241 241
 	$this->checkReadPermission();
242 242
 	
243
-	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');	
243
+	$this->view->tabs=$this->Module()->getConfigTabs()->activate('config');	
244 244
 	
245 245
 	// Get message : sent on configuration problems detected by controllers
246 246
     $this->get_param();
@@ -255,39 +255,39 @@  discard block
 block discarded – undo
255 255
     $this->check_api();
256 256
 	
257 257
 	//Test snmptrapd alive and options
258
-	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
258
+	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage)=$this->checkSnmpTrapd();
259 259
 
260 260
 	// List DB in $ressources
261
-	$resources = $this->get_db_list(array('mysql', 'pgsql')); 
261
+	$resources=$this->get_db_list(array('mysql', 'pgsql')); 
262 262
 
263 263
 	// Check standard Icingaweb2 path
264 264
 	$this->check_icingaweb_path();
265 265
 
266
-	$phpBinary = $this->get_php_binary();
266
+	$phpBinary=$this->get_php_binary();
267 267
 	if ($phpBinary === null)
268 268
 	{
269
-	    $phpBinary = ' PHP BINARY NOT FOUND ';
269
+	    $phpBinary=' PHP BINARY NOT FOUND ';
270 270
 	    
271 271
 	}
272 272
 	
273 273
 	// Setup path for mini documentation
274
-	$this->view->traps_in_config= $phpBinary . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
274
+	$this->view->traps_in_config=$phpBinary.' '.$this->Module()->getBaseDir().'/bin/trap_in.php';
275 275
 	
276
-	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
276
+	$this->view->installer=$this->Module()->getBaseDir().'/bin/installer.sh '
277 277
 	    . ' -c all ' 
278
-	    . ' -d ' . $this->Module()->getBaseDir()
279
-	    . ' -p ' . $phpBinary
280
-	    . ' -a ' . exec('whoami')
281
-	    . ' -w ' . Icinga::app()->getConfigDir();
278
+	    . ' -d '.$this->Module()->getBaseDir()
279
+	    . ' -p '.$phpBinary
280
+	    . ' -a '.exec('whoami')
281
+	    . ' -w '.Icinga::app()->getConfigDir();
282 282
 	        
283 283
 	// ******************* configuration form setup*******************
284
-	$this->view->form = $form = new TrapsConfigForm();
284
+	$this->view->form=$form=new TrapsConfigForm();
285 285
 	
286 286
 	// set default paths;
287
-	$this->view->form->setPaths($this->Module()->getBaseDir(),Icinga::app()->getConfigDir());
287
+	$this->view->form->setPaths($this->Module()->getBaseDir(), Icinga::app()->getConfigDir());
288 288
 	
289 289
 	// set default ido database
290
-	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring','backends')->get('icinga','resource'));
290
+	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring', 'backends')->get('icinga', 'resource'));
291 291
 	
292 292
 	// Make form handle request.
293 293
 	$form->setIniConfig($this->Config())
@@ -316,18 +316,18 @@  discard block
 block discarded – undo
316 316
       $this->view->configPermission=$this->checkModuleConfigPermission();
317 317
       
318 318
       // Setup tabs
319
-      $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
319
+      $this->view->tabs=$this->Module()->getConfigTabs()->activate('satellite');	
320 320
       
321
-      $this->view->masterHASet = FALSE;
321
+      $this->view->masterHASet=FALSE;
322 322
       
323
-      $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
323
+      $this->view->masterHAConf=array('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
324 324
   }
325 325
   
326 326
   
327 327
   public function createschemaAction()
328 328
   {
329 329
 	$this->checkModuleConfigPermission();
330
-	$this->getTabs()->add('create_schema',array(
330
+	$this->getTabs()->add('create_schema', array(
331 331
 		'active'	=> true,
332 332
 		'label'		=> $this->translate('Create Schema'),
333 333
 		'url'		=> Url::fromRequest()
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
 		// Get module database name
349 349
 		$dbName=$this->Config()->get('config', 'database');
350 350
 
351
-        $dbResource = ResourceFactory::getResourceConfig($dbName);
351
+        $dbResource=ResourceFactory::getResourceConfig($dbName);
352 352
         $dbType=$dbResource->get('db');
353 353
         switch ($dbType) {
354 354
           case 'mysql':
@@ -363,28 +363,28 @@  discard block
 block discarded – undo
363 363
         } 
364 364
 
365 365
 		printf('<pre>');
366
-		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
366
+		require_once $this->Module()->getBaseDir().'/bin/trap_class.php';
367 367
 		
368 368
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
369 369
 		$debug_level=4;
370
-		$Trap = new Trap($icingaweb2_etc);
371
-		$Trap->setLogging($debug_level,'display');
370
+		$Trap=new Trap($icingaweb2_etc);
371
+		$Trap->setLogging($debug_level, 'display');
372 372
 		
373 373
 		$prefix=$this->Config()->get('config', 'database_prefix');
374 374
 		// schema file : <path>/SQL/schema_v<verion>.<dbtype>
375
-		$schema=$this->Module()->getBaseDir() . 
376
-		'/SQL/schema_v'. $this->getModuleConfig()->getDbCurVersion() . '.' . $dbFileExt;
375
+		$schema=$this->Module()->getBaseDir(). 
376
+		'/SQL/schema_v'.$this->getModuleConfig()->getDbCurVersion().'.'.$dbFileExt;
377 377
 		
378
-		$Trap->trapsDB->create_schema($schema,$prefix);
378
+		$Trap->trapsDB->create_schema($schema, $prefix);
379 379
 		echo '</pre>';
380 380
 	}
381
-	echo '<br><br>Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a>';
381
+	echo '<br><br>Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a>';
382 382
   }
383 383
 
384 384
   public function updateschemaAction()
385 385
   {
386 386
 	  $this->checkModuleConfigPermission();
387
-      $this->getTabs()->add('get',array(
387
+      $this->getTabs()->add('get', array(
388 388
     		'active'	=> true,
389 389
     		'label'		=> $this->translate('Update Schema'),
390 390
     		'url'		=> Url::fromRequest()
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
           $dberror=$e->getArray(); 
403 403
       }
404 404
 	  
405
-	  echo 'Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a><br><br>';
405
+	  echo 'Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a><br><br>';
406 406
 	  
407 407
 	  if ($dberror[0] != 5)
408 408
 	  {
@@ -410,40 +410,40 @@  discard block
 block discarded – undo
410 410
 	      return;
411 411
 	  }
412 412
       // setup
413
-	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
413
+	  require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
414 414
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
415 415
 	  $debug_level=4;
416
-	  $Trap = new Trap($icingaweb2_etc);
416
+	  $Trap=new Trap($icingaweb2_etc);
417 417
 	  
418 418
 	  
419 419
 	  $prefix=$this->Config()->get('config', 'database_prefix');
420
-	  $updateSchema=$this->Module()->getBaseDir() . '/SQL/';
420
+	  $updateSchema=$this->Module()->getBaseDir().'/SQL/';
421 421
 	  
422 422
 	  $target_version=$dberror[2];
423 423
 	  
424 424
 	  if ($this->params->get('msgok') == null) {
425 425
 	      // Check for messages and display if any
426 426
               echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
427
-	      $Trap->setLogging(2,'syslog');
428
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
427
+	      $Trap->setLogging(2, 'syslog');
428
+	      $message=$Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix, true);
429 429
 	      if ($message != '')
430 430
 	      {
431 431
 	          echo 'Note :<br><pre>';
432 432
 	          echo $message;
433 433
 	          echo '</pre>';
434 434
 	          echo '<br>';
435
-	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
435
+	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="'.Url::fromPath('trapdirector/settings/updateschema').'?msgok=1">Click here to update</a>';
436 436
 	          echo '<br>';
437 437
 	          return;
438 438
 	      }
439 439
 	  }
440 440
 	  
441
-	  $Trap->setLogging($debug_level,'display');
441
+	  $Trap->setLogging($debug_level, 'display');
442 442
 	  
443
-	  echo 'Updating schema to '. $target_version . ': <br>';
443
+	  echo 'Updating schema to '.$target_version.': <br>';
444 444
 	  echo '<pre>';
445 445
 	  	  
446
-	  $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix);
446
+	  $Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix);
447 447
 	  echo '</pre>';
448 448
   }  
449 449
 
@@ -452,50 +452,50 @@  discard block
 block discarded – undo
452 452
   {
453 453
       $psOutput=array();
454 454
       // First check is someone is listening to port 162. As not root, we can't have pid... 
455
-      $sspath = exec('which ss 2>/dev/null');
456
-      if(empty($sspath))
455
+      $sspath=exec('which ss 2>/dev/null');
456
+      if (empty($sspath))
457 457
       {
458 458
           // RHEL based systems
459
-          $sspath = '/usr/sbin/ss';
459
+          $sspath='/usr/sbin/ss';
460 460
       }
461
-      if(!is_executable("$sspath"))
461
+      if (!is_executable("$sspath"))
462 462
       {
463
-          return array(1,"Can not execute $sspath");
463
+          return array(1, "Can not execute $sspath");
464 464
       }
465
-      exec("$sspath -lun | grep ':162 '",$psOutput);
465
+      exec("$sspath -lun | grep ':162 '", $psOutput);
466 466
       if (count($psOutput) == 0)
467 467
       {
468
-          $extra = "";
469
-          if (is_file("/.dockerenv")){ $extra = '<br />=&gt; ignore if Trapdirector is running in a different Docker container'; }
470
-          return array(1,'Port UDP/162 is not open : is snmptrapd running?'. $extra);
468
+          $extra="";
469
+          if (is_file("/.dockerenv")) { $extra='<br />=&gt; ignore if Trapdirector is running in a different Docker container'; }
470
+          return array(1, 'Port UDP/162 is not open : is snmptrapd running?'.$extra);
471 471
       }
472 472
       $psOutput=array();
473
-      $selinux_state = '';
474
-      if(is_executable('/usr/sbin/getenforce'))
473
+      $selinux_state='';
474
+      if (is_executable('/usr/sbin/getenforce'))
475 475
       {
476
-          $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
476
+          $selinux_state=exec('/usr/sbin/getenforce 2>/dev/null');
477 477
       }
478
-      if($selinux_state !== 'Enforcing')
478
+      if ($selinux_state !== 'Enforcing')
479 479
       {
480
-          exec('ps --no-headers -o command -C snmptrapd',$psOutput);
480
+          exec('ps --no-headers -o command -C snmptrapd', $psOutput);
481 481
           if (count($psOutput) == 0)
482 482
           {
483
-              return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
483
+              return array(1, "UDP/162 : OK, but no snmptrapd process (?)");
484 484
           }
485 485
           // Assume there is only one line... TODO : see if there is a better way to do this
486
-          $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
487
-          if (!preg_match('/-n/',$line))
488
-              return array(1,'snmptrapd has no -n option : '.$line);
489
-          if (!preg_match('/-O[^ ]*n/',$line))
490
-              return array(1,'snmptrapd has no -On option : '.$line);
491
-          if (!preg_match('/-O[^ ]*e/',$line))
492
-              return array(1,'snmptrapd has no -Oe option : '.$line);
486
+          $line=preg_replace('/^.*snmptrapd /', '', $psOutput[0]);
487
+          if (!preg_match('/-n/', $line))
488
+              return array(1, 'snmptrapd has no -n option : '.$line);
489
+          if (!preg_match('/-O[^ ]*n/', $line))
490
+              return array(1, 'snmptrapd has no -On option : '.$line);
491
+          if (!preg_match('/-O[^ ]*e/', $line))
492
+              return array(1, 'snmptrapd has no -Oe option : '.$line);
493 493
 
494
-          return array(0,'snmptrapd listening to UDP/162, options : '.$line);
494
+          return array(0, 'snmptrapd listening to UDP/162, options : '.$line);
495 495
       }
496 496
       else
497 497
       {
498
-          return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
498
+          return array(0, 'A daemon (hidden by SELinux) is listening on UDP/162');
499 499
       }
500 500
   }
501 501
 }
Please login to merge, or discard this patch.
application/clicommands/MibCommand.php 1 patch
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -38,39 +38,39 @@  discard block
 block discarded – undo
38 38
 	*/
39 39
 	public function updateAction()
40 40
 	{
41
-	    $background = $this->params->get('pid', null);
42
-	    $logLevel= $this->params->has('verb') ? 4 : 2;
43
-	    if ($this->params->has('force-check')) { echo "Not implemented"; return;}
44
-	    $forceCheck=$this->params->has('force-check')?True:False;
41
+	    $background=$this->params->get('pid', null);
42
+	    $logLevel=$this->params->has('verb') ? 4 : 2;
43
+	    if ($this->params->has('force-check')) { echo "Not implemented"; return; }
44
+	    $forceCheck=$this->params->has('force-check') ?True:False;
45 45
 	    $pid=1;
46 46
 	    if ($background != null)
47 47
 	    {
48
-	        $file=@fopen($background,'w');
48
+	        $file=@fopen($background, 'w');
49 49
 	        if ($file == false)
50 50
 	        {
51 51
 	            echo 'Error : cannot open pid file '.$background;
52 52
 	            return 1;
53 53
 	        }
54
-	        $pid = pcntl_fork();
54
+	        $pid=pcntl_fork();
55 55
 	        if ($pid == -1) {
56 56
 	            echo 'Error : Cannot fork process';
57 57
 	            return 1;
58 58
 	        }
59 59
 	    }
60 60
 	    $module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
61
-		require_once($module->getBaseDir() .'/bin/trap_class.php');
61
+		require_once($module->getBaseDir().'/bin/trap_class.php');
62 62
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
63
-		$trap = new Trap($icingaweb2_etc);
63
+		$trap=new Trap($icingaweb2_etc);
64 64
 		if ($pid == 1)
65 65
 		{
66
-		    $trap->setLogging($logLevel,'display');
66
+		    $trap->setLogging($logLevel, 'display');
67 67
 		}
68 68
 		else
69 69
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
70 70
 		    if ($pid != 0)
71 71
 		    {
72 72
 		        // father process
73
-		        fwrite($file,$pid);
73
+		        fwrite($file, $pid);
74 74
 		        fclose($file);
75 75
 		        echo "OK : process $pid in bckground";
76 76
 		        return 0;
@@ -84,11 +84,11 @@  discard block
 block discarded – undo
84 84
                 fclose(STDERR);
85 85
                 try
86 86
                 {
87
-                    $trap->mibClass->update_mib_database(false,$forceCheck);
87
+                    $trap->mibClass->update_mib_database(false, $forceCheck);
88 88
                 }
89 89
                 catch (Exception $e)
90 90
                 {
91
-                    $trap->logging->log('Error in updating : ' . $e->getMessage(),2);
91
+                    $trap->logging->log('Error in updating : '.$e->getMessage(), 2);
92 92
                 }
93 93
                 unlink($background);
94 94
                 return 0;
@@ -100,13 +100,13 @@  discard block
 block discarded – undo
100 100
 		{
101 101
 			echo "Update main mib database : \n";
102 102
 			echo "# (trap found) C (trap already processed) . (every 2 seconds) : \n";
103
-			$trap->mibClass->update_mib_database(true,$forceCheck);
103
+			$trap->mibClass->update_mib_database(true, $forceCheck);
104 104
 			echo "Done\n";
105 105
 			
106 106
 		}
107 107
 		catch (Exception $e)
108 108
 		{
109
-			echo 'Error in updating : ' . $e->getMessage();
109
+			echo 'Error in updating : '.$e->getMessage();
110 110
 		}
111 111
 		if ($pid != 1)
112 112
 		{
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 		    return;
135 135
 		}
136 136
 		
137
-		$Config = new TrapModuleConfig($db_prefix);
137
+		$Config=new TrapModuleConfig($db_prefix);
138 138
 		
139 139
 		try
140 140
 		{
@@ -142,16 +142,16 @@  discard block
 block discarded – undo
142 142
 			$dbresource=$this->Config()->get('config', 'database');
143 143
 			echo "DB name : $dbresource\n";
144 144
 //			$db = IcingaDbConnection::fromResourceName($dbresource)->getConnection();
145
-			$db = IcingaDbConnection::fromResourceName($dbresource)->getDbAdapter();
145
+			$db=IcingaDbConnection::fromResourceName($dbresource)->getDbAdapter();
146 146
 			
147
-			$query = $db->delete(
147
+			$query=$db->delete(
148 148
 			    $Config->getMIBCacheTableName(),
149 149
 			    'id>0');
150
-            echo 'Deleted '. $query . " traps and objects\n";
150
+            echo 'Deleted '.$query." traps and objects\n";
151 151
 		}
152 152
 		catch (Exception $e)
153 153
 		{
154
-			echo 'Error in DB : ' . $e->getMessage();
154
+			echo 'Error in DB : '.$e->getMessage();
155 155
 		}	   
156 156
 	}  	 	
157 157
 
Please login to merge, or discard this patch.
application/clicommands/StatusCommand.php 1 patch
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -24,22 +24,22 @@
 block discarded – undo
24 24
 	public function dbAction()
25 25
 	{
26 26
 		$db_prefix=$this->Config()->get('config', 'database_prefix');
27
-		$Config = new TrapModuleConfig($db_prefix);
27
+		$Config=new TrapModuleConfig($db_prefix);
28 28
 		
29 29
 		try
30 30
 		{
31 31
 			
32 32
 			$dbresource=$this->Config()->get('config', 'database');
33
-			printf("DB name : %s\n",$dbresource);
33
+			printf("DB name : %s\n", $dbresource);
34 34
 //			$dataBase = IcingaDbConnection::fromResourceName($dbresource)->getConnection();
35
-			$dataBase = IcingaDbConnection::fromResourceName($dbresource)->getDbAdapter();
35
+			$dataBase=IcingaDbConnection::fromResourceName($dbresource)->getDbAdapter();
36 36
 			
37
-			$query = $dataBase->select()->from($Config->getTrapTableName(),array('COUNT(*)'));			
38
-			printf("Number of traps : %s\n", $dataBase->fetchOne($query) );
39
-			$query = $dataBase->select()->from($Config->getTrapDataTableName(),array('COUNT(*)'));			
40
-			printf("Number of trap objects : %s\n", $dataBase->fetchOne($query) );
41
-			$query = $dataBase->select()->from($Config->getTrapRuleName(),array('COUNT(*)'));			
42
-			printf("Number of rules : %s\n", $dataBase->fetchOne($query) );
37
+			$query=$dataBase->select()->from($Config->getTrapTableName(), array('COUNT(*)'));			
38
+			printf("Number of traps : %s\n", $dataBase->fetchOne($query));
39
+			$query=$dataBase->select()->from($Config->getTrapDataTableName(), array('COUNT(*)'));			
40
+			printf("Number of trap objects : %s\n", $dataBase->fetchOne($query));
41
+			$query=$dataBase->select()->from($Config->getTrapRuleName(), array('COUNT(*)'));			
42
+			printf("Number of rules : %s\n", $dataBase->fetchOne($query));
43 43
 			
44 44
 		}
45 45
 		catch (Exception $e)
Please login to merge, or discard this patch.
library/Trapdirector/Icinga2API.php 1 patch
Spacing   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -16,9 +16,9 @@  discard block
 block discarded – undo
16 16
      * @param string $host host name or IP
17 17
      * @param number $port API port
18 18
      */
19
-    public function __construct($host, $port = 5665)
19
+    public function __construct($host, $port=5665)
20 20
     {
21
-        parent::__construct($host,$port);
21
+        parent::__construct($host, $port);
22 22
     }
23 23
     /**
24 24
 
@@ -32,17 +32,17 @@  discard block
 block discarded – undo
32 32
      */
33 33
     public function getHostByFilter(string $hostfilter)
34 34
     {
35
-        $hosts = $this->standardQuery(
35
+        $hosts=$this->standardQuery(
36 36
             'host',
37 37
             $hostfilter,
38 38
             //'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
39
-            array('__name','name','display_name','address','address6')
39
+            array('__name', 'name', 'display_name', 'address', 'address6')
40 40
             );
41
-        foreach ( array_keys($hosts) as $key )
41
+        foreach (array_keys($hosts) as $key)
42 42
         {
43
-            $hosts[$key]->id = $hosts[$key]->__name;
44
-            $hosts[$key]->ip4 = $hosts[$key]->address;
45
-            $hosts[$key]->ip6 = $hosts[$key]->address6;
43
+            $hosts[$key]->id=$hosts[$key]->__name;
44
+            $hosts[$key]->ip4=$hosts[$key]->address;
45
+            $hosts[$key]->ip6=$hosts[$key]->address6;
46 46
         }
47 47
         return $hosts;
48 48
     }
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
      */
56 56
     public function getHostByIP(string $ip) 
57 57
     {
58
-        return $this->getHostByFilter('match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6)');
58
+        return $this->getHostByFilter('match("*'.$ip.'*",host.address) || match("*'.$ip.'*",host.address6)');
59 59
     }
60 60
 
61 61
     
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
      */
67 67
     public function getHostByName(string $name)
68 68
     {
69
-        return $this->getHostByFilter('match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name)');
69
+        return $this->getHostByFilter('match("*'.$name.'*",host.name) || match("*'.$name.'*",host.display_name)');
70 70
     }
71 71
 
72 72
     /**
@@ -77,13 +77,13 @@  discard block
 block discarded – undo
77 77
     public function getHostByNameOrIP(string $name)
78 78
     {
79 79
         return $this->getHostByFilter( 
80
-            'match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name) || match("*' . $name . '*",host.address) || match("*' . $name . '*",host.address6)');
80
+            'match("*'.$name.'*",host.name) || match("*'.$name.'*",host.display_name) || match("*'.$name.'*",host.address) || match("*'.$name.'*",host.address6)');
81 81
     }
82 82
     
83 83
     public function getHostInfoByID(string $name)
84 84
     {
85
-        $host = $this->getHostByFilter(
86
-            'host.__name=="'. $name .'"');
85
+        $host=$this->getHostByFilter(
86
+            'host.__name=="'.$name.'"');
87 87
         if (isset($host[0]))
88 88
             return $host[0];
89 89
         else
@@ -100,8 +100,8 @@  discard block
 block discarded – undo
100 100
     {        
101 101
         return $this->standardQuery(
102 102
             'host', 
103
-            '"' . $hostGroup . '" in host.groups',
104
-            array('address','address6','name')
103
+            '"'.$hostGroup.'" in host.groups',
104
+            array('address', 'address6', 'name')
105 105
                 
106 106
         );
107 107
     }
@@ -115,26 +115,26 @@  discard block
 block discarded – undo
115 115
      *  @param bool $passive_svc
116 116
      *	@return array display_name (of service), service_object_id
117 117
      */
118
-    public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
118
+    public function getServicesByHostid(string $id, bool $active=TRUE, bool $passive_svc=TRUE)
119 119
     {
120
-        $filter = 'match("' . $id . '!*", service.__name)';
120
+        $filter='match("'.$id.'!*", service.__name)';
121 121
         if ($active === TRUE)
122 122
         {
123
-            $filter .= ' && service.active==true';
123
+            $filter.=' && service.active==true';
124 124
         }
125 125
         if ($passive_svc === TRUE)
126 126
         {
127
-            $filter .= ' && service.enable_passive_checks==true';
127
+            $filter.=' && service.enable_passive_checks==true';
128 128
         }
129
-        $services =  $this->standardQuery(
129
+        $services=$this->standardQuery(
130 130
             'service',
131 131
             $filter,
132
-            array('__name','name','display_name','active')
132
+            array('__name', 'name', 'display_name', 'active')
133 133
             );
134 134
         
135
-        foreach ( array_keys($services) as $key )
135
+        foreach (array_keys($services) as $key)
136 136
         {
137
-            $services[$key]->id = $services[$key]->__name;
137
+            $services[$key]->id=$services[$key]->__name;
138 138
         }
139 139
         
140 140
         return $services;
@@ -152,27 +152,27 @@  discard block
 block discarded – undo
152 152
     {
153 153
          return $this->standardQuery(
154 154
             'host',
155
-            '"' . $group . '" in host.groups',
156
-            array('name','display_name')
155
+            '"'.$group.'" in host.groups',
156
+            array('name', 'display_name')
157 157
             );
158 158
     }
159 159
     
160 160
     public function getServicesByHostGroupid(string $group)
161 161
     {
162
-        $hostList = $this->getHostsByGroup($group);
162
+        $hostList=$this->getHostsByGroup($group);
163 163
         //return $hostList;
164
-        $hostNum = count($hostList);
164
+        $hostNum=count($hostList);
165 165
         $serviceList=array();
166 166
         foreach ($hostList as $curHost)
167 167
         {
168
-            $services = $this->getServicesByHostid($curHost->name);
168
+            $services=$this->getServicesByHostid($curHost->name);
169 169
             foreach ($services as $service)
170 170
             {
171 171
                 //return $service;
172
-                if (! isset($serviceList[$service->name]))
172
+                if (!isset($serviceList[$service->name]))
173 173
                 {
174 174
                     $serviceList[$service->name]=
175
-                        array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
175
+                        array('num'=> 1, '__name' => $service->__name, 'display_name' => $service->display_name);
176 176
                 }
177 177
                 else
178 178
                 {
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
         {
186 186
             if ($values['num'] >= $hostNum)
187 187
             {
188
-                array_push($commonServices,array($key,$values['display_name']));
188
+                array_push($commonServices, array($key, $values['display_name']));
189 189
             }
190 190
         }
191 191
         return $commonServices;
@@ -199,15 +199,15 @@  discard block
 block discarded – undo
199 199
      */
200 200
     public function getHostGroupByName($name)
201 201
     {
202
-        $hosts = $this->standardQuery(
202
+        $hosts=$this->standardQuery(
203 203
             'hostgroup',
204
-            'match("*' . $name . '*",hostgroup.name)',
205
-            array('__name','name','display_name')
204
+            'match("*'.$name.'*",hostgroup.name)',
205
+            array('__name', 'name', 'display_name')
206 206
             
207 207
             );
208
-        foreach ( array_keys($hosts) as $key )
208
+        foreach (array_keys($hosts) as $key)
209 209
         {
210
-            $hosts[$key]->id = $hosts[$key]->__name;
210
+            $hosts[$key]->id=$hosts[$key]->__name;
211 211
         }
212 212
         return $hosts;
213 213
     }
@@ -220,13 +220,13 @@  discard block
 block discarded – undo
220 220
      */
221 221
     public function getHostGroupById($name)
222 222
     {
223
-        $hosts = $this->standardQuery(
223
+        $hosts=$this->standardQuery(
224 224
             'hostgroup',
225
-            'hostgroup.__name=="'. $name .'"',
226
-            array('__name','name','display_name')
225
+            'hostgroup.__name=="'.$name.'"',
226
+            array('__name', 'name', 'display_name')
227 227
             
228 228
             );
229
-        $hosts[0]->id = $hosts[0]->__name;
229
+        $hosts[0]->id=$hosts[0]->__name;
230 230
         return $hosts[0];
231 231
     }
232 232
     
@@ -239,26 +239,26 @@  discard block
 block discarded – undo
239 239
      *  @param bool $passive_svc : if true, return only service accepting passive checks
240 240
      *	@return array  service id
241 241
      */
242
-    public function getServiceIDByName($hostname,$name,bool $active = TRUE, bool $passive_svc = TRUE)
242
+    public function getServiceIDByName($hostname, $name, bool $active=TRUE, bool $passive_svc=TRUE)
243 243
     {
244
-        $filter = 'service.__name=="' . $hostname . '!'. $name .'"';
244
+        $filter='service.__name=="'.$hostname.'!'.$name.'"';
245 245
         if ($active === TRUE)
246 246
         {
247
-            $filter .= ' && service.active==true';
247
+            $filter.=' && service.active==true';
248 248
         }
249 249
         if ($passive_svc === TRUE)
250 250
         {
251
-            $filter .= ' && service.enable_passive_checks==true';
251
+            $filter.=' && service.enable_passive_checks==true';
252 252
         }
253
-        $services =  $this->standardQuery(
253
+        $services=$this->standardQuery(
254 254
             'service',
255 255
             $filter,
256
-            array('__name','name','display_name','active','enable_passive_checks')
256
+            array('__name', 'name', 'display_name', 'active', 'enable_passive_checks')
257 257
             );
258 258
         
259
-        foreach ( array_keys($services) as $key )
259
+        foreach (array_keys($services) as $key)
260 260
         {
261
-            $services[$key]->id = $services[$key]->__name;
261
+            $services[$key]->id=$services[$key]->__name;
262 262
         }
263 263
         
264 264
         return $services;
@@ -271,16 +271,16 @@  discard block
 block discarded – undo
271 271
      */
272 272
     public function getServiceById($name)
273 273
     {
274
-        $filter = 'service.__name=="' .  $name .'"';
275
-        $services =  $this->standardQuery(
274
+        $filter='service.__name=="'.$name.'"';
275
+        $services=$this->standardQuery(
276 276
             'service',
277 277
             $filter,
278
-            array('__name','name','display_name','active','enable_passive_checks')
278
+            array('__name', 'name', 'display_name', 'active', 'enable_passive_checks')
279 279
             );
280 280
         
281
-        foreach ( array_keys($services) as $key )
281
+        foreach (array_keys($services) as $key)
282 282
         {
283
-            $services[$key]->id = $services[$key]->__name;
283
+            $services[$key]->id=$services[$key]->__name;
284 284
         }
285 285
         
286 286
         return $services;
@@ -293,16 +293,16 @@  discard block
 block discarded – undo
293 293
      */
294 294
     public function getNOKService()
295 295
     {
296
-        $filter = 'service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
-        $services =  $this->standardQuery(
296
+        $filter='service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
+        $services=$this->standardQuery(
298 298
             'service',
299 299
             $filter,
300
-            array('__name','name','last_check','host_name','state')
300
+            array('__name', 'name', 'last_check', 'host_name', 'state')
301 301
             );
302 302
         
303
-        foreach ( array_keys($services) as $key )
303
+        foreach (array_keys($services) as $key)
304 304
         {
305
-            $services[$key]->id = $services[$key]->__name;
305
+            $services[$key]->id=$services[$key]->__name;
306 306
         }
307 307
         
308 308
         return $services;
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/MibDatabase.php 1 patch
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -60,9 +60,9 @@  discard block
 block discarded – undo
60 60
         }
61 61
         $oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
62 62
         $dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
63
-        if ( $this->oidDesc['name'] != $dbOid['name'] ||
63
+        if ($this->oidDesc['name'] != $dbOid['name'] ||
64 64
             $this->oidDesc['mib'] != $dbOid['mib'] ||
65
-            $this->oidDesc['type'] !=$dbOid['type']
65
+            $this->oidDesc['type'] != $dbOid['type']
66 66
             )
67 67
         { // Do update
68 68
             $sql='UPDATE '.$this->getTrapsDB()->dbPrefix.'mib_cache SET '.
@@ -75,24 +75,24 @@  discard block
 block discarded – undo
75 75
                 ':name' => $this->oidDesc['name'],
76 76
                 ':type' => $this->oidDesc['type'],
77 77
                 ':mib' => $this->oidDesc['mib'],
78
-                ':tc' =>  $this->oidDesc['textconv']??'null',
79
-                ':display_hint' => $this->oidDesc['dispHint']??'null' ,
80
-                ':syntax' => $this->oidDesc['syntax']==null??'null',
81
-                ':type_enum' => $this->oidDesc['type_enum']??'null',
82
-                ':description' => $this->oidDesc['description']??'null',
78
+                ':tc' =>  $this->oidDesc['textconv'] ?? 'null',
79
+                ':display_hint' => $this->oidDesc['dispHint'] ?? 'null',
80
+                ':syntax' => $this->oidDesc['syntax'] == null ?? 'null',
81
+                ':type_enum' => $this->oidDesc['type_enum'] ?? 'null',
82
+                ':description' => $this->oidDesc['description'] ?? 'null',
83 83
                 ':id' => $this->dbOidIndex[$this->oidDesc['oid']]['id']
84 84
 //                ':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
85 85
             );
86 86
             
87 87
             if ($sqlQuery->execute($sqlParam) === false) {
88
-                $this->getLogging()->log('Error in query : ' . $sql,ERROR,'');
88
+                $this->getLogging()->log('Error in query : '.$sql, ERROR, '');
89 89
             }
90
-            $this->getLogging()->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
90
+            $this->getLogging()->log('Trap updated : '.$this->oidDesc['name'].' / OID : '.$this->oidDesc['oid'], DEBUG);
91 91
             return 1;
92 92
         }
93 93
         else
94 94
         {
95
-            $this->getLogging()->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
95
+            $this->getLogging()->log('Trap unchanged : '.$this->oidDesc['name'].' / OID : '.$this->oidDesc['oid'], DEBUG);
96 96
             return 0;
97 97
         }
98 98
     }
@@ -108,11 +108,11 @@  discard block
 block discarded – undo
108 108
         $db_conn=$this->getTrapsDB()->db_connect_trap();
109 109
         $sql='INSERT INTO '.$this->getTrapsDB()->dbPrefix.'mib_cache '.
110 110
             '(oid, name, type , mib, textual_convention, display_hint '.
111
-            ', syntax, type_enum , description ) ' .
111
+            ', syntax, type_enum , description ) '.
112 112
             'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
113 113
             ', :syntax, :type_enum, :description )';
114 114
         
115
-        if ($this->getTrapsDB()->trapDBType == 'pgsql') $sql .= 'RETURNING id';
115
+        if ($this->getTrapsDB()->trapDBType == 'pgsql') $sql.='RETURNING id';
116 116
         
117 117
         $sqlQuery=$db_conn->prepare($sql);
118 118
         
@@ -121,15 +121,15 @@  discard block
 block discarded – undo
121 121
             ':name' => $this->oidDesc['name'],
122 122
             ':type' => $this->oidDesc['type'],
123 123
             ':mib' => $this->oidDesc['mib'],
124
-            ':tc' =>  $this->oidDesc['textconv']??'null',
125
-            ':display_hint' => $this->oidDesc['dispHint']??'null',
126
-            ':syntax' => $this->oidDesc['syntax']??'null',
127
-            ':type_enum' => $this->oidDesc['type_enum']??'null',
128
-            ':description' => $this->oidDesc['description']??'null'
124
+            ':tc' =>  $this->oidDesc['textconv'] ?? 'null',
125
+            ':display_hint' => $this->oidDesc['dispHint'] ?? 'null',
126
+            ':syntax' => $this->oidDesc['syntax'] ?? 'null',
127
+            ':type_enum' => $this->oidDesc['type_enum'] ?? 'null',
128
+            ':description' => $this->oidDesc['description'] ?? 'null'
129 129
         );
130 130
         
131 131
         if ($sqlQuery->execute($sqlParam) === false) {
132
-            $this->getLogging()->log('Error in query : ' . $sql,1,'');
132
+            $this->getLogging()->log('Error in query : '.$sql, 1, '');
133 133
         }
134 134
         
135 135
         switch ($this->getTrapsDB()->trapDBType)
@@ -137,10 +137,10 @@  discard block
 block discarded – undo
137 137
             case 'pgsql':
138 138
                 // Get last id to insert oid/values in secondary table
139 139
                 if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
140
-                    $this->getLogging()->log('Error getting id - pgsql - ',1,'');
140
+                    $this->getLogging()->log('Error getting id - pgsql - ', 1, '');
141 141
                 }
142
-                if (! isset($inserted_id_ret['id'])) {
143
-                    $this->getLogging()->log('Error getting id - pgsql - empty.',ERROR);
142
+                if (!isset($inserted_id_ret['id'])) {
143
+                    $this->getLogging()->log('Error getting id - pgsql - empty.', ERROR);
144 144
                     return 0;
145 145
                 }
146 146
                 $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
@@ -149,16 +149,16 @@  discard block
 block discarded – undo
149 149
                 // Get last id to insert oid/values in secondary table
150 150
                 $sql='SELECT LAST_INSERT_ID();';
151 151
                 if (($ret_code=$db_conn->query($sql)) === false) {
152
-                    $this->getLogging()->log('Erreur getting id - mysql - ',ERROR);
152
+                    $this->getLogging()->log('Erreur getting id - mysql - ', ERROR);
153 153
                     return 0;
154 154
                 }
155 155
                 
156 156
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
157
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
157
+                if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
158 158
                 $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
159 159
                 break;
160 160
             default:
161
-                $this->getLogging()->log('Error SQL type Unknown : '.$this->getTrapsDB()->trapDBType,ERROR);
161
+                $this->getLogging()->log('Error SQL type Unknown : '.$this->getTrapsDB()->trapDBType, ERROR);
162 162
                 return 0;
163 163
         }
164 164
         
@@ -178,9 +178,9 @@  discard block
 block discarded – undo
178 178
         $db_conn=$this->getTrapsDB()->db_connect_trap();
179 179
         // Get all objects
180 180
         $sql='SELECT * FROM '.$this->getTrapsDB()->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
181
-        $this->getLogging()->log('SQL query get all traps: '.$sql,DEBUG );
181
+        $this->getLogging()->log('SQL query get all traps: '.$sql, DEBUG);
182 182
         if (($ret_code=$db_conn->query($sql)) === false) {
183
-            $this->getLogging()->log('No result in query : ' . $sql,1,'');
183
+            $this->getLogging()->log('No result in query : '.$sql, 1, '');
184 184
         }
185 185
         $dbObjectsRaw=$ret_code->fetchAll();
186 186
         
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/TrapConfig.php 1 patch
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -36,15 +36,15 @@  discard block
 block discarded – undo
36 36
      * @param string $message warning message if not found
37 37
      * @return boolean true if found, or false
38 38
      */
39
-    protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = WARN, $message = null)
39
+    protected function getOptionIfSet($option_array, $option_category, $option_name, &$option_var, $log_level=WARN, $message=null)
40 40
     {
41 41
         if (!isset($option_array[$option_category][$option_name]))
42 42
         {
43 43
             if ($message === null)
44 44
             {
45
-                $message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
45
+                $message='No '.$option_name.' in config file: '.$this->trapModuleConfig;
46 46
             }
47
-            $this->getLogging()->log($message,$log_level);
47
+            $this->getLogging()->log($message, $log_level);
48 48
             return false;
49 49
         }
50 50
         else
@@ -62,24 +62,24 @@  discard block
 block discarded – undo
62 62
         // Database options
63 63
         if ($this->logSetup === false) // Only if logging was no setup in constructor
64 64
         {
65
-            $this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
66
-            $this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
67
-            $this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
65
+            $this->getDBConfigIfSet('log_level', $this->getLogging()->debugLevel);
66
+            $this->getDBConfigIfSet('log_destination', $this->getLogging()->outputMode);
67
+            $this->getDBConfigIfSet('log_file', $this->getLogging()->outputFile);
68 68
         }
69 69
         
70
-        $tmpVal = -1; // Get boolean coded in database as 1/0
70
+        $tmpVal=-1; // Get boolean coded in database as 1/0
71 71
         $this->getDBConfigIfSet('use_SnmpTrapAddess', $tmpVal);
72
-        if ($tmpVal != -1) $this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
72
+        if ($tmpVal != -1) $this->useSnmpTrapAddess=($tmpVal == 1) ? TRUE : FALSE;
73 73
         
74 74
         $this->getDBConfigIfSet('SnmpTrapAddess_oid', $this->snmpTrapAddressOID); // Get oid then replace '.' with '\.' to use in regexp whrn reading traps
75
-        $this->snmpTrapAddressOID = preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
75
+        $this->snmpTrapAddressOID=preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
76 76
     }
77 77
         
78 78
     /** Set $variable to value if $element found in database config table
79 79
      * @param string $element
80 80
      * @param string $variable
81 81
      */
82
-    protected function getDBConfigIfSet($element,&$variable)
82
+    protected function getDBConfigIfSet($element, &$variable)
83 83
     {
84 84
         $value=$this->getDBConfig($element);
85 85
         if ($value != null) $variable=$value;
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
         $db_conn=$this->trapsDB->db_connect_trap();
96 96
         $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
97 97
         if (($ret_code=$db_conn->query($sql)) === false) {
98
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
98
+            $this->logging->log('No result in query : '.$sql, WARN, '');
99 99
             return null;
100 100
         }
101 101
         $value=$ret_code->fetch();
@@ -114,10 +114,10 @@  discard block
 block discarded – undo
114 114
     {
115 115
         
116 116
         $nodeStatus='';
117
-        $this->getOptionIfSet($trapConfig,'config','node', $nodeStatus);
117
+        $this->getOptionIfSet($trapConfig, 'config', 'node', $nodeStatus);
118 118
         if ($this->getTrapApi()->setStatus($nodeStatus) === FALSE)
119 119
         {
120
-            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
120
+            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER', WARN);
121 121
             $this->getTrapApi()->setStatusMaster();
122 122
         }
123 123
         else 
@@ -125,36 +125,36 @@  discard block
 block discarded – undo
125 125
             if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
126 126
             {
127 127
                 // Get options to connect to API
128
-                $IP = $port = $user =  $pass = null;
129
-                $this->getOptionIfSet($trapConfig,'config','masterIP', $IP, ERROR);
130
-                $this->getOptionIfSet($trapConfig,'config','masterPort', $port, ERROR);
131
-                $this->getOptionIfSet($trapConfig,'config','masterUser', $user, ERROR);
132
-                $this->getOptionIfSet($trapConfig,'config','masterPass', $pass, ERROR);
128
+                $IP=$port=$user=$pass=null;
129
+                $this->getOptionIfSet($trapConfig, 'config', 'masterIP', $IP, ERROR);
130
+                $this->getOptionIfSet($trapConfig, 'config', 'masterPort', $port, ERROR);
131
+                $this->getOptionIfSet($trapConfig, 'config', 'masterUser', $user, ERROR);
132
+                $this->getOptionIfSet($trapConfig, 'config', 'masterPass', $pass, ERROR);
133 133
                 $this->getTrapApi()->setParams($IP, $port, $user, $pass);
134 134
                 return;
135 135
             }
136 136
         }
137 137
         
138 138
         // Snmptranslate binary path
139
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
139
+        $this->getOptionIfSet($trapConfig, 'config', 'snmptranslate', $this->snmptranslate);
140 140
         
141 141
         // mibs path
142
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
142
+        $this->getOptionIfSet($trapConfig, 'config', 'snmptranslate_dirs', $this->snmptranslate_dirs);
143 143
         
144 144
         // icinga2cmd path
145
-        $this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
145
+        $this->getOptionIfSet($trapConfig, 'config', 'icingacmd', $this->icinga2cmd);
146 146
         
147 147
         // table prefix
148
-        $this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
148
+        $this->getOptionIfSet($trapConfig, 'config', 'database_prefix', $this->dbPrefix);
149 149
         
150 150
         // API options
151
-        if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
151
+        if ($this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_host', $this->apiHostname))
152 152
         {
153 153
             $this->apiUse=true;
154 154
             // Get API options or throw exception as not configured correctly
155
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort,ERROR);
156
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername,ERROR);
157
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword,ERROR);
155
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_port', $this->apiPort, ERROR);
156
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_user', $this->apiUsername, ERROR);
157
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_password', $this->apiPassword, ERROR);
158 158
         }
159 159
     }
160 160
     
@@ -165,43 +165,43 @@  discard block
 block discarded – undo
165 165
     protected function setupDatabase($trapConfig)
166 166
     {
167 167
         // Trap database
168
-        if (!array_key_exists('database',$trapConfig['config']))
168
+        if (!array_key_exists('database', $trapConfig['config']))
169 169
         {
170
-            $this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
170
+            $this->logging->log("No database in config file: ".$this->trapModuleConfig, ERROR, '');
171 171
             return;
172 172
         }
173 173
         $dbTrapName=$trapConfig['config']['database'];
174
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
174
+        $this->logging->log("Found database in config file: ".$dbTrapName, INFO);
175 175
         
176
-        if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
176
+        if (($dbConfig=parse_ini_file($this->icingaweb2Ressources, true)) === false)
177 177
         {
178
-            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
178
+            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources, ERROR, '');
179 179
             return;
180 180
         }
181
-        if (!array_key_exists($dbTrapName,$dbConfig))
181
+        if (!array_key_exists($dbTrapName, $dbConfig))
182 182
         {
183
-            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
183
+            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources, ERROR, '');
184 184
             return;
185 185
         }
186 186
         
187
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
187
+        $this->trapsDB=new Database($this->logging, $dbConfig[$dbTrapName], $this->dbPrefix);
188 188
         
189
-        $this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG );
189
+        $this->logging->log("API Use : ".print_r($this->apiUse, true), DEBUG);
190 190
         
191 191
         //TODO enable this again when API queries are all done :
192 192
         if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
193 193
         
194 194
         // IDO Database
195
-        if (!array_key_exists('IDOdatabase',$trapConfig['config']))
195
+        if (!array_key_exists('IDOdatabase', $trapConfig['config']))
196 196
         {
197
-            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
197
+            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig, ERROR, '');
198 198
         }
199 199
         $dbIdoName=$trapConfig['config']['IDOdatabase'];
200 200
         
201
-        $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
202
-        if (!array_key_exists($dbIdoName,$dbConfig))
201
+        $this->logging->log("Found IDO database in config file: ".$dbIdoName, INFO);
202
+        if (!array_key_exists($dbIdoName, $dbConfig))
203 203
         {
204
-            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
204
+            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources, ERROR, '');
205 205
             return;
206 206
         }
207 207
         
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Trap.php 1 patch
Spacing   +183 added lines, -183 removed lines patch added patch discarded remove patch
@@ -52,13 +52,13 @@  discard block
 block discarded – undo
52 52
     
53 53
     // Logs
54 54
     /** @var Logging Logging class. */
55
-    public $logging;    //< Logging class.
55
+    public $logging; //< Logging class.
56 56
     /** @var bool true if log was setup in constructor */
57
-    protected $logSetup;   //< bool true if log was setup in constructor
57
+    protected $logSetup; //< bool true if log was setup in constructor
58 58
     
59 59
     // Databases
60 60
     /** @var Database $trapsDB  Database class*/
61
-    public $trapsDB = null;
61
+    public $trapsDB=null;
62 62
     
63 63
     // Trap received data
64 64
     protected $receivingHost;
@@ -74,18 +74,18 @@  discard block
 block discarded – undo
74 74
     protected $trapToDb=true;
75 75
     
76 76
     /** @var Mib mib class */
77
-    public $mibClass = null;
77
+    public $mibClass=null;
78 78
     
79 79
     /** @var Rule rule class */
80
-    public $ruleClass = null;
80
+    public $ruleClass=null;
81 81
     
82 82
     /** @var Plugins plugins manager **/
83
-    public $pluginClass = null;
83
+    public $pluginClass=null;
84 84
     
85 85
     /** @var TrapApi $trapApiClass */
86
-    public $trapApiClass = null;
86
+    public $trapApiClass=null;
87 87
     
88
-    function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
88
+    function __construct($etcDir='/etc/icingaweb2', $baseLogLevel=null, $baseLogMode='syslog', $baseLogFile='')
89 89
     {
90 90
         // Paths of ini files
91 91
         $this->icingaweb2Etc=$etcDir;
@@ -93,10 +93,10 @@  discard block
 block discarded – undo
93 93
         $this->icingaweb2Ressources=$this->icingaweb2Etc."/resources.ini";
94 94
 
95 95
         // Setup logging
96
-        $this->logging = new Logging();
96
+        $this->logging=new Logging();
97 97
         if ($baseLogLevel != null)
98 98
         {
99
-            $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
99
+            $this->logging->setLogging($baseLogLevel, $baseLogMode, $baseLogFile);
100 100
             $this->logSetup=true;
101 101
         }
102 102
         else
@@ -108,17 +108,17 @@  discard block
 block discarded – undo
108 108
         
109 109
         // Create distributed API object
110 110
         
111
-        $this->trapApiClass = new TrapApi($this->logging);
111
+        $this->trapApiClass=new TrapApi($this->logging);
112 112
         
113 113
         // Get options from ini files
114
-        if (! is_file($this->trapModuleConfig))
114
+        if (!is_file($this->trapModuleConfig))
115 115
         {
116 116
             throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
117 117
         }
118
-        $trapConfig=parse_ini_file($this->trapModuleConfig,true);
118
+        $trapConfig=parse_ini_file($this->trapModuleConfig, true);
119 119
         if ($trapConfig == false)
120 120
         {
121
-            $this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
121
+            $this->logging->log("Error reading ini file : ".$this->trapModuleConfig, ERROR, 'syslog');
122 122
             throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
123 123
         }
124 124
         $this->getMainOptions($trapConfig); // Get main options from ini file
@@ -132,10 +132,10 @@  discard block
 block discarded – undo
132 132
         if ($this->apiUse === true) $this->getAPI(); // Setup API
133 133
         
134 134
         // Setup MIB
135
-        $this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
135
+        $this->mibClass=new Mib($this->logging, $this->trapsDB, $this->snmptranslate, $this->snmptranslate_dirs); // Create Mib class
136 136
         
137 137
         // Setup Rule
138
-        $this->ruleClass = new Rule($this); //< Create Rule class
138
+        $this->ruleClass=new Rule($this); //< Create Rule class
139 139
         
140 140
         $this->trapData=array(  // TODO : put this in a reset function (DAEMON_MODE)
141 141
             'source_ip'	=> 'unknown',
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
         
148 148
         // Setup Plugins
149 149
         //Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
150
-        $this->pluginClass = new Plugins($this);
150
+        $this->pluginClass=new Plugins($this);
151 151
             
152 152
             
153 153
     }
@@ -176,15 +176,15 @@  discard block
 block discarded – undo
176 176
      *	@param  string $destination file/syslog/display
177 177
      *	@return void
178 178
      **/
179
-    public function trapLog( $message, $level, $destination ='') // OBSOLETE
179
+    public function trapLog($message, $level, $destination='') // OBSOLETE
180 180
     {
181 181
         // TODO : replace ref with $this->logging->log
182 182
         $this->logging->log($message, $level, $destination);
183 183
     }
184 184
     
185
-    public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
185
+    public function setLogging($debugLvl, $outputType, $outputOption=null)  // OBSOLETE
186 186
     {
187
-        $this->logging->setLogging($debugLvl, $outputType,$outputOption);
187
+        $this->logging->setLogging($debugLvl, $outputType, $outputOption);
188 188
     }
189 189
     
190 190
     /**
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
     {
196 196
         if ($this->icinga2api == null)
197 197
         {
198
-            $this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
198
+            $this->icinga2api=new Icinga2API($this->apiHostname, $this->apiPort);
199 199
         }
200 200
         return $this->icinga2api;
201 201
     }
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
         if ($input_stream === false)
215 215
         {
216 216
             $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
217
-            $this->logging->log("Error reading stdin !",ERROR,'');
217
+            $this->logging->log("Error reading stdin !", ERROR, '');
218 218
             return null; // note : exception thrown by logging
219 219
         }
220 220
         
@@ -223,21 +223,21 @@  discard block
 block discarded – undo
223 223
         if ($this->receivingHost === false)
224 224
         {
225 225
             $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
226
-            $this->logging->log("Error reading Host !",ERROR,'');
226
+            $this->logging->log("Error reading Host !", ERROR, '');
227 227
         }
228 228
         // line 2 IP:port=>IP:port
229 229
         $IP=chop(fgets($input_stream));
230 230
         if ($IP === false)
231 231
         {
232 232
             $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
233
-            $this->logging->log("Error reading IP !",ERROR,'');
233
+            $this->logging->log("Error reading IP !", ERROR, '');
234 234
         }
235 235
         $matches=array();
236
-        $ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
237
-        if ($ret_code===0 || $ret_code===false)
236
+        $ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/', $IP, $matches);
237
+        if ($ret_code === 0 || $ret_code === false)
238 238
         {
239 239
             $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
240
-            $this->logging->log('Error parsing IP : '.$IP,ERROR,'');
240
+            $this->logging->log('Error parsing IP : '.$IP, ERROR, '');
241 241
         }
242 242
         else
243 243
         {
@@ -247,41 +247,41 @@  discard block
 block discarded – undo
247 247
             $this->trapData['destination_port']=$matches[4];
248 248
         }
249 249
         
250
-        while (($vars=fgets($input_stream)) !==false)
250
+        while (($vars=fgets($input_stream)) !== false)
251 251
         {
252 252
             $vars=chop($vars);
253
-            $ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
254
-            if ($ret_code===0 || $ret_code===false)
253
+            $ret_code=preg_match('/^([^ ]+) (.*)$/', $vars, $matches);
254
+            if ($ret_code === 0 || $ret_code === false)
255 255
             {
256
-                $this->logging->log('No match on trap data : '.$vars,WARN,'');
256
+                $this->logging->log('No match on trap data : '.$vars, WARN, '');
257 257
                 continue;
258 258
             }
259
-            if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
259
+            if (($matches[1] == '.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1] == '.1.3.6.1.6.3.1.1.4.1'))
260 260
             {
261 261
                 $this->trapData['trap_oid']=$matches[2];
262 262
                 continue;
263 263
             }
264
-            if ( $this->useSnmpTrapAddess === TRUE &&  preg_match('/'.$this->snmpTrapAddressOID.'/', $matches[1]) == 1)
264
+            if ($this->useSnmpTrapAddess === TRUE && preg_match('/'.$this->snmpTrapAddressOID.'/', $matches[1]) == 1)
265 265
             {
266
-                $this->logging->log('Found relayed trap from ' . $matches[2] . ' relayed by ' .$this->trapData['source_ip'],DEBUG);
267
-                if (preg_match('/^[0-9\.]+$/',$matches[2]) == 0 && preg_match('/^[0-9a-fA-F:]+$/',$matches[2]) == 0)
266
+                $this->logging->log('Found relayed trap from '.$matches[2].' relayed by '.$this->trapData['source_ip'], DEBUG);
267
+                if (preg_match('/^[0-9\.]+$/', $matches[2]) == 0 && preg_match('/^[0-9a-fA-F:]+$/', $matches[2]) == 0)
268 268
                 {
269
-                    $this->logging->log('Value of SnmpTrapAddess ('.$this->snmpTrapAddressOID.') is not IP : ' .$matches[2],WARN,'');
269
+                    $this->logging->log('Value of SnmpTrapAddess ('.$this->snmpTrapAddressOID.') is not IP : '.$matches[2], WARN, '');
270 270
                     continue;
271 271
                 }
272
-                $this->trapData['source_ip'] = $matches[2];
272
+                $this->trapData['source_ip']=$matches[2];
273 273
                 continue;
274 274
             }
275
-            $object= new stdClass;
276
-            $object->oid =$matches[1];
277
-            $object->value = $matches[2];
278
-            array_push($this->trapDataExt,$object);
275
+            $object=new stdClass;
276
+            $object->oid=$matches[1];
277
+            $object->value=$matches[2];
278
+            array_push($this->trapDataExt, $object);
279 279
         }
280 280
         
281
-        if ($this->trapData['trap_oid']=='unknown')
281
+        if ($this->trapData['trap_oid'] == 'unknown')
282 282
         {
283
-            $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trapData['source_ip']);
284
-            $this->logging->log('no trap oid found',ERROR,'');
283
+            $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)", $this->trapData['source_ip']);
284
+            $this->logging->log('no trap oid found', ERROR, '');
285 285
         }
286 286
         
287 287
         // Translate oids.
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
         }
304 304
         
305 305
         
306
-        $this->trapData['status']= 'waiting';
306
+        $this->trapData['status']='waiting';
307 307
         
308 308
         return $this->trapData;
309 309
     }
@@ -319,38 +319,38 @@  discard block
 block discarded – undo
319 319
         $db_conn=$this->trapsDB->db_connect_trap();
320 320
         
321 321
         $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
322
-        $this->logging->log('SQL query : '.$sql,DEBUG );
322
+        $this->logging->log('SQL query : '.$sql, DEBUG);
323 323
         if (($ret_code=$db_conn->query($sql)) === false) {
324
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
324
+            $this->logging->log('No result in query : '.$sql, ERROR, '');
325 325
         }
326 326
         else {
327 327
             if (($name=$ret_code->fetch()) !== false)
328
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
328
+                return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
329 329
         }
330 330
         
331 331
         // Also check if it is an instance of OID
332
-        $oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
332
+        $oid_instance=preg_replace('/\.[0-9]+$/', '', $oid);
333 333
         
334 334
         $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
335
-        $this->logging->log('SQL query : '.$sql,DEBUG );
335
+        $this->logging->log('SQL query : '.$sql, DEBUG);
336 336
         if (($ret_code=$db_conn->query($sql)) === false) {
337
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
337
+            $this->logging->log('No result in query : '.$sql, ERROR, '');
338 338
         }
339 339
         else {
340 340
             if (($name=$ret_code->fetch()) !== false)
341
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
341
+                return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
342 342
         }
343 343
         
344 344
         // Try to get oid name from snmptranslate
345
-        $translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
345
+        $translate=exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
346 346
             ' '.$oid);
347 347
         $matches=array();
348
-        $ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
349
-        if ($ret_code===0 || $ret_code === false) {
348
+        $ret_code=preg_match('/(.*)::(.*)/', $translate, $matches);
349
+        if ($ret_code === 0 || $ret_code === false) {
350 350
             return NULL;
351 351
         } else {
352
-            $this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
353
-            return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
352
+            $this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid, INFO);
353
+            return array('trap_name_mib'=>$matches[1], 'trap_name'=>$matches[2]);
354 354
         }
355 355
     }
356 356
     
@@ -361,90 +361,90 @@  discard block
 block discarded – undo
361 361
      **/
362 362
     public function eraseOldTraps($days=0)
363 363
     {
364
-        if ($days==0)
364
+        if ($days == 0)
365 365
         {
366 366
             if (($days=$this->getDBConfig('db_remove_days')) == null)
367 367
             {
368
-                $this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
368
+                $this->logging->log('No days specified & no db value : no tap erase', WARN, '');
369 369
                 return;
370 370
             }
371 371
         }
372 372
         $db_conn=$this->trapsDB->db_connect_trap();
373
-        $daysago = strtotime("-".$days." day");
374
-        $sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
373
+        $daysago=strtotime("-".$days." day");
374
+        $sql='delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s", $daysago).'\';';
375 375
         if ($db_conn->query($sql) === false) {
376
-            $this->logging->log('Error erasing traps : '.$sql,ERROR,'');
376
+            $this->logging->log('Error erasing traps : '.$sql, ERROR, '');
377 377
         }
378
-        $this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
378
+        $this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql, INFO);
379 379
     }
380 380
     
381 381
     /** Write error to received trap database
382 382
      */
383
-    public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
383
+    public function writeTrapErrorToDB($message, $sourceIP=null, $trapoid=null)
384 384
     {
385 385
         
386 386
         $db_conn=$this->trapsDB->db_connect_trap();
387 387
         
388 388
         // add date time
389
-        $insert_col ='date_received,status';
390
-        $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
389
+        $insert_col='date_received,status';
390
+        $insert_val="'".date("Y-m-d H:i:s")."','error'";
391 391
         
392
-        if ($sourceIP !=null)
392
+        if ($sourceIP != null)
393 393
         {
394
-            $insert_col .=',source_ip';
395
-            $insert_val .=",'". $sourceIP ."'";
394
+            $insert_col.=',source_ip';
395
+            $insert_val.=",'".$sourceIP."'";
396 396
         }
397
-        if ($trapoid !=null)
397
+        if ($trapoid != null)
398 398
         {
399
-            $insert_col .=',trap_oid';
400
-            $insert_val .=",'". $trapoid ."'";
399
+            $insert_col.=',trap_oid';
400
+            $insert_val.=",'".$trapoid."'";
401 401
         }
402
-        $insert_col .=',status_detail';
403
-        $insert_val .=",'". $message ."'";
402
+        $insert_col.=',status_detail';
403
+        $insert_val.=",'".$message."'";
404 404
         
405
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
405
+        $sql='INSERT INTO '.$this->dbPrefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
406 406
         
407 407
         switch ($this->trapsDB->trapDBType)
408 408
         {
409 409
             case 'pgsql':
410
-                $sql .= ' RETURNING id;';
411
-                $this->logging->log('sql : '.$sql,INFO);
410
+                $sql.=' RETURNING id;';
411
+                $this->logging->log('sql : '.$sql, INFO);
412 412
                 if (($ret_code=$db_conn->query($sql)) === false) {
413
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
413
+                    $this->logging->log('Error SQL insert : '.$sql, 1, '');
414 414
                 }
415
-                $this->logging->log('SQL insertion OK',INFO );
415
+                $this->logging->log('SQL insertion OK', INFO);
416 416
                 // Get last id to insert oid/values in secondary table
417 417
                 if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
418 418
                     
419
-                    $this->logging->log('Erreur recuperation id',1,'');
419
+                    $this->logging->log('Erreur recuperation id', 1, '');
420 420
                 }
421
-                if (! isset($inserted_id_ret['id'])) {
422
-                    $this->logging->log('Error getting id',1,'');
421
+                if (!isset($inserted_id_ret['id'])) {
422
+                    $this->logging->log('Error getting id', 1, '');
423 423
                 }
424 424
                 $this->trapId=$inserted_id_ret['id'];
425 425
                 break;
426 426
             case 'mysql':
427
-                $sql .= ';';
428
-                $this->logging->log('sql : '.$sql,INFO );
427
+                $sql.=';';
428
+                $this->logging->log('sql : '.$sql, INFO);
429 429
                 if ($db_conn->query($sql) === false) {
430
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
430
+                    $this->logging->log('Error SQL insert : '.$sql, 1, '');
431 431
                 }
432
-                $this->logging->log('SQL insertion OK',INFO );
432
+                $this->logging->log('SQL insertion OK', INFO);
433 433
                 // Get last id to insert oid/values in secondary table
434 434
                 $sql='SELECT LAST_INSERT_ID();';
435 435
                 if (($ret_code=$db_conn->query($sql)) === false) {
436
-                    $this->logging->log('Erreur recuperation id',1,'');
436
+                    $this->logging->log('Erreur recuperation id', 1, '');
437 437
                 }
438 438
                 
439 439
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
440
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
440
+                if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
441 441
                 $this->trapId=$inserted_id;
442 442
                 break;
443 443
             default:
444
-                $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
444
+                $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType, 1, '');
445 445
         }
446 446
         
447
-        $this->logging->log('id found: '. $this->trapId,INFO );
447
+        $this->logging->log('id found: '.$this->trapId, INFO);
448 448
     }
449 449
     
450 450
     /** Write trap data to trap database
@@ -461,86 +461,86 @@  discard block
 block discarded – undo
461 461
         $insert_col='';
462 462
         $insert_val='';
463 463
         // add date time
464
-        $this->trapData['date_received'] = date("Y-m-d H:i:s");
464
+        $this->trapData['date_received']=date("Y-m-d H:i:s");
465 465
         
466 466
         $firstcol=1;
467 467
         foreach ($this->trapData as $col => $val)
468 468
         {
469
-            if ($firstcol==0)
469
+            if ($firstcol == 0)
470 470
             {
471
-                $insert_col .=',';
472
-                $insert_val .=',';
471
+                $insert_col.=',';
472
+                $insert_val.=',';
473 473
             }
474
-            $insert_col .= $col ;
475
-            $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
474
+            $insert_col.=$col;
475
+            $insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
476 476
             $firstcol=0;
477 477
         }
478 478
         
479
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
479
+        $sql='INSERT INTO '.$this->dbPrefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
480 480
         switch ($this->trapsDB->trapDBType)
481 481
         {
482 482
             case 'pgsql':
483
-                $sql .= ' RETURNING id;';
484
-                $this->logging->log('sql : '.$sql,INFO );
483
+                $sql.=' RETURNING id;';
484
+                $this->logging->log('sql : '.$sql, INFO);
485 485
                 if (($ret_code=$db_conn->query($sql)) === false) {
486
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
486
+                    $this->logging->log('Error SQL insert : '.$sql, ERROR, '');
487 487
                 }
488
-                $this->logging->log('SQL insertion OK',INFO );
488
+                $this->logging->log('SQL insertion OK', INFO);
489 489
                 // Get last id to insert oid/values in secondary table
490 490
                 if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
491 491
                     
492
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
492
+                    $this->logging->log('Erreur recuperation id', ERROR, '');
493 493
                 }
494
-                if (! isset($inserted_id_ret['id'])) {
495
-                    $this->logging->log('Error getting id',ERROR,'');
494
+                if (!isset($inserted_id_ret['id'])) {
495
+                    $this->logging->log('Error getting id', ERROR, '');
496 496
                 }
497 497
                 $this->trapId=$inserted_id_ret['id'];
498 498
                 break;
499 499
             case 'mysql':
500
-                $sql .= ';';
501
-                $this->logging->log('sql : '.$sql,INFO );
500
+                $sql.=';';
501
+                $this->logging->log('sql : '.$sql, INFO);
502 502
                 if ($db_conn->query($sql) === false) {
503
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
503
+                    $this->logging->log('Error SQL insert : '.$sql, ERROR, '');
504 504
                 }
505
-                $this->logging->log('SQL insertion OK',INFO );
505
+                $this->logging->log('SQL insertion OK', INFO);
506 506
                 // Get last id to insert oid/values in secondary table
507 507
                 $sql='SELECT LAST_INSERT_ID();';
508 508
                 if (($ret_code=$db_conn->query($sql)) === false) {
509
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
509
+                    $this->logging->log('Erreur recuperation id', ERROR, '');
510 510
                 }
511 511
                 
512 512
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
513
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
513
+                if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
514 514
                 $this->trapId=$inserted_id;
515 515
                 break;
516 516
             default:
517
-                $this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
517
+                $this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType, ERROR, '');
518 518
         }
519
-        $this->logging->log('id found: '.$this->trapId,INFO );
519
+        $this->logging->log('id found: '.$this->trapId, INFO);
520 520
         
521 521
         // Fill trap extended data table
522 522
         foreach ($this->trapDataExt as $value) {
523 523
             // TODO : detect if trap value is encoded and decode it to UTF-8 for database
524 524
             $firstcol=1;
525
-            $value->trap_id = $this->trapId;
525
+            $value->trap_id=$this->trapId;
526 526
             $insert_col='';
527 527
             $insert_val='';
528 528
             foreach ($value as $col => $val)
529 529
             {
530
-                if ($firstcol==0)
530
+                if ($firstcol == 0)
531 531
                 {
532
-                    $insert_col .=',';
533
-                    $insert_val .=',';
532
+                    $insert_col.=',';
533
+                    $insert_val.=',';
534 534
                 }
535
-                $insert_col .= $col;
536
-                $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
535
+                $insert_col.=$col;
536
+                $insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
537 537
                 $firstcol=0;
538 538
             }
539 539
             
540
-            $sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
540
+            $sql='INSERT INTO '.$this->dbPrefix.'received_data ('.$insert_col.') VALUES ('.$insert_val.');';
541 541
             
542 542
             if ($db_conn->query($sql) === false) {
543
-                $this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
543
+                $this->logging->log('Erreur insertion data : '.$sql, WARN, '');
544 544
             }
545 545
         }
546 546
     }
@@ -550,14 +550,14 @@  discard block
 block discarded – undo
550 550
      *	@param $oid string oid in numeric
551 551
      *	@return mixed|boolean : PDO object or false
552 552
      */
553
-    protected function getRules($ip,$oid)
553
+    protected function getRules($ip, $oid)
554 554
     {
555 555
         $db_conn=$this->trapsDB->db_connect_trap();
556 556
         // fetch rules based on IP in rule and OID
557 557
         $sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
558
-        $this->logging->log('SQL query : '.$sql,DEBUG );
558
+        $this->logging->log('SQL query : '.$sql, DEBUG);
559 559
         if (($ret_code=$db_conn->query($sql)) === false) {
560
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
560
+            $this->logging->log('No result in query : '.$sql, WARN, '');
561 561
             return false;
562 562
         }
563 563
         $rules_all=$ret_code->fetchAll();
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
         $rule_ret_key=0;
567 567
         foreach ($rules_all as $key => $rule)
568 568
         {
569
-            if ($rule['ip4']==$ip || $rule['ip6']==$ip)
569
+            if ($rule['ip4'] == $ip || $rule['ip6'] == $ip)
570 570
             {
571 571
                 $rules_ret[$rule_ret_key]=$rules_all[$key];
572 572
                 //TODO : get host name by API (and check if correct in rule).
@@ -574,7 +574,7 @@  discard block
 block discarded – undo
574 574
                 continue;
575 575
             }
576 576
 
577
-            if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
577
+            if (isset($rule['host_group_name']) && $rule['host_group_name'] != null)
578 578
             { // get ips of group members by oid
579 579
                 if ($this->apiUse === false)
580 580
                 {
@@ -587,21 +587,21 @@  discard block
 block discarded – undo
587 587
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
588 588
 						WHERE o.name1='".$rule['host_group_name']."';";
589 589
                     if (($ret_code2=$db_conn2->query($sql)) === false) {
590
-                        $this->logging->log('No result in query : ' . $sql,WARN,'');
590
+                        $this->logging->log('No result in query : '.$sql, WARN, '');
591 591
                         continue;
592 592
                     }
593 593
                     $grouphosts=$ret_code2->fetchAll();
594
-                }else{
595
-                    $api = $this->getAPI();
594
+                } else {
595
+                    $api=$this->getAPI();
596 596
                     $api->setCredentials($this->apiUsername, $this->apiPassword);
597 597
                     $grouphosts=$api->getHostsIPByHostGroup($rule['host_group_name']);
598 598
                 }
599 599
                 //echo "rule grp :\n";print_r($grouphosts);echo "\n";
600
-                foreach ( $grouphosts as $host)
600
+                foreach ($grouphosts as $host)
601 601
                 {
602
-                    if( is_object( $host ) ) $host=(array)$host;
602
+                    if (is_object($host)) $host=(array) $host;
603 603
                     //echo $host['address']."\n";
604
-                    if ($host['address']==$ip || $host['address6']==$ip)
604
+                    if ($host['address'] == $ip || $host['address6'] == $ip)
605 605
                     {
606 606
                         //echo "Rule added \n";
607 607
                         $rules_ret[$rule_ret_key]=$rules_all[$key];
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
         $db_conn=$this->trapsDB->db_connect_trap();
626 626
         $sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
627 627
         if ($db_conn->query($sql) === false) {
628
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
628
+            $this->logging->log('Error in update query : '.$sql, WARN, '');
629 629
         }
630 630
     }
631 631
     
@@ -637,23 +637,23 @@  discard block
 block discarded – undo
637 637
      * @param string $display
638 638
      * @returnn bool true is service check was sent without error
639 639
      */
640
-    public function serviceCheckResult($host,$service,$state,$display)
640
+    public function serviceCheckResult($host, $service, $state, $display)
641 641
     {
642 642
         if ($this->apiUse === false)
643 643
         {
644
-            $send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
645
-                $host.';' .$service .';' . $state . ';'.$display;
646
-                $this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
644
+            $send='['.date('U').'] PROCESS_SERVICE_CHECK_RESULT;'.
645
+                $host.';'.$service.';'.$state.';'.$display;
646
+                $this->logging->log($send." : to : ".$this->icinga2cmd, INFO);
647 647
                 
648 648
                 // TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
649
-                exec('echo "'.$send.'" > ' .$this->icinga2cmd);
649
+                exec('echo "'.$send.'" > '.$this->icinga2cmd);
650 650
                 return true;
651 651
         }
652 652
         else
653 653
         {
654 654
             // Get perfdata if found
655 655
             $matches=array();
656
-            if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
656
+            if (preg_match('/(.*)\|(.*)/', $display, $matches) == 1)
657 657
             {
658 658
                 $display=$matches[1];
659 659
                 $perfdata=$matches[2];
@@ -663,17 +663,17 @@  discard block
 block discarded – undo
663 663
                 $perfdata='';
664 664
             }
665 665
             
666
-            $api = $this->getAPI();
666
+            $api=$this->getAPI();
667 667
             $api->setCredentials($this->apiUsername, $this->apiPassword);
668
-            list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
668
+            list($retcode, $retmessage)=$api->serviceCheckResult($host, $service, $state, $display, $perfdata);
669 669
             if ($retcode == false)
670 670
             {
671
-                $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
671
+                $this->logging->log("Error sending result : ".$retmessage, WARN, '');
672 672
                 return false;
673 673
             }
674 674
             else
675 675
             {
676
-                $this->logging->log( "Sent result : " .$retmessage,INFO );
676
+                $this->logging->log("Sent result : ".$retmessage, INFO);
677 677
                 return true;
678 678
             }
679 679
         }
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
     
682 682
     public function getHostByIP($ip)
683 683
     {
684
-        $api = $this->getAPI();
684
+        $api=$this->getAPI();
685 685
         $api->setCredentials($this->apiUsername, $this->apiPassword);
686 686
         return $api->getHostByIP($ip);
687 687
     }
@@ -694,35 +694,35 @@  discard block
 block discarded – undo
694 694
     protected function applyDisplay($display)
695 695
     {
696 696
         $matches=array();
697
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$display,$matches) == 1)
697
+        while (preg_match('/_OID\(([0-9\.\*]+)\)/', $display, $matches) == 1)
698 698
         {
699 699
             $oid=$matches[1];
700 700
             $found=0;
701 701
             // Test and transform regexp
702
-            $oidR = $this->ruleClass->regexp_eval($oid);
702
+            $oidR=$this->ruleClass->regexp_eval($oid);
703 703
             
704
-            foreach($this->trapDataExt as $val)
704
+            foreach ($this->trapDataExt as $val)
705 705
             {
706
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
706
+                if (preg_match("/^$oidR$/", $val->oid) == 1)
707 707
                 {
708
-                    $val->value=preg_replace('/"/','',$val->value);
708
+                    $val->value=preg_replace('/"/', '', $val->value);
709 709
                     $rep=0;
710
-                    $display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
711
-                    if ($rep==0)
710
+                    $display=preg_replace('/_OID\('.$oid.'\)/', $val->value, $display, -1, $rep);
711
+                    if ($rep == 0)
712 712
                     {
713
-                        $this->logging->log("Error in display",WARN,'');
713
+                        $this->logging->log("Error in display", WARN, '');
714 714
                         return $display;
715 715
                     }
716 716
                     $found=1;
717 717
                     break;
718 718
                 }
719 719
             }
720
-            if ($found==0)
720
+            if ($found == 0)
721 721
             {
722
-                $display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
723
-                if ($rep==0)
722
+                $display=preg_replace('/_OID\('.$oid.'\)/', '<not in trap>', $display, -1, $rep);
723
+                if ($rep == 0)
724 724
                 {
725
-                    $this->logging->log("Error in display",WARN,'');
725
+                    $this->logging->log("Error in display", WARN, '');
726 726
                     return $display;
727 727
                 }
728 728
             }
@@ -734,11 +734,11 @@  discard block
 block discarded – undo
734 734
      */
735 735
     public function applyRules()
736 736
     {
737
-        $rules = $this->getRules($this->trapData['source_ip'],$this->trapData['trap_oid']);
737
+        $rules=$this->getRules($this->trapData['source_ip'], $this->trapData['trap_oid']);
738 738
         
739
-        if ($rules===false || count($rules)==0)
739
+        if ($rules === false || count($rules) == 0)
740 740
         {
741
-            $this->logging->log('No rules found for this trap',INFO );
741
+            $this->logging->log('No rules found for this trap', INFO);
742 742
             $this->trapData['status']='unknown';
743 743
             $this->trapToDb=true;
744 744
             return;
@@ -753,59 +753,59 @@  discard block
 block discarded – undo
753 753
             $service_name=$rule['service_name'];
754 754
             
755 755
             $display=$this->applyDisplay($rule['display']);
756
-            $this->trapAction = ($this->trapAction==null)? '' : $this->trapAction . ', ';
756
+            $this->trapAction=($this->trapAction == null) ? '' : $this->trapAction.', ';
757 757
             try
758 758
             {
759
-                $this->logging->log('Rule to eval : '.$rule['rule'],INFO );
760
-                $evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt) ;
759
+                $this->logging->log('Rule to eval : '.$rule['rule'], INFO);
760
+                $evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt);
761 761
                 //->eval_rule($rule['rule']);
762 762
                 
763 763
                 if ($evalr == true)
764 764
                 {
765 765
                     //$this->logging->log('rules OOK: '.print_r($rule),INFO );
766 766
                     $action=$rule['action_match'];
767
-                    $this->logging->log('action OK : '.$action,INFO );
767
+                    $this->logging->log('action OK : '.$action, INFO);
768 768
                     if ($action >= 0)
769 769
                     {
770
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
770
+                        if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
771 771
                         {
772 772
                             $this->trapAction.='Error sending status : check cmd/API';
773 773
                         }
774 774
                         else
775 775
                         {
776
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
776
+                            $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
777 777
                             $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
778 778
                         }
779 779
                     }
780 780
                     else
781 781
                     {
782
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
782
+                        $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
783 783
                     }
784
-                    $this->trapToDb=($action==-2)?false:true;
784
+                    $this->trapToDb=($action == -2) ?false:true;
785 785
                 }
786 786
                 else
787 787
                 {
788 788
                     //$this->logging->log('rules KOO : '.print_r($rule),INFO );
789 789
                     
790 790
                     $action=$rule['action_nomatch'];
791
-                    $this->logging->log('action NOK : '.$action,INFO );
791
+                    $this->logging->log('action NOK : '.$action, INFO);
792 792
                     if ($action >= 0)
793 793
                     {
794
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
794
+                        if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
795 795
                         {
796 796
                             $this->trapAction.='Error sending status : check cmd/API';
797 797
                         }
798 798
                         else
799 799
                         {
800
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
800
+                            $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
801 801
                             $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
802 802
                         }
803 803
                     }
804 804
                     else
805 805
                     {
806
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
806
+                        $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
807 807
                     }
808
-                    $this->trapToDb=($action==-2)?false:true;
808
+                    $this->trapToDb=($action == -2) ?false:true;
809 809
                 }
810 810
                 // Put name in source_name
811 811
                 if (!isset($this->trapData['source_name']))
@@ -814,7 +814,7 @@  discard block
 block discarded – undo
814 814
                 }
815 815
                 else
816 816
                 {
817
-                    if (!preg_match('/'.$rule['host_name'].'/',$this->trapData['source_name']))
817
+                    if (!preg_match('/'.$rule['host_name'].'/', $this->trapData['source_name']))
818 818
                     { // only add if not present
819 819
                         $this->trapData['source_name'].=','.$rule['host_name'];
820 820
                     }
@@ -822,13 +822,13 @@  discard block
 block discarded – undo
822 822
             }
823 823
             catch (Exception $e)
824 824
             {
825
-                $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
825
+                $this->logging->log('Error in rule eval : '.$e->getMessage(), WARN, '');
826 826
                 $this->trapAction.=' ERR : '.$e->getMessage();
827 827
                 $this->trapData['status']='error';
828 828
             }
829 829
             
830 830
         }
831
-        if ($this->trapData['status']=='error')
831
+        if ($this->trapData['status'] == 'error')
832 832
         {
833 833
             $this->trapToDb=true; // Always put errors in DB for the use can see
834 834
         }
@@ -844,13 +844,13 @@  discard block
 block discarded – undo
844 844
     public function add_rule_final($time)
845 845
     {
846 846
         $db_conn=$this->trapsDB->db_connect_trap();
847
-        if ($this->trapAction==null)
847
+        if ($this->trapAction == null)
848 848
         {
849 849
             $this->trapAction='No action';
850 850
         }
851 851
         $sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trapAction."'  WHERE (id = '".$this->trapId."');";
852 852
         if ($db_conn->query($sql) === false) {
853
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
853
+            $this->logging->log('Error in update query : '.$sql, WARN, '');
854 854
         }
855 855
     }
856 856
     
@@ -875,12 +875,12 @@  discard block
 block discarded – undo
875 875
                                 WHERE s.current_state != 0;";
876 876
             $db_conn=$this->trapsDB->db_connect_ido();
877 877
             if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
878
-                $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
878
+                $this->logging->log('No result in query : '.$sql_query, ERROR, '');
879 879
                 return 0;
880 880
             }
881 881
             $services=$services_db->fetchAll();
882
-        }else{
883
-            $api = $this->getAPI();
882
+        } else {
883
+            $api=$this->getAPI();
884 884
             $api->setCredentials($this->apiUsername, $this->apiPassword);
885 885
             $services=$api->getNOKservice();
886 886
         }
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
         $sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
890 890
         $db_conn2=$this->trapsDB->db_connect_trap();
891 891
         if (($rules_db=$db_conn2->query($sql_query)) === false) {
892
-            $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
892
+            $this->logging->log('No result in query : '.$sql_query, ERROR, '');
893 893
             return 0;
894 894
         }
895 895
         $rules=$rules_db->fetchAll();
@@ -899,20 +899,20 @@  discard block
 block discarded – undo
899 899
         $numreset=0;
900 900
         foreach ($rules as $rule)
901 901
         {
902
-            if( is_object( $services ) ) $services=(array)$services;
902
+            if (is_object($services)) $services=(array) $services;
903 903
             foreach ($services as $service)
904 904
             {
905 905
                 if ($service['name'] == $rule['service_name'] &&
906 906
                     $service['host_name'] == $rule['host_name'] &&
907 907
                     ($service['last_check'] + $rule['revert_ok']) < $now)
908 908
                 {
909
-                    $this->serviceCheckResult($service['host_name'],$service['name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
909
+                    $this->serviceCheckResult($service['host_name'], $service['name'], 0, 'Reset service to OK after '.$rule['revert_ok'].' seconds');
910 910
                     $numreset++;
911 911
                 }
912 912
             }
913 913
         }
914 914
         echo "\n";
915
-        echo $numreset . " service(s) reset to OK\n";
915
+        echo $numreset." service(s) reset to OK\n";
916 916
         return 0;
917 917
         
918 918
     }
Please login to merge, or discard this patch.