Passed
Push — master ( 300cc7...278791 )
by Patrick
01:59
created
bin/trap_class.php 1 patch
Spacing   +190 added lines, -190 removed lines patch added patch discarded remove patch
@@ -36,8 +36,8 @@  discard block
 block discarded – undo
36 36
 	protected $api_password='';
37 37
 
38 38
 	// Logs 
39
-	protected $logging;    //< Logging class.
40
-	protected $logSetup;   //< bool true if log was setup in constructor
39
+	protected $logging; //< Logging class.
40
+	protected $logSetup; //< bool true if log was setup in constructor
41 41
 	
42 42
 	// Databases
43 43
 	public $trapsDB; //< Database class
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 	// Rule evaluation 
57 57
 	public $ruleClass; // Rule class
58 58
 	
59
-	function __construct($etc_dir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
59
+	function __construct($etc_dir='/etc/icingaweb2', $baseLogLevel=null, $baseLogMode='syslog', $baseLogFile='')
60 60
 	{
61 61
 	    // Paths of ini files
62 62
 		$this->icingaweb2_etc=$etc_dir;
@@ -64,10 +64,10 @@  discard block
 block discarded – undo
64 64
 		$this->icingaweb2_ressources=$this->icingaweb2_etc."/resources.ini";
65 65
 
66 66
 		// Setup logging
67
-		$this->logging = new Logging();
67
+		$this->logging=new Logging();
68 68
 		if ($baseLogLevel != null)
69 69
 		{
70
-		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
70
+		    $this->logging->setLogging($baseLogLevel, $baseLogMode, $baseLogFile);
71 71
 		    $this->logSetup=true;
72 72
 		}
73 73
 		else
@@ -75,10 +75,10 @@  discard block
 block discarded – undo
75 75
 		$this->logging->log('Loggin started', INFO);
76 76
 
77 77
 		// Get options from ini files
78
-		$trapConfig=parse_ini_file($this->trap_module_config,true);
78
+		$trapConfig=parse_ini_file($this->trap_module_config, true);
79 79
 		if ($trapConfig == false)
80 80
 		{
81
-		    $this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
81
+		    $this->logging->log("Error reading ini file : ".$this->trap_module_config, ERROR, 'syslog');
82 82
 		}
83 83
 		$this->getMainOptions($trapConfig); // Get main options from ini file
84 84
 		$this->setupDatabase($trapConfig); // Setup database class
@@ -86,9 +86,9 @@  discard block
 block discarded – undo
86 86
 		$this->getDatabaseOptions(); // Get options in database
87 87
 		if ($this->api_use === true) $this->getAPI(); // Setup API
88 88
 		
89
-		$this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
89
+		$this->mibClass=new Mib($this->logging, $this->trapsDB, $this->snmptranslate, $this->snmptranslate_dirs); // Create Mib class
90 90
 		
91
-		$this->ruleClass = new Rule($this->logging); //< Create Rule class
91
+		$this->ruleClass=new Rule($this->logging); //< Create Rule class
92 92
 		
93 93
 		$this->trap_data=array(
94 94
 			'source_ip'	=> 'unknown',
@@ -110,15 +110,15 @@  discard block
 block discarded – undo
110 110
 	 * @param string $message warning message if not found
111 111
 	 * @return boolean true if found, or false
112 112
 	 */
113
-	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
113
+	protected function getOptionIfSet($option_array, $option_category, $option_name, &$option_var, $log_level=2, $message=null)
114 114
 	{
115 115
 	    if (!isset($option_array[$option_category][$option_name]))
116 116
 	    {
117 117
 	        if ($message === null)
118 118
 	        {
119
-	            $message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
119
+	            $message='No '.$option_name.' in config file: '.$this->trap_module_config;
120 120
 	        }
121
-	        $this->logging->log($message,$log_level,'syslog');
121
+	        $this->logging->log($message, $log_level, 'syslog');
122 122
 	        return false;
123 123
 	    }
124 124
 	    else
@@ -136,24 +136,24 @@  discard block
 block discarded – undo
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->db_prefix);
148
+		$this->getOptionIfSet($trapConfig, 'config', 'database_prefix', $this->db_prefix);
149 149
 
150 150
 		// API options
151
-		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->api_hostname))
151
+		if ($this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_host', $this->api_hostname))
152 152
 		{
153 153
 		    $this->api_use=true;
154
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->api_port);
155
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->api_username);
156
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->api_password);
154
+		    $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_port', $this->api_port);
155
+		    $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_user', $this->api_username);
156
+		    $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_password', $this->api_password);
157 157
 		}
158 158
 	}
159 159
 	
@@ -164,40 +164,40 @@  discard block
 block discarded – undo
164 164
 	protected function setupDatabase($trapConfig)
165 165
 	{
166 166
 	    // Trap database
167
-	    if (!array_key_exists('database',$trapConfig['config']))
167
+	    if (!array_key_exists('database', $trapConfig['config']))
168 168
         {
169
-            $this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
169
+            $this->logging->log("No database in config file: ".$this->trap_module_config, ERROR, '');
170 170
             return;
171 171
         }
172 172
         $dbTrapName=$trapConfig['config']['database'];
173
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
173
+        $this->logging->log("Found database in config file: ".$dbTrapName, INFO);
174 174
 	    
175
-	   if ( ($dbConfig=parse_ini_file($this->icingaweb2_ressources,true)) === false)
175
+	   if (($dbConfig=parse_ini_file($this->icingaweb2_ressources, true)) === false)
176 176
 	    {
177
-	        $this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
177
+	        $this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources, ERROR, '');
178 178
 	        return;
179 179
 	    }
180
-	    if (!array_key_exists($dbTrapName,$dbConfig))
180
+	    if (!array_key_exists($dbTrapName, $dbConfig))
181 181
 	    {
182
-	        $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
182
+	        $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources, ERROR, '');
183 183
 	        return;
184 184
 	    }
185 185
 	    
186
-	    $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->db_prefix);
186
+	    $this->trapsDB=new Database($this->logging, $dbConfig[$dbTrapName], $this->db_prefix);
187 187
 	    
188 188
 	    if ($this->api_use === true) return; // In case of API use, no IDO is necessary
189 189
         
190 190
 	    // IDO Database
191
-	    if (!array_key_exists('IDOdatabase',$trapConfig['config']))
191
+	    if (!array_key_exists('IDOdatabase', $trapConfig['config']))
192 192
 	    {
193
-	        $this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
193
+	        $this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config, ERROR, '');
194 194
 	    }
195 195
 	    $dbIdoName=$trapConfig['config']['IDOdatabase'];		
196 196
 
197
-	    $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
198
-        if (!array_key_exists($dbIdoName,$dbConfig))
197
+	    $this->logging->log("Found IDO database in config file: ".$dbIdoName, INFO);
198
+        if (!array_key_exists($dbIdoName, $dbConfig))
199 199
 	    {
200
-	        $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
200
+	        $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources, ERROR, '');
201 201
 	        return;
202 202
 	    }
203 203
 	    
@@ -212,13 +212,13 @@  discard block
 block discarded – undo
212 212
 		// Database options
213 213
 		if ($this->logSetup === false) // Only if logging was no setup in constructor
214 214
 		{
215
-    		$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
216
-    		$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
217
-    		$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
215
+    		$this->getDBConfigIfSet('log_level', $this->logging->debugLevel);
216
+    		$this->getDBConfigIfSet('log_destination', $this->logging->outputMode);
217
+    		$this->getDBConfigIfSet('log_file', $this->logging->outputFile);
218 218
 		}
219 219
 	}
220 220
 
221
-	protected function getDBConfigIfSet($element,&$variable)
221
+	protected function getDBConfigIfSet($element, &$variable)
222 222
 	{
223 223
 		$value=$this->getDBConfig($element);
224 224
 		if ($value != 'null') $variable=$value;
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
 		$db_conn=$this->trapsDB->db_connect_trap();
235 235
 		$sql='SELECT value from '.$this->db_prefix.'db_config WHERE ( name=\''.$element.'\' )';
236 236
 		if (($ret_code=$db_conn->query($sql)) === false) {
237
-			$this->logging->log('No result in query : ' . $sql,WARN,'');
237
+			$this->logging->log('No result in query : '.$sql, WARN, '');
238 238
 			return null;
239 239
 		}
240 240
 		$value=$ret_code->fetch();
@@ -251,22 +251,22 @@  discard block
 block discarded – undo
251 251
 	*	@param  string $destination file/syslog/display
252 252
 	*	@return void
253 253
 	**/	
254
-	public function trapLog( $message, $level, $destination ='') // OBSOLETE
254
+	public function trapLog($message, $level, $destination='') // OBSOLETE
255 255
 	{	
256 256
 		// TODO : replace ref with $this->logging->log 
257 257
 	    $this->logging->log($message, $level, $destination);
258 258
 	}
259 259
 	
260
-	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
260
+	public function setLogging($debugLvl, $outputType, $outputOption=null)  // OBSOLETE
261 261
 	{
262
-		$this->logging->setLogging($debugLvl, $outputType,$outputOption);
262
+		$this->logging->setLogging($debugLvl, $outputType, $outputOption);
263 263
 	}
264 264
 	
265 265
 	protected function getAPI()
266 266
 	{
267 267
 	    if ($this->icinga2api == null)
268 268
 	    {
269
-	        $this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
269
+	        $this->icinga2api=new Icinga2API($this->api_hostname, $this->api_port);
270 270
 	    }
271 271
 	    return $this->icinga2api;
272 272
 	}
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 		if ($input_stream === false)
286 286
 		{
287 287
 		    $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
288
-			$this->logging->log("Error reading stdin !",ERROR,'');
288
+			$this->logging->log("Error reading stdin !", ERROR, '');
289 289
 			return null; // note : exception thrown by logging
290 290
 		}
291 291
 
@@ -294,21 +294,21 @@  discard block
 block discarded – undo
294 294
 		if ($this->receivingHost === false)
295 295
 		{
296 296
 		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
297
-			$this->logging->log("Error reading Host !",ERROR,''); 
297
+			$this->logging->log("Error reading Host !", ERROR, ''); 
298 298
 		}
299 299
 		// line 2 IP:port=>IP:port
300 300
 		$IP=chop(fgets($input_stream));
301 301
 		if ($IP === false)
302 302
 		{
303 303
 		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
304
-			$this->logging->log("Error reading IP !",ERROR,''); 
304
+			$this->logging->log("Error reading IP !", ERROR, ''); 
305 305
 		}
306 306
 		$matches=array();
307
-		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
308
-		if ($ret_code===0 || $ret_code===false) 
307
+		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/', $IP, $matches);
308
+		if ($ret_code === 0 || $ret_code === false) 
309 309
 		{
310 310
 		    $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
311
-			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
311
+			$this->logging->log('Error parsing IP : '.$IP, ERROR, '');
312 312
 		} 
313 313
 		else 
314 314
 		{		
@@ -318,34 +318,34 @@  discard block
 block discarded – undo
318 318
 			$this->trap_data['destination_port']=$matches[4];
319 319
 		}
320 320
 
321
-		while (($vars=fgets($input_stream)) !==false)
321
+		while (($vars=fgets($input_stream)) !== false)
322 322
 		{
323 323
 			$vars=chop($vars);
324
-			$ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
325
-			if ($ret_code===0 || $ret_code===false) 
324
+			$ret_code=preg_match('/^([^ ]+) (.*)$/', $vars, $matches);
325
+			if ($ret_code === 0 || $ret_code === false) 
326 326
 			{
327
-				$this->logging->log('No match on trap data : '.$vars,WARN,'');
327
+				$this->logging->log('No match on trap data : '.$vars, WARN, '');
328 328
 			}
329 329
 			else 
330 330
 			{
331
-			    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'))
331
+			    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'))
332 332
 				{
333 333
 					$this->trap_data['trap_oid']=$matches[2];				
334 334
 				}
335 335
 				else
336 336
 				{
337
-					$object= new stdClass;
338
-					$object->oid =$matches[1];
339
-					$object->value = $matches[2];
340
-					array_push($this->trap_data_ext,$object);
337
+					$object=new stdClass;
338
+					$object->oid=$matches[1];
339
+					$object->value=$matches[2];
340
+					array_push($this->trap_data_ext, $object);
341 341
 				}
342 342
 			}
343 343
 		}
344 344
 
345
-		if ($this->trap_data['trap_oid']=='unknown') 
345
+		if ($this->trap_data['trap_oid'] == 'unknown') 
346 346
 		{
347
-		    $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
348
-			$this->logging->log('no trap oid found',ERROR,'');
347
+		    $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)", $this->trap_data['source_ip']);
348
+			$this->logging->log('no trap oid found', ERROR, '');
349 349
 		} 
350 350
 
351 351
 		// Translate oids.
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 		}
368 368
 		
369 369
 
370
-		$this->trap_data['status']= 'waiting';
370
+		$this->trap_data['status']='waiting';
371 371
 		
372 372
 		return $this->trap_data;
373 373
 	}
@@ -383,40 +383,40 @@  discard block
 block discarded – undo
383 383
 		$db_conn=$this->trapsDB->db_connect_trap();
384 384
 		
385 385
 		$sql='SELECT mib,name from '.$this->db_prefix.'mib_cache WHERE oid=\''.$oid.'\';';
386
-		$this->logging->log('SQL query : '.$sql,DEBUG );
386
+		$this->logging->log('SQL query : '.$sql, DEBUG);
387 387
 		if (($ret_code=$db_conn->query($sql)) === false) {
388
-			$this->logging->log('No result in query : ' . $sql,ERROR,'');
388
+			$this->logging->log('No result in query : '.$sql, ERROR, '');
389 389
 		}
390 390
 		$name=$ret_code->fetch();
391 391
 		if ($name['name'] != null)
392 392
 		{
393
-			return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
393
+			return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
394 394
 		}
395 395
 		
396 396
 		// Also check if it is an instance of OID
397
-		$oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
397
+		$oid_instance=preg_replace('/\.[0-9]+$/', '', $oid);
398 398
 		
399 399
 		$sql='SELECT mib,name from '.$this->db_prefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
400
-		$this->logging->log('SQL query : '.$sql,DEBUG );
400
+		$this->logging->log('SQL query : '.$sql, DEBUG);
401 401
 		if (($ret_code=$db_conn->query($sql)) === false) {
402
-			$this->logging->log('No result in query : ' . $sql,ERROR,'');
402
+			$this->logging->log('No result in query : '.$sql, ERROR, '');
403 403
 		}
404 404
 		$name=$ret_code->fetch();
405 405
 		if ($name['name'] != null)
406 406
 		{
407
-			return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
407
+			return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
408 408
 		}
409 409
 		
410 410
 		// Try to get oid name from snmptranslate
411
-		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
411
+		$translate=exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
412 412
 		    ' '.$oid);
413 413
 		$matches=array();
414
-		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
415
-		if ($ret_code===0 || $ret_code === false) {
414
+		$ret_code=preg_match('/(.*)::(.*)/', $translate, $matches);
415
+		if ($ret_code === 0 || $ret_code === false) {
416 416
 			return NULL;
417 417
 		} else {
418
-			$this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
419
-			return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
418
+			$this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid, INFO);
419
+			return array('trap_name_mib'=>$matches[1], 'trap_name'=>$matches[2]);
420 420
 		}	
421 421
 	}
422 422
 	
@@ -427,90 +427,90 @@  discard block
 block discarded – undo
427 427
 	**/
428 428
 	public function eraseOldTraps($days=0)
429 429
 	{
430
-		if ($days==0)
430
+		if ($days == 0)
431 431
 		{
432 432
 			if (($days=$this->getDBConfig('db_remove_days')) == null)
433 433
 			{
434
-				$this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
434
+				$this->logging->log('No days specified & no db value : no tap erase', WARN, '');
435 435
 				return;
436 436
 			}
437 437
 		}
438 438
 		$db_conn=$this->trapsDB->db_connect_trap();
439
-		$daysago = strtotime("-".$days." day");
440
-		$sql= 'delete from '.$this->db_prefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
439
+		$daysago=strtotime("-".$days." day");
440
+		$sql='delete from '.$this->db_prefix.'received where date_received < \''.date("Y-m-d H:i:s", $daysago).'\';';
441 441
 		if ($db_conn->query($sql) === false) {
442
-			$this->logging->log('Error erasing traps : '.$sql,ERROR,'');
442
+			$this->logging->log('Error erasing traps : '.$sql, ERROR, '');
443 443
 		}
444
-		$this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
444
+		$this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql, INFO);
445 445
 	}
446 446
 
447 447
 	/** Write error to received trap database
448 448
 	 */
449
-	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
449
+	public function writeTrapErrorToDB($message, $sourceIP=null, $trapoid=null)
450 450
 	{
451 451
 	    
452 452
 	    $db_conn=$this->trapsDB->db_connect_trap();
453 453
 	    
454 454
 	    // add date time
455
-	    $insert_col ='date_received,status';
456
-	    $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
455
+	    $insert_col='date_received,status';
456
+	    $insert_val="'".date("Y-m-d H:i:s")."','error'";
457 457
         
458
-	    if ($sourceIP !=null)
458
+	    if ($sourceIP != null)
459 459
 	    {
460
-	        $insert_col .=',source_ip';
461
-	        $insert_val .=",'". $sourceIP ."'";
460
+	        $insert_col.=',source_ip';
461
+	        $insert_val.=",'".$sourceIP."'";
462 462
 	    }
463
-	    if ($trapoid !=null)
463
+	    if ($trapoid != null)
464 464
 	    {
465
-	        $insert_col .=',trap_oid';
466
-	        $insert_val .=",'". $trapoid ."'";
465
+	        $insert_col.=',trap_oid';
466
+	        $insert_val.=",'".$trapoid."'";
467 467
 	    }
468
-	    $insert_col .=',status_detail';
469
-	    $insert_val .=",'". $message ."'";
468
+	    $insert_col.=',status_detail';
469
+	    $insert_val.=",'".$message."'";
470 470
 	    
471
-	    $sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
471
+	    $sql='INSERT INTO '.$this->db_prefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
472 472
 	    
473 473
 	    switch ($this->trapsDB->trapDBType)
474 474
 	    {
475 475
 	        case 'pgsql':
476
-	            $sql .= ' RETURNING id;';
477
-	            $this->logging->log('sql : '.$sql,INFO);
476
+	            $sql.=' RETURNING id;';
477
+	            $this->logging->log('sql : '.$sql, INFO);
478 478
 	            if (($ret_code=$db_conn->query($sql)) === false) {
479
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
479
+	                $this->logging->log('Error SQL insert : '.$sql, 1, '');
480 480
 	            }
481
-	            $this->logging->log('SQL insertion OK',INFO );
481
+	            $this->logging->log('SQL insertion OK', INFO);
482 482
 	            // Get last id to insert oid/values in secondary table
483 483
 	            if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
484 484
 	                
485
-	                $this->logging->log('Erreur recuperation id',1,'');
485
+	                $this->logging->log('Erreur recuperation id', 1, '');
486 486
 	            }
487
-	            if (! isset($inserted_id_ret['id'])) {
488
-	                $this->logging->log('Error getting id',1,'');
487
+	            if (!isset($inserted_id_ret['id'])) {
488
+	                $this->logging->log('Error getting id', 1, '');
489 489
 	            }
490 490
 	            $this->trap_id=$inserted_id_ret['id'];
491 491
 	            break;
492 492
 	        case 'mysql':
493
-	            $sql .= ';';
494
-	            $this->logging->log('sql : '.$sql,INFO );
493
+	            $sql.=';';
494
+	            $this->logging->log('sql : '.$sql, INFO);
495 495
 	            if ($db_conn->query($sql) === false) {
496
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
496
+	                $this->logging->log('Error SQL insert : '.$sql, 1, '');
497 497
 	            }
498
-	            $this->logging->log('SQL insertion OK',INFO );
498
+	            $this->logging->log('SQL insertion OK', INFO);
499 499
 	            // Get last id to insert oid/values in secondary table
500 500
 	            $sql='SELECT LAST_INSERT_ID();';
501 501
 	            if (($ret_code=$db_conn->query($sql)) === false) {
502
-	                $this->logging->log('Erreur recuperation id',1,'');
502
+	                $this->logging->log('Erreur recuperation id', 1, '');
503 503
 	            }
504 504
 	            
505 505
 	            $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
506
-	            if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
506
+	            if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
507 507
 	            $this->trap_id=$inserted_id;
508 508
 	            break;
509 509
 	        default:
510
-	            $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
510
+	            $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType, 1, '');
511 511
 	    }
512 512
 	    
513
-	    $this->logging->log('id found: '. $this->trap_id,INFO );    
513
+	    $this->logging->log('id found: '.$this->trap_id, INFO);    
514 514
 	}
515 515
 	
516 516
 	/** Write trap data to trap database
@@ -527,86 +527,86 @@  discard block
 block discarded – undo
527 527
 		$insert_col='';
528 528
 		$insert_val='';
529 529
 		// add date time
530
-		$this->trap_data['date_received'] = date("Y-m-d H:i:s");
530
+		$this->trap_data['date_received']=date("Y-m-d H:i:s");
531 531
 
532 532
 		$firstcol=1;
533 533
 		foreach ($this->trap_data as $col => $val)
534 534
 		{
535
-			if ($firstcol==0) 
535
+			if ($firstcol == 0) 
536 536
 			{
537
-				$insert_col .=',';
538
-				$insert_val .=',';
537
+				$insert_col.=',';
538
+				$insert_val.=',';
539 539
 			}
540
-			$insert_col .= $col ;
541
-			$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
540
+			$insert_col.=$col;
541
+			$insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
542 542
 			$firstcol=0;
543 543
 		}
544 544
 		
545
-		$sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
545
+		$sql='INSERT INTO '.$this->db_prefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
546 546
 		switch ($this->trapsDB->trapDBType)
547 547
 		{
548 548
 			case 'pgsql': 
549
-				$sql .= ' RETURNING id;';
550
-				$this->logging->log('sql : '.$sql,INFO );
549
+				$sql.=' RETURNING id;';
550
+				$this->logging->log('sql : '.$sql, INFO);
551 551
 				if (($ret_code=$db_conn->query($sql)) === false) {
552
-					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
552
+					$this->logging->log('Error SQL insert : '.$sql, ERROR, '');
553 553
 				}
554
-				$this->logging->log('SQL insertion OK',INFO );
554
+				$this->logging->log('SQL insertion OK', INFO);
555 555
 				// Get last id to insert oid/values in secondary table
556 556
 				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
557 557
 														   
558
-					$this->logging->log('Erreur recuperation id',ERROR,'');
558
+					$this->logging->log('Erreur recuperation id', ERROR, '');
559 559
 				}
560
-				if (! isset($inserted_id_ret['id'])) {
561
-					$this->logging->log('Error getting id',ERROR,'');
560
+				if (!isset($inserted_id_ret['id'])) {
561
+					$this->logging->log('Error getting id', ERROR, '');
562 562
 				}
563 563
 				$this->trap_id=$inserted_id_ret['id'];
564 564
 			break;
565 565
 			case 'mysql': 
566
-				$sql .= ';';
567
-				$this->logging->log('sql : '.$sql,INFO );
566
+				$sql.=';';
567
+				$this->logging->log('sql : '.$sql, INFO);
568 568
 				if ($db_conn->query($sql) === false) {
569
-					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
569
+					$this->logging->log('Error SQL insert : '.$sql, ERROR, '');
570 570
 				}
571
-				$this->logging->log('SQL insertion OK',INFO );
571
+				$this->logging->log('SQL insertion OK', INFO);
572 572
 				// Get last id to insert oid/values in secondary table
573 573
 				$sql='SELECT LAST_INSERT_ID();';
574 574
 				if (($ret_code=$db_conn->query($sql)) === false) {
575
-					$this->logging->log('Erreur recuperation id',ERROR,'');
575
+					$this->logging->log('Erreur recuperation id', ERROR, '');
576 576
 				}
577 577
 
578 578
 				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
579
-				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
579
+				if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
580 580
 				$this->trap_id=$inserted_id;
581 581
 			break;
582 582
 			default: 
583
-				$this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
583
+				$this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType, ERROR, '');
584 584
 		}
585
-		$this->logging->log('id found: '.$this->trap_id,INFO );
585
+		$this->logging->log('id found: '.$this->trap_id, INFO);
586 586
 		
587 587
 		// Fill trap extended data table
588 588
 		foreach ($this->trap_data_ext as $value) {			
589 589
 			// TODO : detect if trap value is encoded and decode it to UTF-8 for database
590 590
 			$firstcol=1;
591
-			$value->trap_id = $this->trap_id;
591
+			$value->trap_id=$this->trap_id;
592 592
 			$insert_col='';
593 593
 			$insert_val='';
594 594
 			foreach ($value as $col => $val)
595 595
 			{
596
-				if ($firstcol==0) 
596
+				if ($firstcol == 0) 
597 597
 				{
598
-					$insert_col .=',';
599
-					$insert_val .=',';
598
+					$insert_col.=',';
599
+					$insert_val.=',';
600 600
 				}
601
-				$insert_col .= $col;
602
-				$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
601
+				$insert_col.=$col;
602
+				$insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
603 603
 				$firstcol=0;
604 604
 			}
605 605
 
606
-			$sql= 'INSERT INTO '.$this->db_prefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';			
606
+			$sql='INSERT INTO '.$this->db_prefix.'received_data ('.$insert_col.') VALUES ('.$insert_val.');';			
607 607
 
608 608
 			if ($db_conn->query($sql) === false) {
609
-				$this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
609
+				$this->logging->log('Erreur insertion data : '.$sql, WARN, '');
610 610
 			}	
611 611
 		}	
612 612
 	}
@@ -616,14 +616,14 @@  discard block
 block discarded – undo
616 616
 	*	@param $oid string oid in numeric
617 617
 	*	@return mixed : PDO object or false
618 618
 	*/	
619
-	protected function getRules($ip,$oid)
619
+	protected function getRules($ip, $oid)
620 620
 	{
621 621
 		$db_conn=$this->trapsDB->db_connect_trap();
622 622
 		// fetch rules based on IP in rule and OID
623 623
 		$sql='SELECT * from '.$this->db_prefix.'rules WHERE trap_oid=\''.$oid.'\' ';
624
-		$this->logging->log('SQL query : '.$sql,DEBUG );
624
+		$this->logging->log('SQL query : '.$sql, DEBUG);
625 625
 		if (($ret_code=$db_conn->query($sql)) === false) {
626
-			$this->logging->log('No result in query : ' . $sql,WARN,'');
626
+			$this->logging->log('No result in query : '.$sql, WARN, '');
627 627
 			return false;
628 628
 		}
629 629
 		$rules_all=$ret_code->fetchAll();
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
 		$rule_ret_key=0;
633 633
 		foreach ($rules_all as $key => $rule)
634 634
 		{
635
-			if ($rule['ip4']==$ip || $rule['ip6']==$ip)
635
+			if ($rule['ip4'] == $ip || $rule['ip6'] == $ip)
636 636
 			{
637 637
 				$rules_ret[$rule_ret_key]=$rules_all[$key];
638 638
 				//TODO : get host name by API (and check if correct in rule).
@@ -640,7 +640,7 @@  discard block
 block discarded – undo
640 640
 				continue;
641 641
 			}
642 642
 			// TODO : get hosts IP by API
643
-			if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
643
+			if (isset($rule['host_group_name']) && $rule['host_group_name'] != null)
644 644
 			{ // get ips of group members by oid
645 645
 				$db_conn2=$this->trapsDB->db_connect_ido();
646 646
 				$sql="SELECT m.host_object_id, a.address as ip4, a.address6 as ip6, b.name1 as host_name
@@ -651,15 +651,15 @@  discard block
 block discarded – undo
651 651
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
652 652
 						WHERE o.name1='".$rule['host_group_name']."';";
653 653
 				if (($ret_code2=$db_conn2->query($sql)) === false) {
654
-					$this->logging->log('No result in query : ' . $sql,WARN,'');
654
+					$this->logging->log('No result in query : '.$sql, WARN, '');
655 655
 					continue;
656 656
 				}
657 657
 				$grouphosts=$ret_code2->fetchAll();
658 658
 				//echo "rule grp :\n";print_r($grouphosts);echo "\n";
659
-				foreach ( $grouphosts as $host)
659
+				foreach ($grouphosts as $host)
660 660
 				{
661 661
 					//echo $host['ip4']."\n";
662
-					if ($host['ip4']==$ip || $host['ip6']==$ip)
662
+					if ($host['ip4'] == $ip || $host['ip6'] == $ip)
663 663
 					{
664 664
 						//echo "Rule added \n";
665 665
 						$rules_ret[$rule_ret_key]=$rules_all[$key];
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
 		$db_conn=$this->trapsDB->db_connect_trap();
683 683
 		$sql="UPDATE ".$this->db_prefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
684 684
 		if ($db_conn->query($sql) === false) {
685
-			$this->logging->log('Error in update query : ' . $sql,WARN,'');
685
+			$this->logging->log('Error in update query : '.$sql, WARN, '');
686 686
 		}
687 687
 	}
688 688
 	
@@ -694,31 +694,31 @@  discard block
 block discarded – undo
694 694
 	 * @param string $display
695 695
 	 * @returnn bool true is service check was sent without error
696 696
 	*/
697
-	public function serviceCheckResult($host,$service,$state,$display)
697
+	public function serviceCheckResult($host, $service, $state, $display)
698 698
 	{
699 699
 	    if ($this->api_use === false)
700 700
 	    {
701
-    		$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
702
-    			$host.';' .$service .';' . $state . ';'.$display;
703
-    		$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
701
+    		$send='['.date('U').'] PROCESS_SERVICE_CHECK_RESULT;'.
702
+    			$host.';'.$service.';'.$state.';'.$display;
703
+    		$this->logging->log($send." : to : ".$this->icinga2cmd, INFO);
704 704
     		
705 705
     		// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
706
-    		exec('echo "'.$send.'" > ' .$this->icinga2cmd);
706
+    		exec('echo "'.$send.'" > '.$this->icinga2cmd);
707 707
     		return true;
708 708
 	    }
709 709
 	    else
710 710
 	    {
711
-	        $api = $this->getAPI();
711
+	        $api=$this->getAPI();
712 712
 	        $api->setCredentials($this->api_username, $this->api_password);
713
-	        list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display);
713
+	        list($retcode, $retmessage)=$api->serviceCheckResult($host, $service, $state, $display);
714 714
 	        if ($retcode == false)
715 715
 	        {
716
-	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
716
+	            $this->logging->log("Error sending result : ".$retmessage, WARN, '');
717 717
 	            return false;
718 718
 	        }
719 719
 	        else 
720 720
 	        {
721
-	            $this->logging->log( "Sent result : " .$retmessage,INFO );
721
+	            $this->logging->log("Sent result : ".$retmessage, INFO);
722 722
 	            return true;
723 723
 	        }
724 724
 	    }
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
 	
727 727
 	public function getHostByIP($ip)
728 728
 	{
729
-	    $api = $this->getAPI();
729
+	    $api=$this->getAPI();
730 730
 	    $api->setCredentials($this->api_username, $this->api_password);
731 731
 	    return $api->getHostByIP($ip);
732 732
 	}
@@ -739,32 +739,32 @@  discard block
 block discarded – undo
739 739
 	protected function applyDisplay($display)
740 740
 	{
741 741
 	    $matches=array();
742
-	    while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
742
+	    while (preg_match('/_OID\(([0-9\.]+)\)/', $display, $matches) == 1)
743 743
 		{
744 744
 			$oid=$matches[1];
745 745
 			$found=0;
746
-			foreach($this->trap_data_ext as $val)
746
+			foreach ($this->trap_data_ext as $val)
747 747
 			{
748 748
 				if ($oid == $val->oid)
749 749
 				{
750
-					$val->value=preg_replace('/"/','',$val->value);
750
+					$val->value=preg_replace('/"/', '', $val->value);
751 751
 					$rep=0;
752
-					$display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
753
-					if ($rep==0)
752
+					$display=preg_replace('/_OID\('.$oid.'\)/', $val->value, $display, -1, $rep);
753
+					if ($rep == 0)
754 754
 					{
755
-						$this->logging->log("Error in display",WARN,'');
755
+						$this->logging->log("Error in display", WARN, '');
756 756
 						return $display;
757 757
 					}
758 758
 					$found=1;
759 759
 					break;
760 760
 				}
761 761
 			}
762
-			if ($found==0)
762
+			if ($found == 0)
763 763
 			{
764
-				$display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
765
-				if ($rep==0)
764
+				$display=preg_replace('/_OID\('.$oid.'\)/', '<not in trap>', $display, -1, $rep);
765
+				if ($rep == 0)
766 766
 				{
767
-					$this->logging->log("Error in display",WARN,'');
767
+					$this->logging->log("Error in display", WARN, '');
768 768
 					return $display;
769 769
 				}				
770 770
 			}
@@ -776,11 +776,11 @@  discard block
 block discarded – undo
776 776
 	*/
777 777
 	public function applyRules()
778 778
 	{
779
-		$rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
779
+		$rules=$this->getRules($this->trap_data['source_ip'], $this->trap_data['trap_oid']);
780 780
 		
781
-		if ($rules===false || count($rules)==0)
781
+		if ($rules === false || count($rules) == 0)
782 782
 		{
783
-			$this->logging->log('No rules found for this trap',INFO );
783
+			$this->logging->log('No rules found for this trap', INFO);
784 784
 			$this->trap_data['status']='unknown';
785 785
 			$this->trap_to_db=true;
786 786
 			return;
@@ -795,59 +795,59 @@  discard block
 block discarded – undo
795 795
 			$service_name=$rule['service_name'];
796 796
 			
797 797
 			$display=$this->applyDisplay($rule['display']);
798
-			$this->trap_action = ($this->trap_action==null)? '' : $this->trap_action . ', ';
798
+			$this->trap_action=($this->trap_action == null) ? '' : $this->trap_action.', ';
799 799
 			try
800 800
 			{
801
-				$this->logging->log('Rule to eval : '.$rule['rule'],INFO );
802
-				$evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trap_data_ext) ;
801
+				$this->logging->log('Rule to eval : '.$rule['rule'], INFO);
802
+				$evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trap_data_ext);
803 803
 				//->eval_rule($rule['rule']);
804 804
 				
805 805
 				if ($evalr == true)
806 806
 				{
807 807
 					//$this->logging->log('rules OOK: '.print_r($rule),INFO );
808 808
 					$action=$rule['action_match'];
809
-					$this->logging->log('action OK : '.$action,INFO );
809
+					$this->logging->log('action OK : '.$action, INFO);
810 810
 					if ($action >= 0)
811 811
 					{
812
-						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
812
+						if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
813 813
 						{
814 814
 						    $this->trap_action.='Error sending status : check cmd/API';
815 815
 						}
816 816
 						else
817 817
 						{
818
-						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
818
+						    $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
819 819
 						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
820 820
 						}
821 821
 					}
822 822
 					else
823 823
 					{
824
-						$this->add_rule_match($rule['id'],$rule['num_match']+1);
824
+						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
825 825
 					}
826
-					$this->trap_to_db=($action==-2)?false:true;
826
+					$this->trap_to_db=($action == -2) ?false:true;
827 827
 				}
828 828
 				else
829 829
 				{
830 830
 					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
831 831
 					
832 832
 					$action=$rule['action_nomatch'];
833
-					$this->logging->log('action NOK : '.$action,INFO );
833
+					$this->logging->log('action NOK : '.$action, INFO);
834 834
 					if ($action >= 0)
835 835
 					{
836
-					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
836
+					    if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
837 837
 					    {
838 838
 					        $this->trap_action.='Error sending status : check cmd/API';
839 839
 					    }
840 840
 					    else
841 841
 					    {
842
-    						$this->add_rule_match($rule['id'],$rule['num_match']+1);
842
+    						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
843 843
     						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
844 844
 					    }
845 845
 					}
846 846
 					else
847 847
 					{
848
-						$this->add_rule_match($rule['id'],$rule['num_match']+1);
848
+						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
849 849
 					}
850
-					$this->trap_to_db=($action==-2)?false:true;					
850
+					$this->trap_to_db=($action == -2) ?false:true;					
851 851
 				}
852 852
 				// Put name in source_name
853 853
 				if (!isset($this->trap_data['source_name']))
@@ -856,7 +856,7 @@  discard block
 block discarded – undo
856 856
 				}
857 857
 				else
858 858
 				{
859
-					if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
859
+					if (!preg_match('/'.$rule['host_name'].'/', $this->trap_data['source_name']))
860 860
 					{ // only add if not present
861 861
 						$this->trap_data['source_name'].=','.$rule['host_name'];
862 862
 					}
@@ -864,13 +864,13 @@  discard block
 block discarded – undo
864 864
 			}
865 865
 			catch (Exception $e) 
866 866
 			{ 
867
-			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
867
+			    $this->logging->log('Error in rule eval : '.$e->getMessage(), WARN, '');
868 868
 			    $this->trap_action.=' ERR : '.$e->getMessage();
869 869
 			    $this->trap_data['status']='error';
870 870
 			}
871 871
 			
872 872
 		}
873
-		if ($this->trap_data['status']=='error')
873
+		if ($this->trap_data['status'] == 'error')
874 874
 		{
875 875
 		  $this->trap_to_db=true; // Always put errors in DB for the use can see
876 876
 		}
@@ -886,13 +886,13 @@  discard block
 block discarded – undo
886 886
 	public function add_rule_final($time)
887 887
 	{
888 888
 		$db_conn=$this->trapsDB->db_connect_trap();
889
-		if ($this->trap_action==null) 
889
+		if ($this->trap_action == null) 
890 890
 		{
891 891
 			$this->trap_action='No action';
892 892
 		}
893 893
 		$sql="UPDATE ".$this->db_prefix."received SET process_time = '".$time."' , status_detail='".$this->trap_action."'  WHERE (id = '".$this->trap_id."');";
894 894
 		if ($db_conn->query($sql) === false) {
895
-			$this->logging->log('Error in update query : ' . $sql,WARN,'');
895
+			$this->logging->log('Error in update query : '.$sql, WARN, '');
896 896
 		}
897 897
 	}
898 898
 	
@@ -915,7 +915,7 @@  discard block
 block discarded – undo
915 915
     WHERE s.current_state != 0;";
916 916
 		$db_conn=$this->trapsDB->db_connect_ido();
917 917
 		if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
918
-			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
918
+			$this->logging->log('No result in query : '.$sql_query, ERROR, '');
919 919
 			return 0;
920 920
 		}
921 921
 		$services=$services_db->fetchAll();
@@ -924,7 +924,7 @@  discard block
 block discarded – undo
924 924
 		$sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->db_prefix."rules where revert_ok != 0;";
925 925
 		$db_conn2=$this->trapsDB->db_connect_trap();
926 926
 		if (($rules_db=$db_conn2->query($sql_query)) === false) {
927
-			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
927
+			$this->logging->log('No result in query : '.$sql_query, ERROR, '');
928 928
 			return 0;
929 929
 		}
930 930
 		$rules=$rules_db->fetchAll();
@@ -940,13 +940,13 @@  discard block
 block discarded – undo
940 940
 					$service['host_name'] == $rule['host_name'] &&
941 941
 					($service['last_check'] + $rule['revert_ok']) < $now)
942 942
 				{
943
-					$this->serviceCheckResult($service['host_name'],$service['service_name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
943
+					$this->serviceCheckResult($service['host_name'], $service['service_name'], 0, 'Reset service to OK after '.$rule['revert_ok'].' seconds');
944 944
 					$numreset++;
945 945
 				}
946 946
 			}
947 947
 		}
948 948
 		echo "\n";
949
-		echo $numreset . " service(s) reset to OK\n";
949
+		echo $numreset." service(s) reset to OK\n";
950 950
 		return 0;
951 951
 		
952 952
 	}
Please login to merge, or discard this patch.
tests/expr_test.php 1 patch
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -3,18 +3,18 @@  discard block
 block discarded – undo
3 3
 
4 4
 require_once 'bin/trap_class.php';
5 5
 
6
-$options = getopt("r:d:");
6
+$options=getopt("r:d:");
7 7
 
8
-$icingaweb2Etc=(array_key_exists('d',$options))?$options['d']:"/etc/icingaweb2";
8
+$icingaweb2Etc=(array_key_exists('d', $options)) ? $options['d'] : "/etc/icingaweb2";
9 9
 
10
-$debugLevel=4;// 0=No output 1=critical 2=warning 3=trace 4=ALL
10
+$debugLevel=4; // 0=No output 1=critical 2=warning 3=trace 4=ALL
11 11
 
12
-$trap = new trap($icingaweb2Etc);
13
-$trap->setLogging($debugLevel,'display');
12
+$trap=new trap($icingaweb2Etc);
13
+$trap->setLogging($debugLevel, 'display');
14 14
 
15
-$input=array_key_exists('r',$options);
15
+$input=array_key_exists('r', $options);
16 16
 
17
-if (! $input) {
17
+if (!$input) {
18 18
   $inputStream=fopen('php://stdin', 'r');
19 19
   $rule=chop(fgets($inputStream));
20 20
 } else
@@ -25,11 +25,11 @@  discard block
 block discarded – undo
25 25
   $rule=$trap->ruleClass->eval_cleanup($rule);
26 26
   //echo 'After cleanup : #'.$rule."#\n";
27 27
   $item=0;
28
-  $val = $trap->ruleClass->evaluation($rule,$item);
29
-  if ($val==true) { printf( "true"); } else { printf( "false");}
28
+  $val=$trap->ruleClass->evaluation($rule, $item);
29
+  if ($val == true) { printf("true"); } else { printf("false"); }
30 30
   printf("\n");
31 31
 }
32
-catch (Exception $e) { printf("%s\n",$e->getMessage()); exit(1);}
32
+catch (Exception $e) { printf("%s\n", $e->getMessage()); exit(1); }
33 33
 
34 34
 exit(0);
35 35
 ?>
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Rule.php 1 patch
Spacing   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -30,47 +30,47 @@  discard block
 block discarded – undo
30 30
  * Get full number 
31 31
  * @return array<number,string>
32 32
  */
33
-    private function get_number($rule,&$item)
33
+    private function get_number($rule, &$item)
34 34
     {
35
-        $item2=$item+1;
35
+        $item2=$item + 1;
36 36
         while (
37
-            ($item2!=strlen($rule)) 
38
-            && (preg_match('/[0-9\.]/',$rule[$item2]))) 
37
+            ($item2 != strlen($rule)) 
38
+            && (preg_match('/[0-9\.]/', $rule[$item2]))) 
39 39
         { 
40
-            $item2++ ;
40
+            $item2++;
41 41
         }
42
-        $val=substr($rule,$item,$item2-$item);
42
+        $val=substr($rule, $item, $item2 - $item);
43 43
         $item=$item2;
44 44
         //echo "number ".$val."\n";
45 45
         
46
-        return array(0,$val);
46
+        return array(0, $val);
47 47
     }
48 48
 
49
-    private function get_string($rule,&$item)
49
+    private function get_string($rule, &$item)
50 50
     {
51 51
         $item++;
52
-        $item2=$this->eval_getNext($rule,$item,'"');
53
-        $val=substr($rule,$item,$item2-$item-1);
52
+        $item2=$this->eval_getNext($rule, $item, '"');
53
+        $val=substr($rule, $item, $item2 - $item - 1);
54 54
         $item=$item2;
55 55
         //echo "string : ".$val."\n";
56
-        return array(1,$val);
56
+        return array(1, $val);
57 57
         
58 58
     }
59 59
     
60
-    private function get_group($rule,&$item)
60
+    private function get_group($rule, &$item)
61 61
     {
62 62
         $item++;
63 63
         $start=$item;
64 64
         $parenthesis_count=0;
65 65
         while (($item < strlen($rule)) // Not end of string AND
66
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
66
+            && (($rule[$item] != ')') || $parenthesis_count > 0)) // Closing ')' or embeded ()
67 67
         {
68
-            if ($rule[$item] == '"' )
68
+            if ($rule[$item] == '"')
69 69
             { // pass through string
70 70
                 $item++;
71
-                $item=$this->eval_getNext($rule,$item,'"');
71
+                $item=$this->eval_getNext($rule, $item, '"');
72 72
             }
73
-            else{
73
+            else {
74 74
                 if ($rule[$item] == '(')
75 75
                 {
76 76
                     $parenthesis_count++;
@@ -83,19 +83,19 @@  discard block
 block discarded – undo
83 83
             }
84 84
         }
85 85
         
86
-        if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
87
-        $val=substr($rule,$start,$item-$start);
86
+        if ($item == strlen($rule)) {throw new Exception("no closing () in ".$rule." at ".$item); }
87
+        $val=substr($rule, $start, $item - $start);
88 88
         $item++;
89 89
         $start=0;
90 90
         //echo "group : ".$val."\n";
91 91
         // returns evaluation of group as type 2 (boolean)
92
-        return array(2,$this->evaluation($val,$start));
92
+        return array(2, $this->evaluation($val, $start));
93 93
     }
94 94
     
95
-    protected function eval_getElement($rule,&$item)
95
+    protected function eval_getElement($rule, &$item)
96 96
     {
97
-        while ($rule[$item]==' ') $item++;
98
-        if (preg_match('/[0-9\.]/',$rule[$item]))
97
+        while ($rule[$item] == ' ') $item++;
98
+        if (preg_match('/[0-9\.]/', $rule[$item]))
99 99
         { // number
100 100
             return $this->get_number($rule, $item);
101 101
         }
@@ -108,48 +108,48 @@  discard block
 block discarded – undo
108 108
         { // grouping
109 109
             return $this->get_group($rule, $item);
110 110
         }
111
-        throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
111
+        throw new Exception("number/string not found in ".$rule." at ".$item.' : '.$rule[$item]);
112 112
         
113 113
     }
114 114
     
115
-    protected function eval_getNext($rule,$item,$tok)
115
+    protected function eval_getNext($rule, $item, $tok)
116 116
     {
117 117
         while (
118
-            ($rule[$item] != $tok ) 
118
+            ($rule[$item] != $tok) 
119 119
             && ($item < strlen($rule))) 
120 120
         { 
121 121
             $item++;
122 122
         }
123
-        if ($item==strlen($rule)) {
124
-            throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
123
+        if ($item == strlen($rule)) {
124
+            throw new Exception("closing '".$tok."' not found in ".$rule." at ".$item);
125 125
         }
126
-        return $item+1;
126
+        return $item + 1;
127 127
     }
128 128
     
129
-    protected function eval_getOper($rule,&$item)
129
+    protected function eval_getOper($rule, &$item)
130 130
     {
131
-        while ($rule[$item]==' ') $item++;
131
+        while ($rule[$item] == ' ') $item++;
132 132
         switch ($rule[$item])
133 133
         {
134 134
             case '<':
135
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
136
-                $item++; return array(0,"<");
135
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, "<="); }
136
+                $item++; return array(0, "<");
137 137
             case '>':
138
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
139
-                $item++; return array(0,">");
138
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, ">="); }
139
+                $item++; return array(0, ">");
140 140
             case '=':
141
-                $item++; return array(0,"=");
141
+                $item++; return array(0, "=");
142 142
             case '!':
143
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
144
-                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
143
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, "!="); }
144
+                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule." at ".$item);
145 145
             case '~':
146
-                $item++; return array(0,"~");
146
+                $item++; return array(0, "~");
147 147
             case '|':
148
-                $item++; return array(1,"|");
148
+                $item++; return array(1, "|");
149 149
             case '&':
150
-                $item++; return array(1,"&");
150
+                $item++; return array(1, "&");
151 151
             default	:
152
-                throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
152
+                throw new Exception("Erreur in expr - operator not found in ".$rule." at ".$item);
153 153
         }
154 154
     }
155 155
     
@@ -162,10 +162,10 @@  discard block
 block discarded – undo
162 162
      *   comparison int vs strings will return null (error)
163 163
      *	return : bool or null on error
164 164
      */
165
-    public function evaluation($rule,&$item)
165
+    public function evaluation($rule, &$item)
166 166
     {
167 167
         //echo "Evaluation of ".substr($rule,$item)."\n";
168
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
168
+        if ($rule[$item] == '!') // If '!' found, negate next expression.
169 169
         {
170 170
             $negate=true;
171 171
             $item++;
@@ -175,63 +175,63 @@  discard block
 block discarded – undo
175 175
             $negate=false;
176 176
         }
177 177
         // First element : number, string or ()
178
-        list($type1,$val1) = $this->eval_getElement($rule,$item);
178
+        list($type1, $val1)=$this->eval_getElement($rule, $item);
179 179
         //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
180 180
         
181
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
181
+        if ($item == strlen($rule)) // If only element, return value, but only boolean
182 182
         {
183 183
             if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
184
-            if ($negate === true) $val1= ! $val1;
184
+            if ($negate === true) $val1=!$val1;
185 185
             return $val1;
186 186
         }
187 187
         
188 188
         // Second element : operator
189
-        list($typec,$comp) = $this->eval_getOper($rule,$item);
189
+        list($typec, $comp)=$this->eval_getOper($rule, $item);
190 190
         //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
191 191
         
192 192
         // Third element : number, string or ()
193
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
193
+        if ($rule[$item] == '!') // starts with a ! so evaluate whats next
194 194
         {
195 195
             $item++;
196 196
             if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
197
-            $val2= ! $this->evaluation($rule,$item);
197
+            $val2=!$this->evaluation($rule, $item);
198 198
             $type2=2; // result is a boolean
199 199
         }
200 200
         else
201 201
         {
202
-            list($type2,$val2) = $this->eval_getElement($rule,$item);
202
+            list($type2, $val2)=$this->eval_getElement($rule, $item);
203 203
         }
204 204
         //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
205 205
         
206
-        if ($type1!=$type2)  // cannot compare different types
206
+        if ($type1 != $type2)  // cannot compare different types
207 207
         {
208 208
             throw new Exception("Cannot compare string & number : ".$rule);
209 209
         }
210
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
210
+        if ($typec == 1 && $type1 != 2) // cannot use & or | with string/number
211 211
         {
212 212
             throw new Exception("Cannot use boolean operators with string & number : ".$rule);
213 213
         }
214 214
         
215
-        switch ($comp){
216
-            case '<':	$retVal= ($val1 < $val2); break;
217
-            case '<=':	$retVal= ($val1 <= $val2); break;
218
-            case '>':	$retVal= ($val1 > $val2); break;
219
-            case '>=':	$retVal= ($val1 >= $val2); break;
220
-            case '=':	$retVal= ($val1 == $val2); break;
221
-            case '!=':	$retVal= ($val1 != $val2); break;
222
-            case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
223
-            case '|':	$retVal= ($val1 || $val2); break;
224
-            case '&':	$retVal= ($val1 && $val2); break;
215
+        switch ($comp) {
216
+            case '<':	$retVal=($val1 < $val2); break;
217
+            case '<=':	$retVal=($val1 <= $val2); break;
218
+            case '>':	$retVal=($val1 > $val2); break;
219
+            case '>=':	$retVal=($val1 >= $val2); break;
220
+            case '=':	$retVal=($val1 == $val2); break;
221
+            case '!=':	$retVal=($val1 != $val2); break;
222
+            case '~':	$retVal=(preg_match('/'.preg_replace('/"/', '', $val2).'/', $val1)); break;
223
+            case '|':	$retVal=($val1 || $val2); break;
224
+            case '&':	$retVal=($val1 && $val2); break;
225 225
             default:  throw new Exception("Error in expression - unknown comp : ".$comp);
226 226
         }
227
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
227
+        if ($negate === true) $retVal=!$retVal; // Inverse result if negate before expression
228 228
         
229
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
229
+        if ($item == strlen($rule)) return $retVal; // End of string : return evaluation
230 230
         // check for logical operator :
231 231
         switch ($rule[$item])
232 232
         {
233
-            case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
234
-            case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
233
+            case '|':	$item++; return ($retVal || $this->evaluation($rule, $item));
234
+            case '&':	$item++; return ($retVal && $this->evaluation($rule, $item));
235 235
             
236 236
             default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
237 237
         }
@@ -244,17 +244,17 @@  discard block
 block discarded – undo
244 244
         $rule2='';
245 245
         while ($item < strlen($rule))
246 246
         {
247
-            if ($rule[$item]==' ') { $item++; continue; }
248
-            if ($rule[$item]=='"')
247
+            if ($rule[$item] == ' ') { $item++; continue; }
248
+            if ($rule[$item] == '"')
249 249
             {
250 250
                 $rule2.=$rule[$item];
251 251
                 $item++;
252
-                while (($rule[$item]!='"') && ($item < strlen($rule)))
252
+                while (($rule[$item] != '"') && ($item < strlen($rule)))
253 253
                 {
254 254
                     $rule2.=$rule[$item];
255 255
                     $item++;
256 256
                 }
257
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
257
+                if ($item == strlen($rule)) throw new Exception("closing '\"' not found in ".$rule." at ".$item);
258 258
                 $rule2.=$rule[$item];
259 259
                 $item++;
260 260
                 continue;
@@ -273,14 +273,14 @@  discard block
 block discarded – undo
273 273
      *	@return bool : true : rule match, false : rule don't match , throw exception on error.
274 274
      */
275 275
     
276
-    public function eval_rule($rule,$oidList)
276
+    public function eval_rule($rule, $oidList)
277 277
     {
278
-        if ($rule==null || $rule == '') // Empty rule is always true
278
+        if ($rule == null || $rule == '') // Empty rule is always true
279 279
         {
280 280
             return true;
281 281
         }
282 282
         $matches=array();
283
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
283
+        while (preg_match('/_OID\(([0-9\.\*]+)\)/', $rule, $matches) == 1)
284 284
         {
285 285
             $oid=$matches[1];
286 286
             $found=0;
@@ -292,38 +292,38 @@  discard block
 block discarded – undo
292 292
             // replace * with \* in oid for preg_replace
293 293
             $oid=preg_replace('/\*/', '\*', $oid);
294 294
             
295
-            $this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
295
+            $this->logging->log('OID in rule : '.$oid.' / '.$oidR, DEBUG);
296 296
             
297
-            foreach($oidList as $val)
297
+            foreach ($oidList as $val)
298 298
             {
299
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
299
+                if (preg_match("/^$oidR$/", $val->oid) == 1)
300 300
                 {
301
-                    if (!preg_match('/^[0-9]*\.?[0-9]+$/',$val->value))
301
+                    if (!preg_match('/^[0-9]*\.?[0-9]+$/', $val->value))
302 302
                     { // If not a number, change " to ' and put " around it
303
-                        $val->value=preg_replace('/"/',"'",$val->value);
303
+                        $val->value=preg_replace('/"/', "'", $val->value);
304 304
                         $val->value='"'.$val->value.'"';
305 305
                     }
306 306
                     $rep=0;
307
-                    $rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
308
-                    if ($rep==0)
307
+                    $rule=preg_replace('/_OID\('.$oid.'\)/', $val->value, $rule, -1, $rep);
308
+                    if ($rep == 0)
309 309
                     {
310
-                        $this->logging->log("Error in rule_eval",WARN,'');
310
+                        $this->logging->log("Error in rule_eval", WARN, '');
311 311
                         return false;
312 312
                     }
313 313
                     $found=1;
314 314
                     break;
315 315
                 }
316 316
             }
317
-            if ($found==0)
317
+            if ($found == 0)
318 318
             {	// OID not found : throw error
319 319
                 throw new Exception('OID '.$oid.' not found in trap');
320 320
             }
321 321
         }
322 322
         $item=0;
323 323
         $rule=$this->eval_cleanup($rule);
324
-        $this->logging->log('Rule after clenup: '.$rule,INFO );
324
+        $this->logging->log('Rule after clenup: '.$rule, INFO);
325 325
         
326
-        return  $this->evaluation($rule,$item);
326
+        return  $this->evaluation($rule, $item);
327 327
     }
328 328
     
329 329
 }
330 330
\ No newline at end of file
Please login to merge, or discard this patch.
application/controllers/HelperController.php 1 patch
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -27,12 +27,12 @@  discard block
 block discarded – undo
27 27
 			return;
28 28
 		}
29 29
 
30
-		$retHosts=array('status'=>'OK','hosts' => array());
30
+		$retHosts=array('status'=>'OK', 'hosts' => array());
31 31
 
32 32
 		$hosts=$this->getHostByIP($hostFilter);
33 33
 		foreach ($hosts as $val)
34 34
 		{
35
-			array_push($retHosts['hosts'],$val->name);
35
+			array_push($retHosts['hosts'], $val->name);
36 36
 		}
37 37
 		
38 38
 		$this->_helper->json($retHosts);
@@ -55,12 +55,12 @@  discard block
 block discarded – undo
55 55
 			return;
56 56
 		}
57 57
 
58
-		$retHosts=array('status'=>'OK','hosts' => array());
58
+		$retHosts=array('status'=>'OK', 'hosts' => array());
59 59
 
60 60
 		$hosts=$this->getHostGroupByName($hostFilter);
61 61
 		foreach ($hosts as $val)
62 62
 		{
63
-			array_push($retHosts['hosts'],$val->name);
63
+			array_push($retHosts['hosts'], $val->name);
64 64
 		}
65 65
 		
66 66
 		$this->_helper->json($retHosts);
@@ -82,31 +82,31 @@  discard block
 block discarded – undo
82 82
 		}
83 83
 		else
84 84
 		{
85
-			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
85
+			$this->_helper->json(array('status'=>'No Hosts', 'hostid' => -1));
86 86
 			return;
87 87
 		}
88 88
 		
89 89
 		$hostArray=$this->getHostByName($host);
90 90
 		if (count($hostArray) > 1)
91 91
 		{	
92
-			$this->_helper->json(array('status'=>'More than one host matches','hostid' => -1));
92
+			$this->_helper->json(array('status'=>'More than one host matches', 'hostid' => -1));
93 93
 			return;
94 94
 		}
95 95
 		else if (count($hostArray) == 0)
96 96
 		{
97
-			$this->_helper->json(array('status'=>'No host matches','hostid' => -1));
97
+			$this->_helper->json(array('status'=>'No host matches', 'hostid' => -1));
98 98
 			return;
99 99
 		}
100 100
 		$services=$this->getServicesByHostid($hostArray[0]->id);
101 101
 		if (count($services) < 1)
102 102
 		{
103
-			$this->_helper->json(array('status'=>'No services found for host','hostid' => $hostArray[0]->id));
103
+			$this->_helper->json(array('status'=>'No services found for host', 'hostid' => $hostArray[0]->id));
104 104
 			return;
105 105
 		}
106
-		$retServices=array('status'=>'OK','services' => array(),'hostid' => $hostArray[0]->id);
106
+		$retServices=array('status'=>'OK', 'services' => array(), 'hostid' => $hostArray[0]->id);
107 107
 		foreach ($services as $val)
108 108
 		{
109
-			array_push($retServices['services'],array($val->id , $val->name));
109
+			array_push($retServices['services'], array($val->id, $val->name));
110 110
 		}
111 111
 		$this->_helper->json($retServices);
112 112
 	}
@@ -126,28 +126,28 @@  discard block
 block discarded – undo
126 126
 		}
127 127
 		else
128 128
 		{
129
-			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
129
+			$this->_helper->json(array('status'=>'No Hosts', 'hostid' => -1));
130 130
 			return;
131 131
 		}
132 132
 		
133 133
 		$hostArray=$this->getHostGroupByName($host);
134 134
 		if (count($hostArray) > 1)
135 135
 		{	
136
-			$this->_helper->json(array('status'=>'More than one hostgroup matches','hostid' => -1));
136
+			$this->_helper->json(array('status'=>'More than one hostgroup matches', 'hostid' => -1));
137 137
 			return;
138 138
 		}
139 139
 		else if (count($hostArray) == 0)
140 140
 		{
141
-			$this->_helper->json(array('status'=>'No hostgroup matches','hostid' => -1));
141
+			$this->_helper->json(array('status'=>'No hostgroup matches', 'hostid' => -1));
142 142
 			return;
143 143
 		}
144 144
 		$services=$this->getServicesByHostGroupid($hostArray[0]->id);
145 145
 		if (count($services) < 1)
146 146
 		{
147
-			$this->_helper->json(array('status'=>'No services found for hostgroup','hostid' => $hostArray[0]->id));
147
+			$this->_helper->json(array('status'=>'No services found for hostgroup', 'hostid' => $hostArray[0]->id));
148 148
 			return;
149 149
 		}
150
-		$retServices=array('status'=>'OK','services' => $services,'hostid' => $hostArray[0]->id);
150
+		$retServices=array('status'=>'OK', 'services' => $services, 'hostid' => $hostArray[0]->id);
151 151
 		
152 152
 		$this->_helper->json($retServices);
153 153
 	}
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 		try
173 173
 		{
174 174
 			$traplist=$this->getMIB()->getTrapList($mib);
175
-			$retTraps=array('status'=>'OK','traps' => $traplist);
175
+			$retTraps=array('status'=>'OK', 'traps' => $traplist);
176 176
 		} 
177 177
 		catch (Exception $e) 
178 178
 		{ 
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
 		try
202 202
 		{
203 203
 			$objectlist=$this->getMIB()->getObjectList($trap);
204
-			$retObjects=array('status'=>'OK','objects' => $objectlist);
204
+			$retObjects=array('status'=>'OK', 'objects' => $objectlist);
205 205
 		} 
206 206
 		catch (Exception $e) 
207 207
 		{ 
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 		if (isset($postData['days']))
279 279
 		{
280 280
 			$days=$postData['days'];
281
-			if (!preg_match('/^[0-9]+$/',$days))
281
+			if (!preg_match('/^[0-9]+$/', $days))
282 282
 			{
283 283
 				$this->_helper->json(array('status'=>'invalid days : '.$days));
284 284
 				return;
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
 		if (isset($postData['action']))
293 293
 		{
294 294
 			$action=$postData['action'];
295
-			if ($action != 'save' && $action !='execute')
295
+			if ($action != 'save' && $action != 'execute')
296 296
 			{
297 297
 				$this->_helper->json(array('status'=>'unknown action '.$action));
298 298
 				return;
@@ -307,11 +307,11 @@  discard block
 block discarded – undo
307 307
 		{
308 308
 			try
309 309
 			{
310
-				$this->setDBConfigValue('db_remove_days',$days);
310
+				$this->setDBConfigValue('db_remove_days', $days);
311 311
 			}
312 312
 			catch (Exception $e)
313 313
 			{
314
-				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
314
+				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage()));
315 315
 				return;
316 316
 			}
317 317
 			$this->_helper->json(array('status'=>'OK'));
@@ -321,16 +321,16 @@  discard block
 block discarded – undo
321 321
 		{
322 322
 			try
323 323
 			{
324
-				require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
324
+				require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
325 325
 				$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
326 326
 				$debug_level=4;
327
-				$Trap = new Trap($icingaweb2_etc);
328
-				$Trap->setLogging($debug_level,'syslog');
327
+				$Trap=new Trap($icingaweb2_etc);
328
+				$Trap->setLogging($debug_level, 'syslog');
329 329
 				$Trap->eraseOldTraps($days);
330 330
 			}
331 331
 			catch (Exception $e)
332 332
 			{
333
-				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage() ));
333
+				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage()));
334 334
 				return;
335 335
 			}			
336 336
 			$this->_helper->json(array('status'=>'OK'));
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
 		if (isset($postData['file']))
365 365
 		{ 
366 366
 			$file=$postData['file'];
367
-			$fileHandler=@fopen($file,'w');
367
+			$fileHandler=@fopen($file, 'w');
368 368
 			if ($fileHandler == false)
369 369
 			{   // File os note writabe / cannot create
370 370
 			    $this->_helper->json(array('status'=>'File not writable :  '.$file));
@@ -396,13 +396,13 @@  discard block
 block discarded – undo
396 396
 		
397 397
 		try
398 398
 		{
399
-			$this->setDBConfigValue('log_destination',$destination);
400
-			$this->setDBConfigValue('log_file',$file);
401
-			$this->setDBConfigValue('log_level',$level);
399
+			$this->setDBConfigValue('log_destination', $destination);
400
+			$this->setDBConfigValue('log_file', $file);
401
+			$this->setDBConfigValue('log_level', $level);
402 402
 		}
403 403
 		catch (Exception $e)
404 404
 		{
405
-			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
405
+			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage()));
406 406
 			return;
407 407
 		}
408 408
 		$this->_helper->json(array('status'=>'OK'));
@@ -445,21 +445,21 @@  discard block
 block discarded – undo
445 445
 	    {
446 446
 	        try
447 447
 	        {
448
-	            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
448
+	            require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
449 449
 	            $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
450
-	            $Trap = new Trap($icingaweb2_etc);
450
+	            $Trap=new Trap($icingaweb2_etc);
451 451
 	            // Cleanup spaces before eval
452 452
 	            $rule=$Trap->ruleClass->eval_cleanup($rule);
453 453
 	            // Eval
454 454
 	            $item=0;
455
-	            $rule=$Trap->ruleClass->evaluation($rule,$item);
455
+	            $rule=$Trap->ruleClass->evaluation($rule, $item);
456 456
 	        }
457 457
 	        catch (Exception $e)
458 458
 	        {
459
-	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
459
+	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage()));
460 460
 	            return;
461 461
 	        }
462
-	        $return=($rule==true)?'true':'false';
462
+	        $return=($rule == true) ? 'true' : 'false';
463 463
 	        $this->_helper->json(array('status'=>'OK', 'message' => $return));
464 464
 	    }
465 465
 	    
Please login to merge, or discard this patch.
application/controllers/SettingsController.php 1 patch
Spacing   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -72,15 +72,15 @@  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
       
@@ -91,13 +91,13 @@  discard block
 block discarded – undo
91 91
       {
92 92
           case 2:
93 93
           case 4:
94
-              $db_message[$dberror[0]][1] .= $dberror[1];
94
+              $db_message[$dberror[0]][1].=$dberror[1];
95 95
               break;
96 96
           case 3:
97
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
97
+              $db_message[$dberror[0]][1].=$dberror[1].', Message : '.$dberror[2];
98 98
               break;
99 99
           case 5:
100
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
100
+              $db_message[$dberror[0]][1].=' version '.$dberror[1].', version needed : '.$dberror[2];
101 101
               break;
102 102
           case 0:
103 103
           case 1:
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
       
110 110
       $dberror=$this->getIdoDb(true); // Get IDO DB in test mode
111 111
       $this->view->ido_db_error=$dberror[0];
112
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
112
+      $this->view->ido_message='IDO Database : '.$dberror[1];
113 113
   }
114 114
   
115 115
   /**
@@ -121,13 +121,13 @@  discard block
 block discarded – undo
121 121
   {
122 122
       if ($this->Config()->get('config', 'icingaAPI_host') != '')
123 123
       {
124
-          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
124
+          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'), $this->Config()->get('config', 'icingaAPI_port'));
125 125
           $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
126 126
           try {
127
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
127
+              list($this->view->apimessageError, $this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
128 128
               //$this->view->apimessageError=false;
129 129
           } catch (RuntimeException $e) {
130
-              $this->view->apimessage='API config : ' . $e->getMessage();
130
+              $this->view->apimessage='API config : '.$e->getMessage();
131 131
               $this->view->apimessageError=true;
132 132
           }
133 133
       }
@@ -152,9 +152,9 @@  discard block
 block discarded – undo
152 152
       {
153 153
           $output=array();
154 154
           
155
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2_etc=" ',$output);
155
+          exec('cat '.$this->module->getBaseDir().'/bin/trap_in.php | grep "\$icingaweb2_etc=" ', $output);
156 156
           
157
-          if (! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
157
+          if (!preg_match('#"'.$icingaweb2_etc.'"#', $output[0]))
158 158
           {
159 159
               $this->view->icingaEtcWarn=1;
160 160
               $this->view->icingaweb2_etc=$icingaweb2_etc;
@@ -170,12 +170,12 @@  discard block
 block discarded – undo
170 170
    */
171 171
   private function get_db_list($allowed)
172 172
   {
173
-      $resources = array();
173
+      $resources=array();
174 174
       foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
175 175
       {
176 176
           if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
177 177
           {
178
-              $resources[$name] = $name;
178
+              $resources[$name]=$name;
179 179
           }
180 180
       }
181 181
       return $resources;
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 	// But check read permission
203 203
 	$this->checkReadPermission();
204 204
 	
205
-	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');
205
+	$this->view->tabs=$this->Module()->getConfigTabs()->activate('config');
206 206
 	
207 207
 	// Get message : sent on configuration problems detected by controllers
208 208
     $this->get_param();
@@ -217,32 +217,32 @@  discard block
 block discarded – undo
217 217
     $this->check_api();
218 218
 	
219 219
 	//*********** Test snmptrapd alive and options
220
-	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
220
+	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage)=$this->checkSnmpTrapd();
221 221
 
222 222
 	// List DB in $ressources
223
-	$resources = $this->get_db_list(array('mysql', 'pgsql')); 
223
+	$resources=$this->get_db_list(array('mysql', 'pgsql')); 
224 224
 
225 225
 	// Check standard Icingaweb2 path
226 226
 	$this->check_icingaweb_path();
227 227
 	
228 228
 	// Setup path for mini documentation
229
-	$this->view->traps_in_config= PHP_BINARY . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
229
+	$this->view->traps_in_config=PHP_BINARY.' '.$this->Module()->getBaseDir().'/bin/trap_in.php';
230 230
 	
231
-	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
231
+	$this->view->installer=$this->Module()->getBaseDir().'/bin/installer.sh '
232 232
 	    . ' -c all ' 
233
-	    . ' -d ' . $this->Module()->getBaseDir()
234
-	    . ' -p ' . PHP_BINARY
235
-	    . ' -a ' . exec('whoami')
236
-	    . ' -w ' . Icinga::app()->getConfigDir();
233
+	    . ' -d '.$this->Module()->getBaseDir()
234
+	    . ' -p '.PHP_BINARY
235
+	    . ' -a '.exec('whoami')
236
+	    . ' -w '.Icinga::app()->getConfigDir();
237 237
 	        
238 238
 	// ******************* configuration form setup*******************
239
-	$this->view->form = $form = new TrapsConfigForm();
239
+	$this->view->form=$form=new TrapsConfigForm();
240 240
 	
241 241
 	// set default paths;
242
-	$this->view->form->setPaths($this->Module()->getBaseDir(),Icinga::app()->getConfigDir());
242
+	$this->view->form->setPaths($this->Module()->getBaseDir(), Icinga::app()->getConfigDir());
243 243
 	
244 244
 	// set default ido database
245
-	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring','backends')->get('icinga','resource'));
245
+	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring', 'backends')->get('icinga', 'resource'));
246 246
 	
247 247
 	// Make form handle request.
248 248
 	$form->setIniConfig($this->Config())
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
   public function createschemaAction()
255 255
   {
256 256
 	$this->checkModuleConfigPermission();
257
-	$this->getTabs()->add('create_schema',array(
257
+	$this->getTabs()->add('create_schema', array(
258 258
 		'active'	=> true,
259 259
 		'label'		=> $this->translate('Create Schema'),
260 260
 		'url'		=> Url::fromRequest()
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 		$dbName=$this->Config()->get('config', 'database');
276 276
 
277 277
 		try {
278
-		  $dbResource = ResourceFactory::getResourceConfig($dbName);
278
+		  $dbResource=ResourceFactory::getResourceConfig($dbName);
279 279
 		  $dbType=$dbResource->get('db');
280 280
 		  switch ($dbType) {
281 281
 		      case 'mysql':
@@ -287,34 +287,34 @@  discard block
 block discarded – undo
287 287
 		      default:
288 288
 		          throw new ConfigurationError('Unsuported database : '.$dbType);
289 289
 		  }
290
-		} catch (ConfigurationError $e )
290
+		} catch (ConfigurationError $e)
291 291
 		{
292
-		    printf("Database configuration error : %s",$e->getMessage());
292
+		    printf("Database configuration error : %s", $e->getMessage());
293 293
 		    return;
294 294
 		}
295 295
 		printf('<pre>');
296
-		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
296
+		require_once $this->Module()->getBaseDir().'/bin/trap_class.php';
297 297
 		
298 298
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
299 299
 		$debug_level=4;
300
-		$Trap = new Trap($icingaweb2_etc);
301
-		$Trap->setLogging($debug_level,'display');
300
+		$Trap=new Trap($icingaweb2_etc);
301
+		$Trap->setLogging($debug_level, 'display');
302 302
 		
303 303
 		$prefix=$this->Config()->get('config', 'database_prefix');
304 304
 		// schema file : <path>/SQL/schema_v<verion>.<dbtype>
305
-		$schema=$this->Module()->getBaseDir() . 
306
-		'/SQL/schema_v'. $this->getModuleConfig()->getDbCurVersion() . '.' . $dbFileExt;
305
+		$schema=$this->Module()->getBaseDir(). 
306
+		'/SQL/schema_v'.$this->getModuleConfig()->getDbCurVersion().'.'.$dbFileExt;
307 307
 		
308
-		$Trap->trapsDB->create_schema($schema,$prefix);
308
+		$Trap->trapsDB->create_schema($schema, $prefix);
309 309
 		echo '</pre>';
310 310
 	}
311
-	echo '<br><br>Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a>';
311
+	echo '<br><br>Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a>';
312 312
   }
313 313
 
314 314
   public function updateschemaAction()
315 315
   {
316 316
 	  $this->checkModuleConfigPermission();
317
-    	$this->getTabs()->add('get',array(
317
+    	$this->getTabs()->add('get', array(
318 318
     		'active'	=> true,
319 319
     		'label'		=> $this->translate('Update Schema'),
320 320
     		'url'		=> Url::fromRequest()
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
 	  
324 324
 	  $dberror=$this->getDb(true); // Get DB in test mode
325 325
 	  
326
-	  echo 'Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a><br><br>';
326
+	  echo 'Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a><br><br>';
327 327
 	  
328 328
 	  if ($dberror[0] == 0)
329 329
 	  {
@@ -336,40 +336,40 @@  discard block
 block discarded – undo
336 336
 	      return;
337 337
 	  }
338 338
       // setup
339
-	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
339
+	  require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
340 340
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
341 341
 	  $debug_level=4;
342
-	  $Trap = new Trap($icingaweb2_etc);
342
+	  $Trap=new Trap($icingaweb2_etc);
343 343
 	  
344 344
 	  
345 345
 	  $prefix=$this->Config()->get('config', 'database_prefix');
346
-	  $updateSchema=$this->Module()->getBaseDir() . '/SQL/';
346
+	  $updateSchema=$this->Module()->getBaseDir().'/SQL/';
347 347
 	  
348 348
 	  $target_version=$dberror[2];
349 349
 	  
350 350
 	  if ($this->params->get('msgok') == null) {
351 351
 	      // Check for messages and display if any
352 352
               echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
353
-	      $Trap->setLogging(2,'syslog');
354
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
353
+	      $Trap->setLogging(2, 'syslog');
354
+	      $message=$Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix, true);
355 355
 	      if ($message != '')
356 356
 	      {
357 357
 	          echo 'Note :<br><pre>';
358 358
 	          echo $message;
359 359
 	          echo '</pre>';
360 360
 	          echo '<br>';
361
-	          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>';
361
+	          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>';
362 362
 	          echo '<br>';
363 363
 	          return;
364 364
 	      }
365 365
 	  }
366 366
 	  
367
-	  $Trap->setLogging($debug_level,'display');
367
+	  $Trap->setLogging($debug_level, 'display');
368 368
 	  
369
-	  echo 'Updating schema to '. $target_version . ': <br>';
369
+	  echo 'Updating schema to '.$target_version.': <br>';
370 370
 	  echo '<pre>';
371 371
 	  	  
372
-	  $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix);
372
+	  $Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix);
373 373
 	  echo '</pre>';
374 374
   }  
375 375
 
@@ -377,26 +377,26 @@  discard block
 block discarded – undo
377 377
   {
378 378
       $psOutput=array();
379 379
       // First check is someone is listening to port 162. As not root, we can't have pid... 
380
-      exec('netstat -an |grep -E "udp.*:162"',$psOutput);
380
+      exec('netstat -an |grep -E "udp.*:162"', $psOutput);
381 381
       if (count($psOutput) == 0)
382 382
       {
383
-          return array(1,'Port UDP/162 is not open : snmptrapd must not be started');
383
+          return array(1, 'Port UDP/162 is not open : snmptrapd must not be started');
384 384
       }
385 385
       $psOutput=array();
386
-      exec('ps fax |grep snmptrapd |grep -v grep',$psOutput);
386
+      exec('ps fax |grep snmptrapd |grep -v grep', $psOutput);
387 387
       if (count($psOutput) == 0)
388 388
       {
389
-          return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
389
+          return array(1, "UDP/162 : OK, but no snmptrapd process (?)");
390 390
       }
391 391
       // Assume there is only one line... TODO : see if there is a better way to do this
392
-      $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
393
-      if (!preg_match('/-n/',$line))
394
-          return array(1,'snmptrapd has no -n option : '.$line);
395
-      if (!preg_match('/-O[^ ]*n/',$line))
396
-          return array(1,'snmptrapd has no -On option : '.$line);
397
-      if (!preg_match('/-O[^ ]*e/',$line))
398
-          return array(1,'snmptrapd has no -Oe option : '.$line);
392
+      $line=preg_replace('/^.*snmptrapd /', '', $psOutput[0]);
393
+      if (!preg_match('/-n/', $line))
394
+          return array(1, 'snmptrapd has no -n option : '.$line);
395
+      if (!preg_match('/-O[^ ]*n/', $line))
396
+          return array(1, 'snmptrapd has no -On option : '.$line);
397
+      if (!preg_match('/-O[^ ]*e/', $line))
398
+          return array(1, 'snmptrapd has no -Oe option : '.$line);
399 399
       
400
-      return array(0,'snmptrapd listening to UDP/162, options : '.$line);
400
+      return array(0, 'snmptrapd listening to UDP/162, options : '.$line);
401 401
   }
402 402
 }
Please login to merge, or discard this patch.