Passed
Push — master ( df2595...b8f383 )
by Patrick
01:54
created
bin/trap_class.php 3 patches
Indentation   +597 added lines, -597 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 	
61 61
 	function __construct($etc_dir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
62 62
 	{
63
-	    // Paths of ini files
63
+		// Paths of ini files
64 64
 		$this->icingaweb2_etc=$etc_dir;
65 65
 		$this->trap_module_config=$this->icingaweb2_etc."/modules/trapdirector/config.ini";		
66 66
 		$this->icingaweb2_ressources=$this->icingaweb2_etc."/resources.ini";
@@ -69,18 +69,18 @@  discard block
 block discarded – undo
69 69
 		$this->logging = new Logging();
70 70
 		if ($baseLogLevel != null)
71 71
 		{
72
-		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
73
-		    $this->logSetup=true;
72
+			$this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
73
+			$this->logSetup=true;
74 74
 		}
75 75
 		else 
76
-		    $this->logSetup=false;
76
+			$this->logSetup=false;
77 77
 		$this->logging->log('Loggin started', INFO);
78 78
 
79 79
 		// Get options from ini files
80 80
 		$trapConfig=parse_ini_file($this->trap_module_config,true);
81 81
 		if ($trapConfig == false)
82 82
 		{
83
-		    $this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
83
+			$this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
84 84
 		}
85 85
 		$this->getMainOptions($trapConfig); // Get main options from ini file
86 86
 		$this->setupDatabase($trapConfig); // Setup database class
@@ -110,27 +110,27 @@  discard block
 block discarded – undo
110 110
 	 */
111 111
 	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
112 112
 	{
113
-	    if (!isset($option_array[$option_category][$option_name]))
114
-	    {
115
-	        if ($message === null)
116
-	        {
117
-	            $message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
118
-	        }
119
-	        $this->logging->log($message,$log_level,'syslog');
120
-	        return false;
121
-	    }
122
-	    else
123
-	    {
124
-	        $option_var=$option_array[$option_category][$option_name];
125
-	        return true;
126
-	    }
113
+		if (!isset($option_array[$option_category][$option_name]))
114
+		{
115
+			if ($message === null)
116
+			{
117
+				$message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
118
+			}
119
+			$this->logging->log($message,$log_level,'syslog');
120
+			return false;
121
+		}
122
+		else
123
+		{
124
+			$option_var=$option_array[$option_category][$option_name];
125
+			return true;
126
+		}
127 127
 	}
128 128
 	
129 129
 	/** 
130 130
 	 * Get options from ini file and database
131 131
 	 * Setup the database class with options.
132 132
 	 * @param array : ini file array
133
-	*/
133
+	 */
134 134
 	protected function getMainOptions($trap_config)
135 135
 	{
136 136
 		$trap_config=parse_ini_file($this->trap_module_config,true);
@@ -153,55 +153,55 @@  discard block
 block discarded – undo
153 153
 		// API options
154 154
 		if ($this->getOptionIfSet($trap_config,'config','icingaAPI_host', $this->api_hostname))
155 155
 		{
156
-		    $this->api_use=true;
157
-		    $this->getOptionIfSet($trap_config,'config','icingaAPI_port', $this->api_port);
158
-		    $this->getOptionIfSet($trap_config,'config','icingaAPI_user', $this->api_username);
159
-		    $this->getOptionIfSet($trap_config,'config','icingaAPI_password', $this->api_password);
156
+			$this->api_use=true;
157
+			$this->getOptionIfSet($trap_config,'config','icingaAPI_port', $this->api_port);
158
+			$this->getOptionIfSet($trap_config,'config','icingaAPI_user', $this->api_username);
159
+			$this->getOptionIfSet($trap_config,'config','icingaAPI_password', $this->api_password);
160 160
 		}
161 161
 	}
162 162
 	
163 163
 	
164 164
 	protected function setupDatabase($trapConfig)
165 165
 	{
166
-	    // Trap database
167
-	    if (!array_key_exists('database',$trapConfig['config']))
168
-        {
169
-            $this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
170
-            return;
171
-        }
172
-        $dbTrapName=$trapConfig['config']['database'];
173
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
166
+		// Trap database
167
+		if (!array_key_exists('database',$trapConfig['config']))
168
+		{
169
+			$this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
170
+			return;
171
+		}
172
+		$dbTrapName=$trapConfig['config']['database'];
173
+		$this->logging->log("Found database in config file: ".$dbTrapName,INFO );
174 174
 	    
175 175
 	   if ( ($dbConfig=parse_ini_file($this->icingaweb2_ressources,true)) === false)
176
-	    {
177
-	        $this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
178
-	        return;
179
-	    }
180
-	    if (!array_key_exists($dbTrapName,$dbConfig))
181
-	    {
182
-	        $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
183
-	        return;
184
-	    }
176
+		{
177
+			$this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
178
+			return;
179
+		}
180
+		if (!array_key_exists($dbTrapName,$dbConfig))
181
+		{
182
+			$this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
183
+			return;
184
+		}
185 185
 	    
186
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName]);
186
+		$this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName]);
187 187
 	    
188
-	    if ($this->api_use === true) return; // In case of API use, no IDO is necessary
188
+		if ($this->api_use === true) return; // In case of API use, no IDO is necessary
189 189
         
190
-	    // IDO Database
191
-	    if (!array_key_exists('IDOdatabase',$trapConfig['config']))
192
-	    {
193
-	        $this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
194
-	    }
195
-	    $dbIdoName=$trapConfig['config']['IDOdatabase'];		
190
+		// IDO Database
191
+		if (!array_key_exists('IDOdatabase',$trapConfig['config']))
192
+		{
193
+			$this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
194
+		}
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))
199
-	    {
200
-	        $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
201
-	        return;
202
-	    }
197
+		$this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
198
+		if (!array_key_exists($dbIdoName,$dbConfig))
199
+		{
200
+			$this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
201
+			return;
202
+		}
203 203
 	    
204
-	    $this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
204
+		$this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
205 205
 	}
206 206
 	
207 207
 	/**
@@ -212,9 +212,9 @@  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
 
@@ -225,10 +225,10 @@  discard block
 block discarded – undo
225 225
 	}
226 226
 	
227 227
 	/** 
228
-	*   Get data from db_config
229
-	*	@param $element string name of param
230
-	*	@return mixed : value (or null)
231
-	*/	
228
+	 *   Get data from db_config
229
+	 *	@param $element string name of param
230
+	 *	@return mixed : value (or null)
231
+	 */	
232 232
 	protected function getDBConfig($element)
233 233
 	{
234 234
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -246,15 +246,15 @@  discard block
 block discarded – undo
246 246
 	}
247 247
 	
248 248
 	/** OBSOLETE Send log. Throws exception on critical error
249
-	*	@param	string $message Message to log
250
-	*	@param	int $level 1=critical 2=warning 3=trace 4=debug
251
-	*	@param  string $destination file/syslog/display
252
-	*	@return void
253
-	**/	
249
+	 *	@param	string $message Message to log
250
+	 *	@param	int $level 1=critical 2=warning 3=trace 4=debug
251
+	 *	@param  string $destination file/syslog/display
252
+	 *	@return void
253
+	 **/	
254 254
 	public function trapLog( $message, $level, $destination ='') // OBSOLETE
255 255
 	{	
256 256
 		// TODO : replace ref with $this->logging->log 
257
-	    $this->logging->log($message, $level, $destination);
257
+		$this->logging->log($message, $level, $destination);
258 258
 	}
259 259
 	
260 260
 	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
@@ -264,19 +264,19 @@  discard block
 block discarded – undo
264 264
 	
265 265
 	protected function getAPI()
266 266
 	{
267
-	    if ($this->icinga2api == null)
268
-	    {
269
-	        $this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
270
-	    }
271
-	    return $this->icinga2api;
267
+		if ($this->icinga2api == null)
268
+		{
269
+			$this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
270
+		}
271
+		return $this->icinga2api;
272 272
 	}
273 273
 	
274 274
 	
275 275
 	/** 
276 276
 	 * read data from stream
277
-	*	@param $stream string input stream, defaults to "php://stdin"
278
-	*	@return mixed array trap data or exception with error
279
-	*/
277
+	 *	@param $stream string input stream, defaults to "php://stdin"
278
+	 *	@return mixed array trap data or exception with error
279
+	 */
280 280
 	public function read_trap($stream='php://stdin')
281 281
 	{
282 282
 		//Read data from snmptrapd from stdin
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
 
285 285
 		if ($input_stream === false)
286 286
 		{
287
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
287
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
288 288
 			$this->logging->log("Error reading stdin !",ERROR,'');
289 289
 			return null; // note : exception thrown by logging
290 290
 		}
@@ -293,21 +293,21 @@  discard block
 block discarded – undo
293 293
 		$this->receivingHost=chop(fgets($input_stream));
294 294
 		if ($this->receivingHost === false)
295 295
 		{
296
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
296
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
297 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
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
303
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
304 304
 			$this->logging->log("Error reading IP !",ERROR,''); 
305 305
 		}
306 306
 		$matches=array();
307 307
 		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
308 308
 		if ($ret_code===0 || $ret_code===false) 
309 309
 		{
310
-		    $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
310
+			$this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
311 311
 			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
312 312
 		} 
313 313
 		else 
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
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
 				}
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 
345 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']);
347
+			$this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
348 348
 			$this->logging->log('no trap oid found',ERROR,'');
349 349
 		} 
350 350
 
@@ -374,9 +374,9 @@  discard block
 block discarded – undo
374 374
 
375 375
 	/** 
376 376
 	 * Translate oid into array(MIB,Name)
377
-	* @param $oid string oid to translate
378
-	* @return mixed : null if not found or array(MIB,Name)
379
-	*/
377
+	 * @param $oid string oid to translate
378
+	 * @return mixed : null if not found or array(MIB,Name)
379
+	 */
380 380
 	public function translateOID($oid)
381 381
 	{
382 382
 		// try from database
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
 		
410 410
 		// Try to get oid name from snmptranslate
411 411
 		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
412
-		    ' '.$oid);
412
+			' '.$oid);
413 413
 		$matches=array();
414 414
 		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
415 415
 		if ($ret_code===0 || $ret_code === false) {
@@ -422,9 +422,9 @@  discard block
 block discarded – undo
422 422
 	
423 423
 	/** 
424 424
 	 * Erase old trap records 
425
-	*	@param integer $days : erase traps when more than $days old
426
-	*	@return integer : number of lines deleted
427
-	**/
425
+	 *	@param integer $days : erase traps when more than $days old
426
+	 *	@return integer : number of lines deleted
427
+	 **/
428 428
 	public function eraseOldTraps($days=0)
429 429
 	{
430 430
 		if ($days==0)
@@ -449,72 +449,72 @@  discard block
 block discarded – undo
449 449
 	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
450 450
 	{
451 451
 	    
452
-	    $db_conn=$this->trapsDB->db_connect_trap();
452
+		$db_conn=$this->trapsDB->db_connect_trap();
453 453
 	    
454
-	    // add date time
455
-	    $insert_col ='date_received,status';
456
-	    $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
454
+		// add date time
455
+		$insert_col ='date_received,status';
456
+		$insert_val = "'" . date("Y-m-d H:i:s")."','error'";
457 457
         
458
-	    if ($sourceIP !=null)
459
-	    {
460
-	        $insert_col .=',source_ip';
461
-	        $insert_val .=",'". $sourceIP ."'";
462
-	    }
463
-	    if ($trapoid !=null)
464
-	    {
465
-	        $insert_col .=',trap_oid';
466
-	        $insert_val .=",'". $trapoid ."'";
467
-	    }
468
-	    $insert_col .=',status_detail';
469
-	    $insert_val .=",'". $message ."'";
458
+		if ($sourceIP !=null)
459
+		{
460
+			$insert_col .=',source_ip';
461
+			$insert_val .=",'". $sourceIP ."'";
462
+		}
463
+		if ($trapoid !=null)
464
+		{
465
+			$insert_col .=',trap_oid';
466
+			$insert_val .=",'". $trapoid ."'";
467
+		}
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
-	    switch ($this->trapsDB->trapDBType)
474
-	    {
475
-	        case 'pgsql':
476
-	            $sql .= ' RETURNING id;';
477
-	            $this->logging->log('sql : '.$sql,INFO);
478
-	            if (($ret_code=$db_conn->query($sql)) === false) {
479
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
480
-	            }
481
-	            $this->logging->log('SQL insertion OK',INFO );
482
-	            // Get last id to insert oid/values in secondary table
483
-	            if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
473
+		switch ($this->trapsDB->trapDBType)
474
+		{
475
+			case 'pgsql':
476
+				$sql .= ' RETURNING id;';
477
+				$this->logging->log('sql : '.$sql,INFO);
478
+				if (($ret_code=$db_conn->query($sql)) === false) {
479
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
480
+				}
481
+				$this->logging->log('SQL insertion OK',INFO );
482
+				// Get last id to insert oid/values in secondary table
483
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
484 484
 	                
485
-	                $this->logging->log('Erreur recuperation id',1,'');
486
-	            }
487
-	            if (! isset($inserted_id_ret['id'])) {
488
-	                $this->logging->log('Error getting id',1,'');
489
-	            }
490
-	            $this->trap_id=$inserted_id_ret['id'];
491
-	            break;
492
-	        case 'mysql':
493
-	            $sql .= ';';
494
-	            $this->logging->log('sql : '.$sql,INFO );
495
-	            if ($db_conn->query($sql) === false) {
496
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
497
-	            }
498
-	            $this->logging->log('SQL insertion OK',INFO );
499
-	            // Get last id to insert oid/values in secondary table
500
-	            $sql='SELECT LAST_INSERT_ID();';
501
-	            if (($ret_code=$db_conn->query($sql)) === false) {
502
-	                $this->logging->log('Erreur recuperation id',1,'');
503
-	            }
485
+					$this->logging->log('Erreur recuperation id',1,'');
486
+				}
487
+				if (! isset($inserted_id_ret['id'])) {
488
+					$this->logging->log('Error getting id',1,'');
489
+				}
490
+				$this->trap_id=$inserted_id_ret['id'];
491
+				break;
492
+			case 'mysql':
493
+				$sql .= ';';
494
+				$this->logging->log('sql : '.$sql,INFO );
495
+				if ($db_conn->query($sql) === false) {
496
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
497
+				}
498
+				$this->logging->log('SQL insertion OK',INFO );
499
+				// Get last id to insert oid/values in secondary table
500
+				$sql='SELECT LAST_INSERT_ID();';
501
+				if (($ret_code=$db_conn->query($sql)) === false) {
502
+					$this->logging->log('Erreur recuperation id',1,'');
503
+				}
504 504
 	            
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");
507
-	            $this->trap_id=$inserted_id;
508
-	            break;
509
-	        default:
510
-	            $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
511
-	    }
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");
507
+				$this->trap_id=$inserted_id;
508
+				break;
509
+			default:
510
+				$this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
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
517
-	*/
517
+	 */
518 518
 	public function writeTrapToDB()
519 519
 	{
520 520
 		
@@ -612,10 +612,10 @@  discard block
 block discarded – undo
612 612
 	}
613 613
 
614 614
 	/** Get rules from rule database with ip and oid
615
-	*	@param $ip string ipv4 or ipv6
616
-	*	@param $oid string oid in numeric
617
-	*	@return mixed : PDO object or false
618
-	*/	
615
+	 *	@param $ip string ipv4 or ipv6
616
+	 *	@param $oid string oid in numeric
617
+	 *	@return mixed : PDO object or false
618
+	 */	
619 619
 	protected function getRules($ip,$oid)
620 620
 	{
621 621
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -674,9 +674,9 @@  discard block
 block discarded – undo
674 674
 	}
675 675
 
676 676
 	/** Add rule match to rule
677
-	*	@param id int : rule id
678
-	*   @param set int : value to set
679
-	*/
677
+	 *	@param id int : rule id
678
+	 *   @param set int : value to set
679
+	 */
680 680
 	protected function add_rule_match($id, $set)
681 681
 	{
682 682
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -693,53 +693,53 @@  discard block
 block discarded – undo
693 693
 	 * @param integer $state numerical staus 
694 694
 	 * @param string $display
695 695
 	 * @returnn bool true is service check was sent without error
696
-	*/
696
+	 */
697 697
 	public function serviceCheckResult($host,$service,$state,$display)
698 698
 	{
699
-	    if ($this->api_use === false)
700
-	    {
701
-    		$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
702
-    			$host.';' .$service .';' . $state . ';'.$display;
703
-    		$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
699
+		if ($this->api_use === false)
700
+		{
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
-    		// 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);
707
-    		return true;
708
-	    }
709
-	    else
710
-	    {
711
-	        $api = $this->getAPI();
712
-	        $api->setCredentials($this->api_username, $this->api_password);
713
-	        list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display);
714
-	        if ($retcode == false)
715
-	        {
716
-	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
717
-	            return false;
718
-	        }
719
-	        else 
720
-	        {
721
-	            $this->logging->log( "Sent result : " .$retmessage,INFO );
722
-	            return true;
723
-	        }
724
-	    }
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);
707
+			return true;
708
+		}
709
+		else
710
+		{
711
+			$api = $this->getAPI();
712
+			$api->setCredentials($this->api_username, $this->api_password);
713
+			list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display);
714
+			if ($retcode == false)
715
+			{
716
+				$this->logging->log( "Error sending result : " .$retmessage,WARN,'');
717
+				return false;
718
+			}
719
+			else 
720
+			{
721
+				$this->logging->log( "Sent result : " .$retmessage,INFO );
722
+				return true;
723
+			}
724
+		}
725 725
 	}
726 726
 	
727 727
 	public function getHostByIP($ip)
728 728
 	{
729
-	    $api = $this->getAPI();
730
-	    $api->setCredentials($this->api_username, $this->api_password);
731
-	    return $api->getHostByIP($ip);
729
+		$api = $this->getAPI();
730
+		$api->setCredentials($this->api_username, $this->api_password);
731
+		return $api->getHostByIP($ip);
732 732
 	}
733 733
 	
734 734
 	/** Resolve display. 
735
-	*	Changes OID(<oid>) to value if found or text "<not in trap>"
736
-	*	@param $display string
737
-	*	@return string display
738
-	*/
735
+	 *	Changes OID(<oid>) to value if found or text "<not in trap>"
736
+	 *	@param $display string
737
+	 *	@return string display
738
+	 */
739 739
 	protected function applyDisplay($display)
740 740
 	{
741
-	    $matches=array();
742
-	    while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
741
+		$matches=array();
742
+		while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
743 743
 		{
744 744
 			$oid=$matches[1];
745 745
 			$found=0;
@@ -799,11 +799,11 @@  discard block
 block discarded – undo
799 799
 		
800 800
 		if ($rule[$item] == '(')
801 801
 		{ // grouping
802
-		    $item++;
802
+			$item++;
803 803
 			$start=$item;
804 804
 			$parenthesis_count=0; 
805 805
 			while (($item < strlen($rule)) // Not end of string AND
806
-			      && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
806
+				  && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
807 807
 			{ 
808 808
 				if ($rule[$item] == '"' )
809 809
 				{ // pass through string
@@ -811,14 +811,14 @@  discard block
 block discarded – undo
811 811
 					$item=$this->eval_getNext($rule,$item,'"');
812 812
 				} 
813 813
 				else{
814
-				    if ($rule[$item] == '(')
815
-				    {
816
-				        $parenthesis_count++;
817
-				    }
818
-				    if ($rule[$item] == ')')
819
-				    {
820
-				        $parenthesis_count--;
821
-				    }
814
+					if ($rule[$item] == '(')
815
+					{
816
+						$parenthesis_count++;
817
+					}
818
+					if ($rule[$item] == ')')
819
+					{
820
+						$parenthesis_count--;
821
+					}
822 822
 					$item++;
823 823
 				}
824 824
 			}
@@ -870,24 +870,24 @@  discard block
 block discarded – undo
870 870
 	}
871 871
 	
872 872
 	/** Evaluation : makes token and evaluate. 
873
-	*	Public function for expressions testing
874
-	*	accepts : < > = <= >= !=  (typec = 0)
875
-	*	operators : & | (typec=1)
876
-	*	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
877
-	*   comparison int vs strings will return null (error)
878
-	*	return : bool or null on error
879
-	*/
873
+	 *	Public function for expressions testing
874
+	 *	accepts : < > = <= >= !=  (typec = 0)
875
+	 *	operators : & | (typec=1)
876
+	 *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
877
+	 *   comparison int vs strings will return null (error)
878
+	 *	return : bool or null on error
879
+	 */
880 880
 	public function evaluation($rule,&$item)
881 881
 	{
882
-	    //echo "Evaluation of ".substr($rule,$item)."\n";
882
+		//echo "Evaluation of ".substr($rule,$item)."\n";
883 883
 		if ( $rule[$item] == '!') // If '!' found, negate next expression.
884 884
 		{
885
-		    $negate=true;
886
-		    $item++;
885
+			$negate=true;
886
+			$item++;
887 887
 		}
888 888
 		else
889 889
 		{
890
-		    $negate=false;
890
+			$negate=false;
891 891
 		}
892 892
 		// First element : number, string or ()
893 893
 		list($type1,$val1) = $this->eval_getElement($rule,$item);
@@ -907,24 +907,24 @@  discard block
 block discarded – undo
907 907
 		// Third element : number, string or ()
908 908
 		if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
909 909
 		{
910
-		    $item++;
911
-		    if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
912
-		    $val2= ! $this->evaluation($rule,$item);
913
-		    $type2=2; // result is a boolean 
910
+			$item++;
911
+			if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
912
+			$val2= ! $this->evaluation($rule,$item);
913
+			$type2=2; // result is a boolean 
914 914
 		}
915 915
 		else 
916 916
 		{
917
-		    list($type2,$val2) = $this->eval_getElement($rule,$item);
917
+			list($type2,$val2) = $this->eval_getElement($rule,$item);
918 918
 		}
919 919
 		//echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
920 920
 		
921 921
 		if ($type1!=$type2)  // cannot compare different types
922 922
 		{ 
923
-		    throw new Exception("Cannot compare string & number : ".$rule);
923
+			throw new Exception("Cannot compare string & number : ".$rule);
924 924
 		}
925 925
 		if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
926 926
 		{
927
-		    throw new Exception("Cannot use boolean operators with string & number : ".$rule);
927
+			throw new Exception("Cannot use boolean operators with string & number : ".$rule);
928 928
 		}
929 929
 		
930 930
 		switch ($comp){
@@ -982,9 +982,9 @@  discard block
 block discarded – undo
982 982
 	}		
983 983
 	
984 984
 	/** Evaluation rule (uses eval_* functions recursively)
985
-	*	@param $rule string rule ( _OID(.1.3.6.1.4.1.8072.2.3.2.1)=_OID(.1.3.6.1.2.1.1.3.0) )
986
-	*	@return bool : true : rule match, false : rule don't match , throw exception on error.
987
-	*/
985
+	 *	@param $rule string rule ( _OID(.1.3.6.1.4.1.8072.2.3.2.1)=_OID(.1.3.6.1.2.1.1.3.0) )
986
+	 *	@return bool : true : rule match, false : rule don't match , throw exception on error.
987
+	 */
988 988
 	
989 989
 	protected function eval_rule($rule)
990 990
 	{
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
 			}
1030 1030
 			if ($found==0)
1031 1031
 			{	// OID not found : throw error
1032
-			    throw new Exception('OID '.$oid.' not found in trap');
1032
+				throw new Exception('OID '.$oid.' not found in trap');
1033 1033
 			}
1034 1034
 		}
1035 1035
 		$item=0;
@@ -1040,7 +1040,7 @@  discard block
 block discarded – undo
1040 1040
 	}
1041 1041
 	
1042 1042
 	/** Match rules for current trap and do action
1043
-	*/
1043
+	 */
1044 1044
 	public function applyRules()
1045 1045
 	{
1046 1046
 		$rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
@@ -1077,12 +1077,12 @@  discard block
 block discarded – undo
1077 1077
 					{
1078 1078
 						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
1079 1079
 						{
1080
-						    $this->trap_action.='Error sending status : check cmd/API';
1080
+							$this->trap_action.='Error sending status : check cmd/API';
1081 1081
 						}
1082 1082
 						else
1083 1083
 						{
1084
-						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
1085
-						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1084
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
1085
+							$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1086 1086
 						}
1087 1087
 					}
1088 1088
 					else
@@ -1099,15 +1099,15 @@  discard block
 block discarded – undo
1099 1099
 					$this->logging->log('action NOK : '.$action,INFO );
1100 1100
 					if ($action >= 0)
1101 1101
 					{
1102
-					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
1103
-					    {
1104
-					        $this->trap_action.='Error sending status : check cmd/API';
1105
-					    }
1106
-					    else
1107
-					    {
1108
-    						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1109
-    						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1110
-					    }
1102
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
1103
+						{
1104
+							$this->trap_action.='Error sending status : check cmd/API';
1105
+						}
1106
+						else
1107
+						{
1108
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
1109
+							$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1110
+						}
1111 1111
 					}
1112 1112
 					else
1113 1113
 					{
@@ -1130,9 +1130,9 @@  discard block
 block discarded – undo
1130 1130
 			}
1131 1131
 			catch (Exception $e) 
1132 1132
 			{ 
1133
-			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
1134
-			    $this->trap_action.=' ERR : '.$e->getMessage();
1135
-			    $this->trap_data['status']='error';
1133
+				$this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
1134
+				$this->trap_action.=' ERR : '.$e->getMessage();
1135
+				$this->trap_data['status']='error';
1136 1136
 			}
1137 1137
 			
1138 1138
 		}
@@ -1147,8 +1147,8 @@  discard block
 block discarded – undo
1147 1147
 	}
1148 1148
 
1149 1149
 	/** Add Time a action to rule
1150
-	*	@param string $time : time to process to insert in SQL
1151
-	*/
1150
+	 *	@param string $time : time to process to insert in SQL
1151
+	 */
1152 1152
 	public function add_rule_final($time)
1153 1153
 	{
1154 1154
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -1165,9 +1165,9 @@  discard block
 block discarded – undo
1165 1165
 	/*********** UTILITIES *********************/
1166 1166
 	
1167 1167
 	/** Create database schema 
1168
-	*	@param $schema_file	string File to read schema from
1169
-	*	@param $table_prefix string to replace #PREFIX# in schema file by this
1170
-	*/
1168
+	 *	@param $schema_file	string File to read schema from
1169
+	 *	@param $table_prefix string to replace #PREFIX# in schema file by this
1170
+	 */
1171 1171
 	public function create_schema($schema_file,$table_prefix)
1172 1172
 	{
1173 1173
 		//Read data from snmptrapd from stdin
@@ -1187,30 +1187,30 @@  discard block
 block discarded – undo
1187 1187
 		{
1188 1188
 			$newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
1189 1189
 			if (preg_match('/; *$/', $newline)) 
1190
-            {
1191
-                $sql= $newline;
1192
-                if ($db_conn->query($sql) === false) {
1193
-                    $this->logging->log('Error create schema : '.$sql,ERROR,'');
1194
-                }
1195
-                if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
1196
-                {
1197
-                    $cur_table='table '.$cur_table_array[1];
1198
-                }
1199
-                else
1200
-                {
1201
-                    $cur_table='secret SQL stuff :-)';
1202
-                }
1203
-                $this->logging->log('Creating : ' . $cur_table,INFO );
1204
-                $newline='';
1205
-            }
1190
+			{
1191
+				$sql= $newline;
1192
+				if ($db_conn->query($sql) === false) {
1193
+					$this->logging->log('Error create schema : '.$sql,ERROR,'');
1194
+				}
1195
+				if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
1196
+				{
1197
+					$cur_table='table '.$cur_table_array[1];
1198
+				}
1199
+				else
1200
+				{
1201
+					$cur_table='secret SQL stuff :-)';
1202
+				}
1203
+				$this->logging->log('Creating : ' . $cur_table,INFO );
1204
+				$newline='';
1205
+			}
1206 1206
 		}
1207 1207
 		
1208 1208
 		$sql= $newline;
1209 1209
 		if ($sql != '')
1210 1210
 		{
1211
-    		if ($db_conn->query($sql) === false) {
1212
-    			$this->logging->log('Error create schema : '.$sql,ERROR,'');
1213
-    		}
1211
+			if ($db_conn->query($sql) === false) {
1212
+				$this->logging->log('Error create schema : '.$sql,ERROR,'');
1213
+			}
1214 1214
 		}
1215 1215
 		$this->logging->log('Schema created',INFO);		
1216 1216
 	}
@@ -1225,113 +1225,113 @@  discard block
 block discarded – undo
1225 1225
 	 */
1226 1226
 	public function update_schema($prefix,$target_version,$table_prefix,$getmsg=false)
1227 1227
 	{
1228
-	    // Get current db number
1229
-	    $db_conn=$this->trapsDB->db_connect_trap();
1230
-	    $sql='SELECT id,value from '.$this->db_prefix.'db_config WHERE name=\'db_version\' ';
1231
-	    $this->logging->log('SQL query : '.$sql,DEBUG );
1232
-	    if (($ret_code=$db_conn->query($sql)) === false) {
1233
-	        $this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
1234
-	        return;
1235
-	    }
1236
-	    $version=$ret_code->fetchAll();
1237
-	    $cur_version=$version[0]['value'];
1238
-	    $db_version_id=$version[0]['id'];
1228
+		// Get current db number
1229
+		$db_conn=$this->trapsDB->db_connect_trap();
1230
+		$sql='SELECT id,value from '.$this->db_prefix.'db_config WHERE name=\'db_version\' ';
1231
+		$this->logging->log('SQL query : '.$sql,DEBUG );
1232
+		if (($ret_code=$db_conn->query($sql)) === false) {
1233
+			$this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
1234
+			return;
1235
+		}
1236
+		$version=$ret_code->fetchAll();
1237
+		$cur_version=$version[0]['value'];
1238
+		$db_version_id=$version[0]['id'];
1239 1239
 	    
1240
-	    if ($this->trapsDB->trapDBType == 'pgsql')
1241
-	    {
1242
-	        $prefix .= 'update_pgsql/schema_';
1243
-	    }
1244
-	    else
1245
-	    {
1246
-	        $prefix .= 'update_sql/schema_';
1247
-	    }
1248
-	    //echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
1249
-	    if ($getmsg === true)
1250
-	    {
1251
-	        $message='';
1252
-	        $this->logging->log('getting message for upgrade',DEBUG );
1253
-	        while($cur_version<$target_version)
1254
-	        {
1255
-	            $cur_version++;
1256
-	            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
1257
-	            $input_stream=fopen($updateFile, 'r');
1258
-	            if ($input_stream=== false)
1259
-	            {
1260
-	                $this->logging->log("Error reading update file ". $updateFile,2,'');
1261
-	                return;
1262
-	            }
1263
-	            do { $line=fgets($input_stream); }
1264
-	            while ($line !== false && !preg_match('/#MESSAGE/',$line));
1265
-	            if ($line === false)
1266
-	            {
1267
-	                $this->logging->log("No message in file ". $updateFile,2,'');
1268
-	                return;
1269
-	            }
1270
-	            $message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
1271
-	        }
1272
-	        return $message;
1273
-	    }
1274
-	    while($cur_version<$target_version)
1275
-	    { // tODO : execute pre & post scripts
1276
-	       $cur_version++;
1277
-	       $this->logging->log('Updating to version : ' .$cur_version ,INFO );
1278
-	       $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
1279
-	       $input_stream=fopen($updateFile, 'r');
1280
-	       if ($input_stream=== false)
1281
-	       {
1282
-	           $this->logging->log("Error reading update file ". $updateFile,2,'');
1283
-	           return;
1284
-	       }
1285
-	       $newline='';
1286
-	       $db_conn=$this->trapsDB->db_connect_trap();
1287
-	       $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
1288
-	       while (($line=fgets($input_stream)) !== false)
1289
-	       {
1290
-	           if (preg_match('/^#/', $line)) continue; // ignore comment lines
1291
-	           $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
1292
-	           if (preg_match('/; *$/', $newline))
1293
-	           {
1294
-	               $sql_req=$db_conn->prepare($newline);
1295
-	               if ($sql_req->execute() === false) {
1296
-	                   $this->logging->log('Error create schema : '.$newline,1,'');
1297
-	               }
1298
-	               $cur_table_array=array();
1299
-	               if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
1300
-	               {
1301
-	                   $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
1302
-	               }
1303
-	               else
1304
-	               {
1305
-	                   $cur_table='secret SQL stuff :-)';
1306
-	                   //$cur_table=$newline;
1307
-	               }
1308
-	               $this->logging->log('Doing : ' . $cur_table,INFO );
1240
+		if ($this->trapsDB->trapDBType == 'pgsql')
1241
+		{
1242
+			$prefix .= 'update_pgsql/schema_';
1243
+		}
1244
+		else
1245
+		{
1246
+			$prefix .= 'update_sql/schema_';
1247
+		}
1248
+		//echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
1249
+		if ($getmsg === true)
1250
+		{
1251
+			$message='';
1252
+			$this->logging->log('getting message for upgrade',DEBUG );
1253
+			while($cur_version<$target_version)
1254
+			{
1255
+				$cur_version++;
1256
+				$updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
1257
+				$input_stream=fopen($updateFile, 'r');
1258
+				if ($input_stream=== false)
1259
+				{
1260
+					$this->logging->log("Error reading update file ". $updateFile,2,'');
1261
+					return;
1262
+				}
1263
+				do { $line=fgets($input_stream); }
1264
+				while ($line !== false && !preg_match('/#MESSAGE/',$line));
1265
+				if ($line === false)
1266
+				{
1267
+					$this->logging->log("No message in file ". $updateFile,2,'');
1268
+					return;
1269
+				}
1270
+				$message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
1271
+			}
1272
+			return $message;
1273
+		}
1274
+		while($cur_version<$target_version)
1275
+		{ // tODO : execute pre & post scripts
1276
+		   $cur_version++;
1277
+		   $this->logging->log('Updating to version : ' .$cur_version ,INFO );
1278
+		   $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
1279
+		   $input_stream=fopen($updateFile, 'r');
1280
+		   if ($input_stream=== false)
1281
+		   {
1282
+			   $this->logging->log("Error reading update file ". $updateFile,2,'');
1283
+			   return;
1284
+		   }
1285
+		   $newline='';
1286
+		   $db_conn=$this->trapsDB->db_connect_trap();
1287
+		   $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
1288
+		   while (($line=fgets($input_stream)) !== false)
1289
+		   {
1290
+			   if (preg_match('/^#/', $line)) continue; // ignore comment lines
1291
+			   $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
1292
+			   if (preg_match('/; *$/', $newline))
1293
+			   {
1294
+				   $sql_req=$db_conn->prepare($newline);
1295
+				   if ($sql_req->execute() === false) {
1296
+					   $this->logging->log('Error create schema : '.$newline,1,'');
1297
+				   }
1298
+				   $cur_table_array=array();
1299
+				   if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
1300
+				   {
1301
+					   $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
1302
+				   }
1303
+				   else
1304
+				   {
1305
+					   $cur_table='secret SQL stuff :-)';
1306
+					   //$cur_table=$newline;
1307
+				   }
1308
+				   $this->logging->log('Doing : ' . $cur_table,INFO );
1309 1309
 	               
1310
-	               $newline='';
1311
-	           }
1312
-	       }
1313
-	       fclose($input_stream);
1310
+				   $newline='';
1311
+			   }
1312
+		   }
1313
+		   fclose($input_stream);
1314 1314
 	       
1315
-	       //$sql= $newline;
1316
-	       //if ($db_conn->query($sql) === false) {
1317
-	       //    $this->logging->log('Error updating schema : '.$sql,1,'');
1318
-	       //}
1315
+		   //$sql= $newline;
1316
+		   //if ($db_conn->query($sql) === false) {
1317
+		   //    $this->logging->log('Error updating schema : '.$sql,1,'');
1318
+		   //}
1319 1319
 	       
1320
-	       $sql='UPDATE '.$this->db_prefix.'db_config SET value='.$cur_version.' WHERE ( id = '.$db_version_id.' )';
1321
-	       $this->logging->log('SQL query : '.$sql,DEBUG );
1322
-	       if ($db_conn->query($sql) === false) {
1323
-	           $this->logging->log('Cannot update db version. Query : ' . $sql,2);
1324
-	           return;
1325
-	       }
1320
+		   $sql='UPDATE '.$this->db_prefix.'db_config SET value='.$cur_version.' WHERE ( id = '.$db_version_id.' )';
1321
+		   $this->logging->log('SQL query : '.$sql,DEBUG );
1322
+		   if ($db_conn->query($sql) === false) {
1323
+			   $this->logging->log('Cannot update db version. Query : ' . $sql,2);
1324
+			   return;
1325
+		   }
1326 1326
 	       
1327
-	       $this->logging->log('Schema updated to version : '.$cur_version ,INFO);
1328
-	    }
1327
+		   $this->logging->log('Schema updated to version : '.$cur_version ,INFO);
1328
+		}
1329 1329
 	}
1330 1330
 	
1331 1331
 	/** reset service to OK after time defined in rule
1332
-	*	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better 
1333
-	*	@return : like a plugin : status code (0->3) <message> | <perfdata>
1334
-	**/
1332
+	 *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better 
1333
+	 *	@return : like a plugin : status code (0->3) <message> | <perfdata>
1334
+	 **/
1335 1335
 	public function reset_services()
1336 1336
 	{
1337 1337
 		// Get all services not in 'ok' state
@@ -1401,105 +1401,105 @@  discard block
 block discarded – undo
1401 1401
 		$description=$db_conn->quote($description);
1402 1402
 		if (isset($this->dbOidIndex[$oid]))
1403 1403
 		{
1404
-		    if ($this->dbOidIndex[$oid]['key'] == -1)
1405
-		    { // newly created.
1406
-		        return 0;
1407
-		    }
1404
+			if ($this->dbOidIndex[$oid]['key'] == -1)
1405
+			{ // newly created.
1406
+				return 0;
1407
+			}
1408 1408
 			if ( $name != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['name'] ||
1409
-			    $mib != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['mib'] ||
1410
-			    $type != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['type'] //||
1411
-			    //$textConv != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['textual_convention'] //||
1412
-			    //$dispHint != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['display_hint'] ||
1413
-			    //$syntax != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['syntax'] ||
1414
-			    //$type_enum != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['type_enum'] ||
1415
-			    //$description != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['description']
1416
-			    )
1409
+				$mib != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['mib'] ||
1410
+				$type != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['type'] //||
1411
+				//$textConv != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['textual_convention'] //||
1412
+				//$dispHint != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['display_hint'] ||
1413
+				//$syntax != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['syntax'] ||
1414
+				//$type_enum != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['type_enum'] ||
1415
+				//$description != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['description']
1416
+				)
1417 1417
 			{ // Do update
1418
-			    $sql='UPDATE '.$this->db_prefix.'mib_cache SET '.
1419
- 			    'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'. 
1420
- 			    ', syntax = :syntax, type_enum = :type_enum, description = :description '.
1421
- 			    ' WHERE id= :id';
1422
-			    $sqlQuery=$db_conn->prepare($sql);
1418
+				$sql='UPDATE '.$this->db_prefix.'mib_cache SET '.
1419
+ 				'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'. 
1420
+ 				', syntax = :syntax, type_enum = :type_enum, description = :description '.
1421
+ 				' WHERE id= :id';
1422
+				$sqlQuery=$db_conn->prepare($sql);
1423 1423
 			    
1424
-			    $sqlParam=array(
1425
-			        ':name' => $name,
1426
-			        ':type' => $type, 
1427
-			        ':mib' => $mib, 
1428
-			        ':tc' =>  ($textConv==null)?'null':$textConv , 
1429
-			        ':display_hint' => ($dispHint==null)?'null':$dispHint ,
1430
-			        ':syntax' => ($syntax==null)?'null':$syntax,
1431
-			        ':type_enum' => ($type_enum==null)?'null':$type_enum, 
1432
-			        ':description' => ($description==null)?'null':$description,
1433
-			        ':id' => $this->dbOidAll[$this->dbOidIndex[$oid]['id']]
1434
-			    );
1424
+				$sqlParam=array(
1425
+					':name' => $name,
1426
+					':type' => $type, 
1427
+					':mib' => $mib, 
1428
+					':tc' =>  ($textConv==null)?'null':$textConv , 
1429
+					':display_hint' => ($dispHint==null)?'null':$dispHint ,
1430
+					':syntax' => ($syntax==null)?'null':$syntax,
1431
+					':type_enum' => ($type_enum==null)?'null':$type_enum, 
1432
+					':description' => ($description==null)?'null':$description,
1433
+					':id' => $this->dbOidAll[$this->dbOidIndex[$oid]['id']]
1434
+				);
1435 1435
 			    
1436
-			    if ($sqlQuery->execute($sqlParam) === false) {
1437
-			        $this->logging->log('Error in query : ' . $sql,ERROR,'');
1438
-			    }
1439
-			    $this->logging->log('Trap updated : '.$name . ' / OID : '.$oid,DEBUG );
1436
+				if ($sqlQuery->execute($sqlParam) === false) {
1437
+					$this->logging->log('Error in query : ' . $sql,ERROR,'');
1438
+				}
1439
+				$this->logging->log('Trap updated : '.$name . ' / OID : '.$oid,DEBUG );
1440 1440
 				return 1;
1441 1441
 			}
1442 1442
 			else
1443 1443
 			{
1444
-			    $this->logging->log('Trap unchanged : '.$name . ' / OID : '.$oid,DEBUG );
1445
-			    return 0;
1444
+				$this->logging->log('Trap unchanged : '.$name . ' / OID : '.$oid,DEBUG );
1445
+				return 0;
1446 1446
 			}
1447 1447
 		}
1448
-        // create new OID.
1448
+		// create new OID.
1449 1449
 			
1450 1450
 		// Insert data
1451 1451
 
1452 1452
 		$sql='INSERT INTO '.$this->db_prefix.'mib_cache '.
1453
-		      '(oid, name, type , mib, textual_convention, display_hint '.
1454
-              ', syntax, type_enum , description ) ' . 
1455
-              'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
1456
-              ', :syntax, :type_enum, :description )';
1453
+			  '(oid, name, type , mib, textual_convention, display_hint '.
1454
+			  ', syntax, type_enum , description ) ' . 
1455
+			  'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
1456
+			  ', :syntax, :type_enum, :description )';
1457 1457
         
1458 1458
 		if ($this->trapsDB->trapDBType == 'pgsql') $sql .= 'RETURNING id';
1459 1459
 		
1460 1460
 		$sqlQuery=$db_conn->prepare($sql);
1461 1461
 		
1462 1462
 		$sqlParam=array(
1463
-		    ':oid' => $oid,
1464
-		    ':name' => $name,
1465
-		    ':type' => $type,
1466
-		    ':mib' => $mib,
1467
-		    ':tc' =>  ($textConv==null)?'null':$textConv ,
1468
-		    ':display_hint' => ($dispHint==null)?'null':$dispHint ,
1469
-		    ':syntax' => ($syntax==null)?'null':$syntax,
1470
-		    ':type_enum' => ($type_enum==null)?'null':$type_enum,
1471
-		    ':description' => ($description==null)?'null':$description
1463
+			':oid' => $oid,
1464
+			':name' => $name,
1465
+			':type' => $type,
1466
+			':mib' => $mib,
1467
+			':tc' =>  ($textConv==null)?'null':$textConv ,
1468
+			':display_hint' => ($dispHint==null)?'null':$dispHint ,
1469
+			':syntax' => ($syntax==null)?'null':$syntax,
1470
+			':type_enum' => ($type_enum==null)?'null':$type_enum,
1471
+			':description' => ($description==null)?'null':$description
1472 1472
 		);
1473 1473
 		
1474 1474
 		if ($sqlQuery->execute($sqlParam) === false) {
1475
-		    $this->logging->log('Error in query : ' . $sql,1,'');
1475
+			$this->logging->log('Error in query : ' . $sql,1,'');
1476 1476
 		}
1477 1477
 		
1478 1478
 		switch ($this->trapsDB->trapDBType)
1479 1479
 		{
1480
-		    case 'pgsql':
1481
-		        // Get last id to insert oid/values in secondary table
1482
-		        if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {		            
1483
-		            $this->logging->log('Error getting id - pgsql - ',1,'');
1484
-		        }
1485
-		        if (! isset($inserted_id_ret['id'])) {
1486
-		            $this->logging->log('Error getting id - pgsql - empty.',1,'');
1487
-		        }
1488
-		        $this->dbOidIndex[$oid]['id']=$inserted_id_ret['id'];
1489
-		        break;
1490
-		    case 'mysql':
1491
-		        // Get last id to insert oid/values in secondary table
1492
-		        $sql='SELECT LAST_INSERT_ID();';
1493
-		        if (($ret_code=$db_conn->query($sql)) === false) {
1494
-		            $this->logging->log('Erreur getting id - mysql - ',1,'');
1495
-		        }
1480
+			case 'pgsql':
1481
+				// Get last id to insert oid/values in secondary table
1482
+				if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {		            
1483
+					$this->logging->log('Error getting id - pgsql - ',1,'');
1484
+				}
1485
+				if (! isset($inserted_id_ret['id'])) {
1486
+					$this->logging->log('Error getting id - pgsql - empty.',1,'');
1487
+				}
1488
+				$this->dbOidIndex[$oid]['id']=$inserted_id_ret['id'];
1489
+				break;
1490
+			case 'mysql':
1491
+				// Get last id to insert oid/values in secondary table
1492
+				$sql='SELECT LAST_INSERT_ID();';
1493
+				if (($ret_code=$db_conn->query($sql)) === false) {
1494
+					$this->logging->log('Erreur getting id - mysql - ',1,'');
1495
+				}
1496 1496
 		        
1497
-		        $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
1498
-		        if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
1499
-		        $this->dbOidIndex[$oid]['id']=$inserted_id;
1500
-		        break;
1501
-		    default:
1502
-		        $this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType,1,'');
1497
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
1498
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
1499
+				$this->dbOidIndex[$oid]['id']=$inserted_id;
1500
+				break;
1501
+			default:
1502
+				$this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType,1,'');
1503 1503
 		}
1504 1504
 
1505 1505
 		// Set as newly created.
@@ -1507,148 +1507,148 @@  discard block
 block discarded – undo
1507 1507
 		return 2;
1508 1508
 	}
1509 1509
 
1510
-    /**
1511
-     * create or update (with check_existing = true) objects of trap
1512
-     * @param string $trapOID : trap oid
1513
-     * @param string $trapmib : mib of trap
1514
-     * @param array $objects : array of objects name (without MIB)
1515
-     * @param bool $check_existing : check instead of create
1516
-     */
1510
+	/**
1511
+	 * create or update (with check_existing = true) objects of trap
1512
+	 * @param string $trapOID : trap oid
1513
+	 * @param string $trapmib : mib of trap
1514
+	 * @param array $objects : array of objects name (without MIB)
1515
+	 * @param bool $check_existing : check instead of create
1516
+	 */
1517 1517
 	public function trap_objects($trapOID,$trapmib,$objects,$check_existing)
1518 1518
 	{
1519
-	    $dbObjects=null; // cache of objects for trap in db
1520
-	    $db_conn=$this->trapsDB->db_connect_trap();
1519
+		$dbObjects=null; // cache of objects for trap in db
1520
+		$db_conn=$this->trapsDB->db_connect_trap();
1521 1521
 	    
1522
-	    // Get id of trapmib.
1522
+		// Get id of trapmib.
1523 1523
 
1524
-	    $trapId = $this->dbOidIndex[$trapOID]['id'];
1525
-	    if ($check_existing === true)
1526
-	    {
1527
-	        // Get all objects
1528
-	        $sql='SELECT * FROM '.$this->db_prefix.'mib_cache_trap_object where trap_id='.$trapId.';';
1529
-	        $this->logging->log('SQL query get all traps: '.$sql,DEBUG );
1530
-	        if (($ret_code=$db_conn->query($sql)) === false) {
1531
-	            $this->logging->log('No result in query : ' . $sql,1,'');
1532
-	        }
1533
-	        $dbObjectsRaw=$ret_code->fetchAll();
1524
+		$trapId = $this->dbOidIndex[$trapOID]['id'];
1525
+		if ($check_existing === true)
1526
+		{
1527
+			// Get all objects
1528
+			$sql='SELECT * FROM '.$this->db_prefix.'mib_cache_trap_object where trap_id='.$trapId.';';
1529
+			$this->logging->log('SQL query get all traps: '.$sql,DEBUG );
1530
+			if (($ret_code=$db_conn->query($sql)) === false) {
1531
+				$this->logging->log('No result in query : ' . $sql,1,'');
1532
+			}
1533
+			$dbObjectsRaw=$ret_code->fetchAll();
1534 1534
 	        
1535
-	        foreach ($dbObjectsRaw as $val)
1536
-	        {
1537
-	            $dbObjects[$val['object_id']]=1;
1538
-	        }
1539
-	    }
1540
-	    foreach ($objects as $object)
1541
-	    {
1542
-	        $match=$snmptrans=array();
1543
-	        $retVal=0;
1544
-	        $objOid=$objTc=$objDispHint=$objSyntax=$objDesc=$objEnum=NULL;
1545
-	        $tmpdesc='';$indesc=false;
1535
+			foreach ($dbObjectsRaw as $val)
1536
+			{
1537
+				$dbObjects[$val['object_id']]=1;
1538
+			}
1539
+		}
1540
+		foreach ($objects as $object)
1541
+		{
1542
+			$match=$snmptrans=array();
1543
+			$retVal=0;
1544
+			$objOid=$objTc=$objDispHint=$objSyntax=$objDesc=$objEnum=NULL;
1545
+			$tmpdesc='';$indesc=false;
1546 1546
 	        
1547
-	        $objMib=$trapmib;
1548
-	        exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1549
-	            ' -On -Td '.$objMib.'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
1550
-	        if ($retVal!=0)
1551
-	        {
1552
-	            // Maybe not trap mib, search with IR
1553
-	            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1554
-	                ' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
1555
-	            if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
1556
-	            { // Not found -> continue with warning
1557
-	               $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
1558
-	               continue;
1559
-	            }
1560
-	            $objMib=$match[1];
1547
+			$objMib=$trapmib;
1548
+			exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1549
+				' -On -Td '.$objMib.'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
1550
+			if ($retVal!=0)
1551
+			{
1552
+				// Maybe not trap mib, search with IR
1553
+				exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1554
+					' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
1555
+				if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
1556
+				{ // Not found -> continue with warning
1557
+				   $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
1558
+				   continue;
1559
+				}
1560
+				$objMib=$match[1];
1561 1561
 	            
1562
-	            // Do the snmptranslate again.
1563
-	            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1564
-	                ' -On -Td '.$objMib.'::'.$object,$snmptrans,$retVal);
1565
-	            if ($retVal!=0) {
1566
-	                $this->logging->log('Error finding trap object : '.$objMib.'::'.$object,2,'');
1567
-	            }
1562
+				// Do the snmptranslate again.
1563
+				exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1564
+					' -On -Td '.$objMib.'::'.$object,$snmptrans,$retVal);
1565
+				if ($retVal!=0) {
1566
+					$this->logging->log('Error finding trap object : '.$objMib.'::'.$object,2,'');
1567
+				}
1568 1568
 	            
1569
-	        }
1570
-	        foreach ($snmptrans as $line)
1571
-	        {
1572
-	            if ($indesc===true)
1573
-	            {
1574
-	                $line=preg_replace('/[\t ]+/',' ',$line);
1575
-	                if (preg_match('/(.*)"$/', $line,$match))
1576
-	                {
1577
-	                    $objDesc = $tmpdesc . $match[1];
1578
-	                    $indesc=false;
1579
-	                }
1580
-	                $tmpdesc.=$line;
1581
-	                continue;
1582
-	            }
1583
-	            if (preg_match('/^\.[0-9\.]+$/', $line))
1584
-	            {
1585
-	                $objOid=$line;
1586
-	                continue;
1587
-	            }
1588
-	            if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
1589
-	            {
1590
-	                $objSyntax=$match[1];
1591
-                    $objEnum=$match[2];
1592
-	                continue;
1593
-	            }
1594
-	            if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
1595
-	            {
1596
-	                $objSyntax=$match[1];
1597
-	                continue;
1598
-	            }
1599
-	            if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
1600
-	            {
1601
-	                $objDispHint=$match[1];
1602
-	                continue;
1603
-	            }
1604
-	            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
1605
-	            {
1606
-	                $objDesc=$match[1];
1607
-	                continue;
1608
-	            }
1609
-	            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
1610
-	            {
1611
-	                $tmpdesc=$match[1];
1612
-	                $indesc=true;
1613
-	                continue;
1614
-	            }
1615
-	            if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
1616
-	            {
1617
-	                $objTc=$match[1];
1618
-	                continue;
1619
-	            }
1620
-	        }
1621
-	        $this->logging->log("Adding trap $object : $objOid / $objSyntax / $objEnum / $objDispHint / $objTc",DEBUG );
1622
-	        //echo "$object : $objOid / $objSyntax / $objEnum / $objDispHint / $objTc / $objDesc\n";
1623
-	        // Update 
1624
-	        $this->update_oid($objOid, $objMib, $object, '3', $objTc, $objDispHint, $objSyntax, $objEnum,$objDesc);
1569
+			}
1570
+			foreach ($snmptrans as $line)
1571
+			{
1572
+				if ($indesc===true)
1573
+				{
1574
+					$line=preg_replace('/[\t ]+/',' ',$line);
1575
+					if (preg_match('/(.*)"$/', $line,$match))
1576
+					{
1577
+						$objDesc = $tmpdesc . $match[1];
1578
+						$indesc=false;
1579
+					}
1580
+					$tmpdesc.=$line;
1581
+					continue;
1582
+				}
1583
+				if (preg_match('/^\.[0-9\.]+$/', $line))
1584
+				{
1585
+					$objOid=$line;
1586
+					continue;
1587
+				}
1588
+				if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
1589
+				{
1590
+					$objSyntax=$match[1];
1591
+					$objEnum=$match[2];
1592
+					continue;
1593
+				}
1594
+				if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
1595
+				{
1596
+					$objSyntax=$match[1];
1597
+					continue;
1598
+				}
1599
+				if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
1600
+				{
1601
+					$objDispHint=$match[1];
1602
+					continue;
1603
+				}
1604
+				if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
1605
+				{
1606
+					$objDesc=$match[1];
1607
+					continue;
1608
+				}
1609
+				if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
1610
+				{
1611
+					$tmpdesc=$match[1];
1612
+					$indesc=true;
1613
+					continue;
1614
+				}
1615
+				if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
1616
+				{
1617
+					$objTc=$match[1];
1618
+					continue;
1619
+				}
1620
+			}
1621
+			$this->logging->log("Adding trap $object : $objOid / $objSyntax / $objEnum / $objDispHint / $objTc",DEBUG );
1622
+			//echo "$object : $objOid / $objSyntax / $objEnum / $objDispHint / $objTc / $objDesc\n";
1623
+			// Update 
1624
+			$this->update_oid($objOid, $objMib, $object, '3', $objTc, $objDispHint, $objSyntax, $objEnum,$objDesc);
1625 1625
             
1626
-	        if (isset($dbObjects[$this->dbOidIndex[$objOid]['id']]))
1627
-	        {   // if link exists, continue
1628
-	            $dbObjects[$this->dbOidIndex[$objOid]['id']]=2;
1629
-	            continue;
1630
-	        }
1631
-	        if ($check_existing === true) 
1632
-	        {
1633
-	            // TODO : check link trap - objects exists, mark them.
1634
-	        }
1635
-	        // Associate in object table
1636
-	        $sql='INSERT INTO '.$this->db_prefix.'mib_cache_trap_object (trap_id,object_id) '.
1637
-	   	        'values (:trap_id, :object_id)';	        
1638
-	        $sqlQuery=$db_conn->prepare($sql);	        
1639
-	        $sqlParam=array(
1640
-	            ':trap_id' => $trapId,
1641
-	            ':object_id' => $this->dbOidIndex[$objOid]['id'],
1642
-	        );
1626
+			if (isset($dbObjects[$this->dbOidIndex[$objOid]['id']]))
1627
+			{   // if link exists, continue
1628
+				$dbObjects[$this->dbOidIndex[$objOid]['id']]=2;
1629
+				continue;
1630
+			}
1631
+			if ($check_existing === true) 
1632
+			{
1633
+				// TODO : check link trap - objects exists, mark them.
1634
+			}
1635
+			// Associate in object table
1636
+			$sql='INSERT INTO '.$this->db_prefix.'mib_cache_trap_object (trap_id,object_id) '.
1637
+	   			'values (:trap_id, :object_id)';	        
1638
+			$sqlQuery=$db_conn->prepare($sql);	        
1639
+			$sqlParam=array(
1640
+				':trap_id' => $trapId,
1641
+				':object_id' => $this->dbOidIndex[$objOid]['id'],
1642
+			);
1643 1643
 	        
1644
-	        if ($sqlQuery->execute($sqlParam) === false) {
1645
-	            $this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$objOid]['id'] ,1,'');
1646
-	        }
1647
-	    }
1648
-	    if ($check_existing === true)
1649
-	    {
1650
-	        // TODO : remove link trap - objects that wasn't marked.
1651
-	    }
1644
+			if ($sqlQuery->execute($sqlParam) === false) {
1645
+				$this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$objOid]['id'] ,1,'');
1646
+			}
1647
+		}
1648
+		if ($check_existing === true)
1649
+		{
1650
+			// TODO : remove link trap - objects that wasn't marked.
1651
+		}
1652 1652
 	    
1653 1653
 	}
1654 1654
 	
@@ -1658,7 +1658,7 @@  discard block
 block discarded – undo
1658 1658
 	 * @param boolean $check_change : Force check of trap params & objects
1659 1659
 	 * @param boolean $onlyTraps : only cache traps and objects (true) or all (false)
1660 1660
 	 * @param string $startOID : only cache under startOID (NOT IMPLEMENTED)
1661
-	*/	
1661
+	 */	
1662 1662
 	public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,$startOID='.1')
1663 1663
 	{
1664 1664
 		// Timing 
@@ -1710,7 +1710,7 @@  discard block
 block discarded – undo
1710 1710
 		
1711 1711
 		for ($curElement=0;$curElement < $numElements;$curElement++)
1712 1712
 		{
1713
-		    $time_1= microtime(true);
1713
+			$time_1= microtime(true);
1714 1714
 			if ((microtime(true)-$timeFiveSec) > 2 && $display_progress)
1715 1715
 			{ // echo a . every 2 sec
1716 1716
 				echo '.';
@@ -1728,8 +1728,8 @@  discard block
 block discarded – undo
1728 1728
 			// Get oid or pass if not found
1729 1729
 			if (!preg_match('/^\.[0-9\.]+$/',$this->objectsAll[$curElement]))
1730 1730
 			{
1731
-			    $time_parse1 += microtime(true) - $time_1;
1732
-			    $time_parse1N ++;
1731
+				$time_parse1 += microtime(true) - $time_1;
1732
+				$time_parse1N ++;
1733 1733
 				continue;
1734 1734
 			}
1735 1735
 			$oid=$this->objectsAll[$curElement];
@@ -1740,7 +1740,7 @@  discard block
 block discarded – undo
1740 1740
 			if (!preg_match('/ +([^\(]+)\(.+\) type=([0-9]+)( tc=([0-9]+))?( hint=(.+))?/',
1741 1741
 						$this->objectsAll[$curElement],$match))
1742 1742
 			{
1743
-			    $time_check1 += microtime(true) - $time_1;
1743
+				$time_check1 += microtime(true) - $time_1;
1744 1744
 				$time_check1N++;
1745 1745
 				continue;
1746 1746
 			}
@@ -1753,8 +1753,8 @@  discard block
 block discarded – undo
1753 1753
 				// Check if next is suboid -> in that case is cannot be a trap
1754 1754
 				if (preg_match("/^$oid/",$this->objectsAll[$curElement+1]))
1755 1755
 				{
1756
-				    $time_check2 += microtime(true) - $time_1;
1757
-				    $time_check2N++;
1756
+					$time_check2 += microtime(true) - $time_1;
1757
+					$time_check2N++;
1758 1758
 					continue;
1759 1759
 				}		
1760 1760
 				unset($snmptrans);
@@ -1762,8 +1762,8 @@  discard block
 block discarded – undo
1762 1762
 					' -Td '.$oid . ' | grep OBJECTS ',$snmptrans,$retVal);
1763 1763
 				if ($retVal!=0)
1764 1764
 				{
1765
-				    $time_check2 += microtime(true) - $time_1;
1766
-				    $time_check2N++;
1765
+					$time_check2 += microtime(true) - $time_1;
1766
+					$time_check2N++;
1767 1767
 					continue;
1768 1768
 				}
1769 1769
 				//echo "\n v1 trap found : $oid \n";
@@ -1772,7 +1772,7 @@  discard block
 block discarded – undo
1772 1772
 			}
1773 1773
 			if ($onlyTraps===true && $type!=21) // if only traps and not a trap, continue
1774 1774
 			{
1775
-			    $time_check3 += microtime(true) - $time_1;
1775
+				$time_check3 += microtime(true) - $time_1;
1776 1776
 				$time_check3N++;
1777 1777
 				continue;
1778 1778
 			}
@@ -1793,7 +1793,7 @@  discard block
 block discarded – undo
1793 1793
 			
1794 1794
 			if (!preg_match('/^(.*)::/',$snmptrans[0],$match))
1795 1795
 			{
1796
-			    $this->logging->log('Error getting mib from trap '.$oid.' : ' . $snmptrans[0],1,'');
1796
+				$this->logging->log('Error getting mib from trap '.$oid.' : ' . $snmptrans[0],1,'');
1797 1797
 			}
1798 1798
 			$trapMib=$match[1];
1799 1799
 			
@@ -1801,17 +1801,17 @@  discard block
 block discarded – undo
1801 1801
 			while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
1802 1802
 			if (isset($snmptrans[$numLine]))
1803 1803
 			{
1804
-			    $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
1804
+				$snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
1805 1805
 
1806
-			    while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
1807
-			    {
1808
-			        $trapDesc.=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
1809
-			        $numLine++;
1810
-			    }
1811
-			    if (isset($snmptrans[$numLine])) {
1812
-			        $trapDesc.=preg_replace('/".*/','',$snmptrans[$numLine]);
1813
-			        $trapDesc=preg_replace('/[\t ]+/',' ',$trapDesc);
1814
-			    }
1806
+				while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
1807
+				{
1808
+					$trapDesc.=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
1809
+					$numLine++;
1810
+				}
1811
+				if (isset($snmptrans[$numLine])) {
1812
+					$trapDesc.=preg_replace('/".*/','',$snmptrans[$numLine]);
1813
+					$trapDesc=preg_replace('/[\t ]+/',' ',$trapDesc);
1814
+				}
1815 1815
 
1816 1816
 			}
1817 1817
 			$update=$this->update_oid($oid,$trapMib,$name,$type,NULL,NULL,NULL,NULL,$trapDesc);
@@ -1819,23 +1819,23 @@  discard block
 block discarded – undo
1819 1819
 			
1820 1820
 			if (($update==0) && ($check_change===false))
1821 1821
 			{ // Trapd didn't change & force check disabled
1822
-			    $time_objects += microtime(true) - $time_1;
1823
-			    if ($display_progress) echo "C";
1824
-			    continue;
1822
+				$time_objects += microtime(true) - $time_1;
1823
+				if ($display_progress) echo "C";
1824
+				continue;
1825 1825
 			}
1826 1826
 			
1827 1827
 			$synt=null;
1828 1828
 			foreach ($snmptrans as $line)
1829 1829
 			{	
1830
-    			if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
1831
-    				{
1832
-    					$synt=$match[1];
1833
-    				}
1830
+				if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
1831
+					{
1832
+						$synt=$match[1];
1833
+					}
1834 1834
 			}
1835 1835
 			if ($synt == null) 
1836 1836
 			{
1837 1837
 				//echo "No objects for $trapOID\n";
1838
-			    $time_objects += microtime(true) - $time_1;
1838
+				$time_objects += microtime(true) - $time_1;
1839 1839
 				continue;
1840 1840
 			}
1841 1841
 			//echo "$synt \n";
@@ -1854,18 +1854,18 @@  discard block
 block discarded – undo
1854 1854
 		
1855 1855
 		if ($display_progress)
1856 1856
 		{
1857
-    		echo "\nNumber of processed traps : $time_num_traps \n";
1858
-    		echo "\nParsing : " . number_format($time_parse1+$time_check1,1) ." sec / " . ($time_parse1N+ $time_check1N)  . " occurences\n";
1859
-    		echo "Detecting traps : " . number_format($time_check2+$time_check3,1) . " sec / " . ($time_check2N+$time_check3N) ." occurences\n";
1860
-    		echo "Trap processing ($time_updateN): ".number_format($time_update,1)." sec , ";
1861
-    		echo "Objects processing ($time_objectsN) : ".number_format($time_objects,1)." sec \n";
1857
+			echo "\nNumber of processed traps : $time_num_traps \n";
1858
+			echo "\nParsing : " . number_format($time_parse1+$time_check1,1) ." sec / " . ($time_parse1N+ $time_check1N)  . " occurences\n";
1859
+			echo "Detecting traps : " . number_format($time_check2+$time_check3,1) . " sec / " . ($time_check2N+$time_check3N) ." occurences\n";
1860
+			echo "Trap processing ($time_updateN): ".number_format($time_update,1)." sec , ";
1861
+			echo "Objects processing ($time_objectsN) : ".number_format($time_objects,1)." sec \n";
1862 1862
 		}
1863 1863
 		
1864 1864
 		// Timing ends
1865 1865
 		$timeTaken=microtime(true) - $timeTaken;
1866 1866
 		if ($display_progress)
1867 1867
 		{
1868
-		    echo "Global time : ".round($timeTaken)." seconds\n";
1868
+			echo "Global time : ".round($timeTaken)." seconds\n";
1869 1869
 		}
1870 1870
 		
1871 1871
 	}
Please login to merge, or discard this patch.
Spacing   +417 added lines, -417 removed lines patch added patch discarded remove patch
@@ -32,8 +32,8 @@  discard block
 block discarded – undo
32 32
 	protected $api_password='';
33 33
 
34 34
 	// Logs 
35
-	protected $logging;    //< Logging class.
36
-	protected $logSetup;   //< bool true if log was setup in constructor
35
+	protected $logging; //< Logging class.
36
+	protected $logSetup; //< bool true if log was setup in constructor
37 37
 	
38 38
 	//protected $debug_file="php://stdout";	
39 39
 	// Databases
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 	private $objectsAll; //< output lines of snmptranslate list
59 59
 	private $trapObjectsIndex; //< array of traps objects (as OID)
60 60
 	
61
-	function __construct($etc_dir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
61
+	function __construct($etc_dir='/etc/icingaweb2', $baseLogLevel=null, $baseLogMode='syslog', $baseLogFile='')
62 62
 	{
63 63
 	    // Paths of ini files
64 64
 		$this->icingaweb2_etc=$etc_dir;
@@ -66,10 +66,10 @@  discard block
 block discarded – undo
66 66
 		$this->icingaweb2_ressources=$this->icingaweb2_etc."/resources.ini";
67 67
 
68 68
 		// Setup logging
69
-		$this->logging = new Logging();
69
+		$this->logging=new Logging();
70 70
 		if ($baseLogLevel != null)
71 71
 		{
72
-		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
72
+		    $this->logging->setLogging($baseLogLevel, $baseLogMode, $baseLogFile);
73 73
 		    $this->logSetup=true;
74 74
 		}
75 75
 		else 
@@ -77,10 +77,10 @@  discard block
 block discarded – undo
77 77
 		$this->logging->log('Loggin started', INFO);
78 78
 
79 79
 		// Get options from ini files
80
-		$trapConfig=parse_ini_file($this->trap_module_config,true);
80
+		$trapConfig=parse_ini_file($this->trap_module_config, true);
81 81
 		if ($trapConfig == false)
82 82
 		{
83
-		    $this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
83
+		    $this->logging->log("Error reading ini file : ".$this->trap_module_config, ERROR, 'syslog');
84 84
 		}
85 85
 		$this->getMainOptions($trapConfig); // Get main options from ini file
86 86
 		$this->setupDatabase($trapConfig); // Setup database class
@@ -108,15 +108,15 @@  discard block
 block discarded – undo
108 108
 	 * @param string $message warning message if not found
109 109
 	 * @return boolean true if found, or false
110 110
 	 */
111
-	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
111
+	protected function getOptionIfSet($option_array, $option_category, $option_name, &$option_var, $log_level=2, $message=null)
112 112
 	{
113 113
 	    if (!isset($option_array[$option_category][$option_name]))
114 114
 	    {
115 115
 	        if ($message === null)
116 116
 	        {
117
-	            $message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
117
+	            $message='No '.$option_name.' in config file: '.$this->trap_module_config;
118 118
 	        }
119
-	        $this->logging->log($message,$log_level,'syslog');
119
+	        $this->logging->log($message, $log_level, 'syslog');
120 120
 	        return false;
121 121
 	    }
122 122
 	    else
@@ -133,30 +133,30 @@  discard block
 block discarded – undo
133 133
 	*/
134 134
 	protected function getMainOptions($trap_config)
135 135
 	{
136
-		$trap_config=parse_ini_file($this->trap_module_config,true);
136
+		$trap_config=parse_ini_file($this->trap_module_config, true);
137 137
 		if ($trap_config == false) 
138 138
 		{
139
-			$this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog'); 
139
+			$this->logging->log("Error reading ini file : ".$this->trap_module_config, ERROR, 'syslog'); 
140 140
 		}
141 141
 		// Snmptranslate binary path
142
-		$this->getOptionIfSet($trap_config,'config','snmptranslate', $this->snmptranslate);
142
+		$this->getOptionIfSet($trap_config, 'config', 'snmptranslate', $this->snmptranslate);
143 143
 
144 144
 		// mibs path
145
-		$this->getOptionIfSet($trap_config,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
145
+		$this->getOptionIfSet($trap_config, 'config', 'snmptranslate_dirs', $this->snmptranslate_dirs);
146 146
 
147 147
 		// icinga2cmd path
148
-		$this->getOptionIfSet($trap_config,'config','icingacmd', $this->icinga2cmd);
148
+		$this->getOptionIfSet($trap_config, 'config', 'icingacmd', $this->icinga2cmd);
149 149
 		
150 150
 		// table prefix
151
-		$this->getOptionIfSet($trap_config,'config','database_prefix', $this->db_prefix);
151
+		$this->getOptionIfSet($trap_config, 'config', 'database_prefix', $this->db_prefix);
152 152
 
153 153
 		// API options
154
-		if ($this->getOptionIfSet($trap_config,'config','icingaAPI_host', $this->api_hostname))
154
+		if ($this->getOptionIfSet($trap_config, 'config', 'icingaAPI_host', $this->api_hostname))
155 155
 		{
156 156
 		    $this->api_use=true;
157
-		    $this->getOptionIfSet($trap_config,'config','icingaAPI_port', $this->api_port);
158
-		    $this->getOptionIfSet($trap_config,'config','icingaAPI_user', $this->api_username);
159
-		    $this->getOptionIfSet($trap_config,'config','icingaAPI_password', $this->api_password);
157
+		    $this->getOptionIfSet($trap_config, 'config', 'icingaAPI_port', $this->api_port);
158
+		    $this->getOptionIfSet($trap_config, 'config', 'icingaAPI_user', $this->api_username);
159
+		    $this->getOptionIfSet($trap_config, 'config', 'icingaAPI_password', $this->api_password);
160 160
 		}
161 161
 	}
162 162
 	
@@ -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]);
186
+        $this->trapsDB=new Database($this->logging, $dbConfig[$dbTrapName]);
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 (($ret_code=$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
 			}
@@ -774,27 +774,27 @@  discard block
 block discarded – undo
774 774
 
775 775
 	
776 776
 	/***************** Eval & tokenizer functions ****************/
777
-	protected function eval_getElement($rule,&$item)
777
+	protected function eval_getElement($rule, &$item)
778 778
 	{
779
-		while ($rule[$item]==' ') $item++;
780
-		if (preg_match('/[0-9\.]/',$rule[$item]))
779
+		while ($rule[$item] == ' ') $item++;
780
+		if (preg_match('/[0-9\.]/', $rule[$item]))
781 781
 		{ // number
782 782
 	
783
-			$item2=$item+1; 
784
-			while (($item2!=strlen($rule)) && (preg_match('/[0-9\.]/',$rule[$item2]))) { $item2++ ;}
785
-			$val=substr($rule,$item,$item2-$item);
783
+			$item2=$item + 1; 
784
+			while (($item2 != strlen($rule)) && (preg_match('/[0-9\.]/', $rule[$item2]))) { $item2++; }
785
+			$val=substr($rule, $item, $item2 - $item);
786 786
 			$item=$item2;
787 787
 			//echo "number ".$val."\n";
788
-			return array(0,$val);
788
+			return array(0, $val);
789 789
 		}
790 790
 		if ($rule[$item] == '"')
791 791
 		{ // string
792 792
 			$item++;
793
-			$item2=$this->eval_getNext($rule,$item,'"');
794
-			$val=substr($rule,$item,$item2-$item-1);
793
+			$item2=$this->eval_getNext($rule, $item, '"');
794
+			$val=substr($rule, $item, $item2 - $item - 1);
795 795
 			$item=$item2;
796 796
 			//echo "string : ".$val."\n";
797
-			return array(1,$val);
797
+			return array(1, $val);
798 798
 		}
799 799
 		
800 800
 		if ($rule[$item] == '(')
@@ -803,14 +803,14 @@  discard block
 block discarded – undo
803 803
 			$start=$item;
804 804
 			$parenthesis_count=0; 
805 805
 			while (($item < strlen($rule)) // Not end of string AND
806
-			      && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
806
+			      && (($rule[$item] != ')') || $parenthesis_count > 0)) // Closing ')' or embeded ()
807 807
 			{ 
808
-				if ($rule[$item] == '"' )
808
+				if ($rule[$item] == '"')
809 809
 				{ // pass through string
810 810
 					$item++;
811
-					$item=$this->eval_getNext($rule,$item,'"');
811
+					$item=$this->eval_getNext($rule, $item, '"');
812 812
 				} 
813
-				else{
813
+				else {
814 814
 				    if ($rule[$item] == '(')
815 815
 				    {
816 816
 				        $parenthesis_count++;
@@ -823,49 +823,49 @@  discard block
 block discarded – undo
823 823
 				}
824 824
 			}
825 825
 			
826
-			if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
827
-			$val=substr($rule,$start,$item-$start);
826
+			if ($item == strlen($rule)) {throw new Exception("no closing () in ".$rule." at ".$item); }
827
+			$val=substr($rule, $start, $item - $start);
828 828
 			$item++;
829 829
 			$start=0;
830 830
 			//echo "group : ".$val."\n";
831 831
 			// returns evaluation of group as type 2 (boolean)
832
-			return array(2,$this->evaluation($val,$start));		
832
+			return array(2, $this->evaluation($val, $start));		
833 833
 		}
834
-		throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
834
+		throw new Exception("number/string not found in ".$rule." at ".$item.' : '.$rule[$item]);
835 835
 		
836 836
 	}
837 837
 	
838
-	protected function eval_getNext($rule,$item,$tok)
838
+	protected function eval_getNext($rule, $item, $tok)
839 839
 	{
840
-		while (($rule[$item] != $tok ) && ($item < strlen($rule))) { $item++;}
841
-		if ($item==strlen($rule)) throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
842
-		return $item+1;
840
+		while (($rule[$item] != $tok) && ($item < strlen($rule))) { $item++; }
841
+		if ($item == strlen($rule)) throw new Exception("closing '".$tok."' not found in ".$rule." at ".$item);
842
+		return $item + 1;
843 843
 	}
844 844
 	
845
-	protected function eval_getOper($rule,&$item)
845
+	protected function eval_getOper($rule, &$item)
846 846
 	{
847
-		while ($rule[$item]==' ') $item++;
847
+		while ($rule[$item] == ' ') $item++;
848 848
 		switch ($rule[$item])
849 849
 		{
850 850
 			case '<':
851
-				if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
852
-				$item++; return array(0,"<");
851
+				if ($rule[$item + 1] == '=') { $item+=2; return array(0, "<="); }
852
+				$item++; return array(0, "<");
853 853
 			case '>':
854
-				if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
855
-				$item++; return array(0,">");
854
+				if ($rule[$item + 1] == '=') { $item+=2; return array(0, ">="); }
855
+				$item++; return array(0, ">");
856 856
 			case '=':
857
-				$item++; return array(0,"=");	
857
+				$item++; return array(0, "=");	
858 858
 			case '!':
859
-				if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
860
-				throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
859
+				if ($rule[$item + 1] == '=') { $item+=2; return array(0, "!="); }
860
+				throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule." at ".$item);
861 861
 			case '~':
862
-				$item++; return array(0,"~");	
862
+				$item++; return array(0, "~");	
863 863
 			case '|':
864
-				$item++; return array(1,"|");	
864
+				$item++; return array(1, "|");	
865 865
 			case '&':
866
-				$item++; return array(1,"&");
866
+				$item++; return array(1, "&");
867 867
 			default	:
868
-				throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
868
+				throw new Exception("Erreur in expr - operator not found in ".$rule." at ".$item);
869 869
 		}
870 870
 	}
871 871
 	
@@ -877,10 +877,10 @@  discard block
 block discarded – undo
877 877
 	*   comparison int vs strings will return null (error)
878 878
 	*	return : bool or null on error
879 879
 	*/
880
-	public function evaluation($rule,&$item)
880
+	public function evaluation($rule, &$item)
881 881
 	{
882 882
 	    //echo "Evaluation of ".substr($rule,$item)."\n";
883
-		if ( $rule[$item] == '!') // If '!' found, negate next expression.
883
+		if ($rule[$item] == '!') // If '!' found, negate next expression.
884 884
 		{
885 885
 		    $negate=true;
886 886
 		    $item++;
@@ -890,63 +890,63 @@  discard block
 block discarded – undo
890 890
 		    $negate=false;
891 891
 		}
892 892
 		// First element : number, string or ()
893
-		list($type1,$val1) = $this->eval_getElement($rule,$item);
893
+		list($type1, $val1)=$this->eval_getElement($rule, $item);
894 894
 		//echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
895 895
 		
896
-		if ($item==strlen($rule)) // If only element, return value, but only boolean
896
+		if ($item == strlen($rule)) // If only element, return value, but only boolean
897 897
 		{
898 898
 		  if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
899
-		  if ($negate === true) $val1= ! $val1;
899
+		  if ($negate === true) $val1=!$val1;
900 900
 		  return $val1;
901 901
 		}  
902 902
 		
903 903
 		// Second element : operator
904
-		list($typec,$comp) = $this->eval_getOper($rule,$item);
904
+		list($typec, $comp)=$this->eval_getOper($rule, $item);
905 905
 		//echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
906 906
         
907 907
 		// Third element : number, string or ()
908
-		if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
908
+		if ($rule[$item] == '!') // starts with a ! so evaluate whats next
909 909
 		{
910 910
 		    $item++;
911 911
 		    if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
912
-		    $val2= ! $this->evaluation($rule,$item);
912
+		    $val2=!$this->evaluation($rule, $item);
913 913
 		    $type2=2; // result is a boolean 
914 914
 		}
915 915
 		else 
916 916
 		{
917
-		    list($type2,$val2) = $this->eval_getElement($rule,$item);
917
+		    list($type2, $val2)=$this->eval_getElement($rule, $item);
918 918
 		}
919 919
 		//echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
920 920
 		
921
-		if ($type1!=$type2)  // cannot compare different types
921
+		if ($type1 != $type2)  // cannot compare different types
922 922
 		{ 
923 923
 		    throw new Exception("Cannot compare string & number : ".$rule);
924 924
 		}
925
-		if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
925
+		if ($typec == 1 && $type1 != 2) // cannot use & or | with string/number
926 926
 		{
927 927
 		    throw new Exception("Cannot use boolean operators with string & number : ".$rule);
928 928
 		}
929 929
 		
930
-		switch ($comp){
931
-			case '<':	$retVal= ($val1 < $val2); break;
932
-			case '<=':	$retVal= ($val1 <= $val2); break;
933
-			case '>':	$retVal= ($val1 > $val2); break;
934
-			case '>=':	$retVal= ($val1 >= $val2); break;
935
-			case '=':	$retVal= ($val1 == $val2); break;
936
-			case '!=':	$retVal= ($val1 != $val2); break;
937
-			case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
938
-			case '|':	$retVal= ($val1 || $val2); break;
939
-			case '&':	$retVal= ($val1 && $val2); break;
930
+		switch ($comp) {
931
+			case '<':	$retVal=($val1 < $val2); break;
932
+			case '<=':	$retVal=($val1 <= $val2); break;
933
+			case '>':	$retVal=($val1 > $val2); break;
934
+			case '>=':	$retVal=($val1 >= $val2); break;
935
+			case '=':	$retVal=($val1 == $val2); break;
936
+			case '!=':	$retVal=($val1 != $val2); break;
937
+			case '~':	$retVal=(preg_match('/'.preg_replace('/"/', '', $val2).'/', $val1)); break;
938
+			case '|':	$retVal=($val1 || $val2); break;
939
+			case '&':	$retVal=($val1 && $val2); break;
940 940
 			default:  throw new Exception("Error in expression - unknown comp : ".$comp);
941 941
 		}
942
-		if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
942
+		if ($negate === true) $retVal=!$retVal; // Inverse result if negate before expression
943 943
 		
944
-		if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
944
+		if ($item == strlen($rule)) return $retVal; // End of string : return evaluation
945 945
 		// check for logical operator :
946 946
 		switch ($rule[$item])
947 947
 		{
948
-			case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
949
-			case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
948
+			case '|':	$item++; return ($retVal || $this->evaluation($rule, $item));
949
+			case '&':	$item++; return ($retVal && $this->evaluation($rule, $item));
950 950
 			
951 951
 			default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
952 952
 		}
@@ -958,17 +958,17 @@  discard block
 block discarded – undo
958 958
 		$rule2='';
959 959
 		while ($item < strlen($rule))
960 960
 		{
961
-			if ($rule[$item]==' ') { $item++; continue; }
962
-			if ($rule[$item]=='"')
961
+			if ($rule[$item] == ' ') { $item++; continue; }
962
+			if ($rule[$item] == '"')
963 963
 			{
964 964
 				$rule2.=$rule[$item];
965 965
 				$item++;
966
-				while (($rule[$item]!='"') && ($item < strlen($rule)))
966
+				while (($rule[$item] != '"') && ($item < strlen($rule)))
967 967
 				{
968 968
 					$rule2.=$rule[$item];
969 969
 					$item++;
970 970
 				}
971
-				if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
971
+				if ($item == strlen($rule)) throw new Exception("closing '\"' not found in ".$rule." at ".$item);
972 972
 				$rule2.=$rule[$item];
973 973
 				$item++;
974 974
 				continue;
@@ -988,12 +988,12 @@  discard block
 block discarded – undo
988 988
 	
989 989
 	protected function eval_rule($rule)
990 990
 	{
991
-		if ($rule==null || $rule == '') // Empty rule is always true
991
+		if ($rule == null || $rule == '') // Empty rule is always true
992 992
 		{
993 993
 			return true;
994 994
 		}
995 995
 		$matches=array();
996
-		while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
996
+		while (preg_match('/_OID\(([0-9\.\*]+)\)/', $rule, $matches) == 1)
997 997
 		{
998 998
 			$oid=$matches[1];
999 999
 			$found=0;
@@ -1005,49 +1005,49 @@  discard block
 block discarded – undo
1005 1005
 			// replace * with \* in oid for preg_replace
1006 1006
 			$oid=preg_replace('/\*/', '\*', $oid);
1007 1007
 			
1008
-			$this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
1008
+			$this->logging->log('OID in rule : '.$oid.' / '.$oidR, DEBUG);
1009 1009
 			
1010
-			foreach($this->trap_data_ext as $val)
1010
+			foreach ($this->trap_data_ext as $val)
1011 1011
 			{
1012
-				if (preg_match("/^$oidR$/",$val->oid) == 1)
1012
+				if (preg_match("/^$oidR$/", $val->oid) == 1)
1013 1013
 				{
1014
-					if (!preg_match('/^[0-9]*\.?[0-9]+$/',$val->value))
1014
+					if (!preg_match('/^[0-9]*\.?[0-9]+$/', $val->value))
1015 1015
 					{ // If not a number, change " to ' and put " around it
1016
-						$val->value=preg_replace('/"/',"'",$val->value);
1016
+						$val->value=preg_replace('/"/', "'", $val->value);
1017 1017
 						$val->value='"'.$val->value.'"';
1018 1018
 					}
1019 1019
 					$rep=0;
1020
-					$rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
1021
-					if ($rep==0)
1020
+					$rule=preg_replace('/_OID\('.$oid.'\)/', $val->value, $rule, -1, $rep);
1021
+					if ($rep == 0)
1022 1022
 					{
1023
-						$this->logging->log("Error in rule_eval",WARN,'');
1023
+						$this->logging->log("Error in rule_eval", WARN, '');
1024 1024
 						return false;
1025 1025
 					}
1026 1026
 					$found=1;
1027 1027
 					break;
1028 1028
 				}
1029 1029
 			}
1030
-			if ($found==0)
1030
+			if ($found == 0)
1031 1031
 			{	// OID not found : throw error
1032 1032
 			    throw new Exception('OID '.$oid.' not found in trap');
1033 1033
 			}
1034 1034
 		}
1035 1035
 		$item=0;
1036 1036
 		$rule=$this->eval_cleanup($rule);
1037
-		$this->logging->log('Rule after clenup: '.$rule,INFO );
1037
+		$this->logging->log('Rule after clenup: '.$rule, INFO);
1038 1038
 		
1039
-		return  $this->evaluation($rule,$item);
1039
+		return  $this->evaluation($rule, $item);
1040 1040
 	}
1041 1041
 	
1042 1042
 	/** Match rules for current trap and do action
1043 1043
 	*/
1044 1044
 	public function applyRules()
1045 1045
 	{
1046
-		$rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
1046
+		$rules=$this->getRules($this->trap_data['source_ip'], $this->trap_data['trap_oid']);
1047 1047
 		
1048
-		if ($rules===false || count($rules)==0)
1048
+		if ($rules === false || count($rules) == 0)
1049 1049
 		{
1050
-			$this->logging->log('No rules found for this trap',INFO );
1050
+			$this->logging->log('No rules found for this trap', INFO);
1051 1051
 			$this->trap_data['status']='unknown';
1052 1052
 			$this->trap_to_db=true;
1053 1053
 			return;
@@ -1062,58 +1062,58 @@  discard block
 block discarded – undo
1062 1062
 			$service_name=$rule['service_name'];
1063 1063
 			
1064 1064
 			$display=$this->applyDisplay($rule['display']);
1065
-			$this->trap_action = ($this->trap_action==null)? '' : $this->trap_action . ', ';
1065
+			$this->trap_action=($this->trap_action == null) ? '' : $this->trap_action.', ';
1066 1066
 			try
1067 1067
 			{
1068
-				$this->logging->log('Rule to eval : '.$rule['rule'],INFO );
1068
+				$this->logging->log('Rule to eval : '.$rule['rule'], INFO);
1069 1069
 				$evalr=$this->eval_rule($rule['rule']);
1070 1070
 				
1071 1071
 				if ($evalr == true)
1072 1072
 				{
1073 1073
 					//$this->logging->log('rules OOK: '.print_r($rule),INFO );
1074 1074
 					$action=$rule['action_match'];
1075
-					$this->logging->log('action OK : '.$action,INFO );
1075
+					$this->logging->log('action OK : '.$action, INFO);
1076 1076
 					if ($action >= 0)
1077 1077
 					{
1078
-						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
1078
+						if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
1079 1079
 						{
1080 1080
 						    $this->trap_action.='Error sending status : check cmd/API';
1081 1081
 						}
1082 1082
 						else
1083 1083
 						{
1084
-						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
1084
+						    $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
1085 1085
 						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1086 1086
 						}
1087 1087
 					}
1088 1088
 					else
1089 1089
 					{
1090
-						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1090
+						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
1091 1091
 					}
1092
-					$this->trap_to_db=($action==-2)?false:true;
1092
+					$this->trap_to_db=($action == -2) ?false:true;
1093 1093
 				}
1094 1094
 				else
1095 1095
 				{
1096 1096
 					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
1097 1097
 					
1098 1098
 					$action=$rule['action_nomatch'];
1099
-					$this->logging->log('action NOK : '.$action,INFO );
1099
+					$this->logging->log('action NOK : '.$action, INFO);
1100 1100
 					if ($action >= 0)
1101 1101
 					{
1102
-					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
1102
+					    if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
1103 1103
 					    {
1104 1104
 					        $this->trap_action.='Error sending status : check cmd/API';
1105 1105
 					    }
1106 1106
 					    else
1107 1107
 					    {
1108
-    						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1108
+    						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
1109 1109
     						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1110 1110
 					    }
1111 1111
 					}
1112 1112
 					else
1113 1113
 					{
1114
-						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1114
+						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
1115 1115
 					}
1116
-					$this->trap_to_db=($action==-2)?false:true;					
1116
+					$this->trap_to_db=($action == -2) ?false:true;					
1117 1117
 				}
1118 1118
 				// Put name in source_name
1119 1119
 				if (!isset($this->trap_data['source_name']))
@@ -1122,7 +1122,7 @@  discard block
 block discarded – undo
1122 1122
 				}
1123 1123
 				else
1124 1124
 				{
1125
-					if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
1125
+					if (!preg_match('/'.$rule['host_name'].'/', $this->trap_data['source_name']))
1126 1126
 					{ // only add if not present
1127 1127
 						$this->trap_data['source_name'].=','.$rule['host_name'];
1128 1128
 					}
@@ -1130,13 +1130,13 @@  discard block
 block discarded – undo
1130 1130
 			}
1131 1131
 			catch (Exception $e) 
1132 1132
 			{ 
1133
-			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
1133
+			    $this->logging->log('Error in rule eval : '.$e->getMessage(), WARN, '');
1134 1134
 			    $this->trap_action.=' ERR : '.$e->getMessage();
1135 1135
 			    $this->trap_data['status']='error';
1136 1136
 			}
1137 1137
 			
1138 1138
 		}
1139
-		if ($this->trap_data['status']=='error')
1139
+		if ($this->trap_data['status'] == 'error')
1140 1140
 		{
1141 1141
 		  $this->trap_to_db=true; // Always put errors in DB for the use can see
1142 1142
 		}
@@ -1152,13 +1152,13 @@  discard block
 block discarded – undo
1152 1152
 	public function add_rule_final($time)
1153 1153
 	{
1154 1154
 		$db_conn=$this->trapsDB->db_connect_trap();
1155
-		if ($this->trap_action==null) 
1155
+		if ($this->trap_action == null) 
1156 1156
 		{
1157 1157
 			$this->trap_action='No action';
1158 1158
 		}
1159 1159
 		$sql="UPDATE ".$this->db_prefix."received SET process_time = '".$time."' , status_detail='".$this->trap_action."'  WHERE (id = '".$this->trap_id."');";
1160 1160
 		if ($db_conn->query($sql) === false) {
1161
-			$this->logging->log('Error in update query : ' . $sql,WARN,'');
1161
+			$this->logging->log('Error in update query : '.$sql, WARN, '');
1162 1162
 		}
1163 1163
 	}
1164 1164
 	
@@ -1168,14 +1168,14 @@  discard block
 block discarded – undo
1168 1168
 	*	@param $schema_file	string File to read schema from
1169 1169
 	*	@param $table_prefix string to replace #PREFIX# in schema file by this
1170 1170
 	*/
1171
-	public function create_schema($schema_file,$table_prefix)
1171
+	public function create_schema($schema_file, $table_prefix)
1172 1172
 	{
1173 1173
 		//Read data from snmptrapd from stdin
1174 1174
 		$input_stream=fopen($schema_file, 'r');
1175 1175
 
1176
-		if ($input_stream=== false)
1176
+		if ($input_stream === false)
1177 1177
 		{
1178
-			$this->logging->log("Error reading schema !",ERROR,''); 
1178
+			$this->logging->log("Error reading schema !", ERROR, ''); 
1179 1179
 			return;
1180 1180
 		}
1181 1181
 		$newline='';
@@ -1185,14 +1185,14 @@  discard block
 block discarded – undo
1185 1185
 		
1186 1186
 		while (($line=fgets($input_stream)) !== false)
1187 1187
 		{
1188
-			$newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
1188
+			$newline.=chop(preg_replace('/#PREFIX#/', $table_prefix, $line));
1189 1189
 			if (preg_match('/; *$/', $newline)) 
1190 1190
             {
1191
-                $sql= $newline;
1191
+                $sql=$newline;
1192 1192
                 if ($db_conn->query($sql) === false) {
1193
-                    $this->logging->log('Error create schema : '.$sql,ERROR,'');
1193
+                    $this->logging->log('Error create schema : '.$sql, ERROR, '');
1194 1194
                 }
1195
-                if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
1195
+                if (preg_match('/^ *CREATE TABLE ([^ ]+)/', $newline, $cur_table_array))
1196 1196
                 {
1197 1197
                     $cur_table='table '.$cur_table_array[1];
1198 1198
                 }
@@ -1200,19 +1200,19 @@  discard block
 block discarded – undo
1200 1200
                 {
1201 1201
                     $cur_table='secret SQL stuff :-)';
1202 1202
                 }
1203
-                $this->logging->log('Creating : ' . $cur_table,INFO );
1203
+                $this->logging->log('Creating : '.$cur_table, INFO);
1204 1204
                 $newline='';
1205 1205
             }
1206 1206
 		}
1207 1207
 		
1208
-		$sql= $newline;
1208
+		$sql=$newline;
1209 1209
 		if ($sql != '')
1210 1210
 		{
1211 1211
     		if ($db_conn->query($sql) === false) {
1212
-    			$this->logging->log('Error create schema : '.$sql,ERROR,'');
1212
+    			$this->logging->log('Error create schema : '.$sql, ERROR, '');
1213 1213
     		}
1214 1214
 		}
1215
-		$this->logging->log('Schema created',INFO);		
1215
+		$this->logging->log('Schema created', INFO);		
1216 1216
 	}
1217 1217
 
1218 1218
 	/** 
@@ -1223,14 +1223,14 @@  discard block
 block discarded – undo
1223 1223
 	 *     @param bool $getmsg : only get messages from version upgrades
1224 1224
 	 *     @return string : if $getmsg=true, return messages.
1225 1225
 	 */
1226
-	public function update_schema($prefix,$target_version,$table_prefix,$getmsg=false)
1226
+	public function update_schema($prefix, $target_version, $table_prefix, $getmsg=false)
1227 1227
 	{
1228 1228
 	    // Get current db number
1229 1229
 	    $db_conn=$this->trapsDB->db_connect_trap();
1230 1230
 	    $sql='SELECT id,value from '.$this->db_prefix.'db_config WHERE name=\'db_version\' ';
1231
-	    $this->logging->log('SQL query : '.$sql,DEBUG );
1231
+	    $this->logging->log('SQL query : '.$sql, DEBUG);
1232 1232
 	    if (($ret_code=$db_conn->query($sql)) === false) {
1233
-	        $this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
1233
+	        $this->logging->log('Cannot get db version. Query : '.$sql, 2, '');
1234 1234
 	        return;
1235 1235
 	    }
1236 1236
 	    $version=$ret_code->fetchAll();
@@ -1239,47 +1239,47 @@  discard block
 block discarded – undo
1239 1239
 	    
1240 1240
 	    if ($this->trapsDB->trapDBType == 'pgsql')
1241 1241
 	    {
1242
-	        $prefix .= 'update_pgsql/schema_';
1242
+	        $prefix.='update_pgsql/schema_';
1243 1243
 	    }
1244 1244
 	    else
1245 1245
 	    {
1246
-	        $prefix .= 'update_sql/schema_';
1246
+	        $prefix.='update_sql/schema_';
1247 1247
 	    }
1248 1248
 	    //echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
1249 1249
 	    if ($getmsg === true)
1250 1250
 	    {
1251 1251
 	        $message='';
1252
-	        $this->logging->log('getting message for upgrade',DEBUG );
1253
-	        while($cur_version<$target_version)
1252
+	        $this->logging->log('getting message for upgrade', DEBUG);
1253
+	        while ($cur_version < $target_version)
1254 1254
 	        {
1255 1255
 	            $cur_version++;
1256
-	            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
1256
+	            $updateFile=$prefix.'v'.($cur_version - 1).'_v'.$cur_version.'.sql';
1257 1257
 	            $input_stream=fopen($updateFile, 'r');
1258
-	            if ($input_stream=== false)
1258
+	            if ($input_stream === false)
1259 1259
 	            {
1260
-	                $this->logging->log("Error reading update file ". $updateFile,2,'');
1260
+	                $this->logging->log("Error reading update file ".$updateFile, 2, '');
1261 1261
 	                return;
1262 1262
 	            }
1263 1263
 	            do { $line=fgets($input_stream); }
1264
-	            while ($line !== false && !preg_match('/#MESSAGE/',$line));
1264
+	            while ($line !== false && !preg_match('/#MESSAGE/', $line));
1265 1265
 	            if ($line === false)
1266 1266
 	            {
1267
-	                $this->logging->log("No message in file ". $updateFile,2,'');
1267
+	                $this->logging->log("No message in file ".$updateFile, 2, '');
1268 1268
 	                return;
1269 1269
 	            }
1270
-	            $message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
1270
+	            $message.=($cur_version - 1).'->'.$cur_version.' : '.preg_replace('/#MESSAGE : /', '', $line)."\n";
1271 1271
 	        }
1272 1272
 	        return $message;
1273 1273
 	    }
1274
-	    while($cur_version<$target_version)
1274
+	    while ($cur_version < $target_version)
1275 1275
 	    { // tODO : execute pre & post scripts
1276 1276
 	       $cur_version++;
1277
-	       $this->logging->log('Updating to version : ' .$cur_version ,INFO );
1278
-	       $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
1277
+	       $this->logging->log('Updating to version : '.$cur_version, INFO);
1278
+	       $updateFile=$prefix.'v'.($cur_version - 1).'_v'.$cur_version.'.sql';
1279 1279
 	       $input_stream=fopen($updateFile, 'r');
1280
-	       if ($input_stream=== false)
1280
+	       if ($input_stream === false)
1281 1281
 	       {
1282
-	           $this->logging->log("Error reading update file ". $updateFile,2,'');
1282
+	           $this->logging->log("Error reading update file ".$updateFile, 2, '');
1283 1283
 	           return;
1284 1284
 	       }
1285 1285
 	       $newline='';
@@ -1288,24 +1288,24 @@  discard block
 block discarded – undo
1288 1288
 	       while (($line=fgets($input_stream)) !== false)
1289 1289
 	       {
1290 1290
 	           if (preg_match('/^#/', $line)) continue; // ignore comment lines
1291
-	           $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
1291
+	           $newline.=chop(preg_replace('/#PREFIX#/', $table_prefix, $line));
1292 1292
 	           if (preg_match('/; *$/', $newline))
1293 1293
 	           {
1294 1294
 	               $sql_req=$db_conn->prepare($newline);
1295 1295
 	               if ($sql_req->execute() === false) {
1296
-	                   $this->logging->log('Error create schema : '.$newline,1,'');
1296
+	                   $this->logging->log('Error create schema : '.$newline, 1, '');
1297 1297
 	               }
1298 1298
 	               $cur_table_array=array();
1299
-	               if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
1299
+	               if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/', $newline, $cur_table_array))
1300 1300
 	               {
1301
-	                   $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
1301
+	                   $cur_table=$cur_table_array[1].' SQL table '.$cur_table_array[2];
1302 1302
 	               }
1303 1303
 	               else
1304 1304
 	               {
1305 1305
 	                   $cur_table='secret SQL stuff :-)';
1306 1306
 	                   //$cur_table=$newline;
1307 1307
 	               }
1308
-	               $this->logging->log('Doing : ' . $cur_table,INFO );
1308
+	               $this->logging->log('Doing : '.$cur_table, INFO);
1309 1309
 	               
1310 1310
 	               $newline='';
1311 1311
 	           }
@@ -1318,13 +1318,13 @@  discard block
 block discarded – undo
1318 1318
 	       //}
1319 1319
 	       
1320 1320
 	       $sql='UPDATE '.$this->db_prefix.'db_config SET value='.$cur_version.' WHERE ( id = '.$db_version_id.' )';
1321
-	       $this->logging->log('SQL query : '.$sql,DEBUG );
1321
+	       $this->logging->log('SQL query : '.$sql, DEBUG);
1322 1322
 	       if ($db_conn->query($sql) === false) {
1323
-	           $this->logging->log('Cannot update db version. Query : ' . $sql,2);
1323
+	           $this->logging->log('Cannot update db version. Query : '.$sql, 2);
1324 1324
 	           return;
1325 1325
 	       }
1326 1326
 	       
1327
-	       $this->logging->log('Schema updated to version : '.$cur_version ,INFO);
1327
+	       $this->logging->log('Schema updated to version : '.$cur_version, INFO);
1328 1328
 	    }
1329 1329
 	}
1330 1330
 	
@@ -1345,7 +1345,7 @@  discard block
 block discarded – undo
1345 1345
     WHERE s.current_state != 0;";
1346 1346
 		$db_conn=$this->trapsDB->db_connect_ido();
1347 1347
 		if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
1348
-			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
1348
+			$this->logging->log('No result in query : '.$sql_query, ERROR, '');
1349 1349
 		}
1350 1350
 		$services=$services_db->fetchAll();
1351 1351
 		
@@ -1353,7 +1353,7 @@  discard block
 block discarded – undo
1353 1353
 		$sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->db_prefix."rules where revert_ok != 0;";
1354 1354
 		$db_conn2=$this->trapsDB->db_connect_trap();
1355 1355
 		if (($rules_db=$db_conn2->query($sql_query)) === false) {
1356
-			$this->logging->log('No result in query : ' . $sql_query,ERROR,''); 
1356
+			$this->logging->log('No result in query : '.$sql_query, ERROR, ''); 
1357 1357
 		}
1358 1358
 		$rules=$rules_db->fetchAll();
1359 1359
 		
@@ -1368,13 +1368,13 @@  discard block
 block discarded – undo
1368 1368
 					$service['host_name'] == $rule['host_name'] &&
1369 1369
 					($service['last_check'] + $rule['revert_ok']) < $now)
1370 1370
 				{
1371
-					$this->serviceCheckResult($service['host_name'],$service['service_name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
1371
+					$this->serviceCheckResult($service['host_name'], $service['service_name'], 0, 'Reset service to OK after '.$rule['revert_ok'].' seconds');
1372 1372
 					$numreset++;
1373 1373
 				}
1374 1374
 			}
1375 1375
 		}
1376 1376
 		echo "\n";
1377
-		echo $numreset . " service(s) reset to OK\n";
1377
+		echo $numreset." service(s) reset to OK\n";
1378 1378
 		return 0;
1379 1379
 		
1380 1380
 	}
@@ -1395,7 +1395,7 @@  discard block
 block discarded – undo
1395 1395
 	 * @param string $description
1396 1396
 	 * @return number : 0=unchanged, 1 = changed, 2=created
1397 1397
 	 */
1398
-	public function update_oid($oid,$mib,$name,$type,$textConv,$dispHint,$syntax,$type_enum,$description=NULL)
1398
+	public function update_oid($oid, $mib, $name, $type, $textConv, $dispHint, $syntax, $type_enum, $description=NULL)
1399 1399
 	{
1400 1400
 		$db_conn=$this->trapsDB->db_connect_trap();
1401 1401
 		$description=$db_conn->quote($description);
@@ -1405,7 +1405,7 @@  discard block
 block discarded – undo
1405 1405
 		    { // newly created.
1406 1406
 		        return 0;
1407 1407
 		    }
1408
-			if ( $name != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['name'] ||
1408
+			if ($name != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['name'] ||
1409 1409
 			    $mib != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['mib'] ||
1410 1410
 			    $type != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['type'] //||
1411 1411
 			    //$textConv != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['textual_convention'] //||
@@ -1425,23 +1425,23 @@  discard block
 block discarded – undo
1425 1425
 			        ':name' => $name,
1426 1426
 			        ':type' => $type, 
1427 1427
 			        ':mib' => $mib, 
1428
-			        ':tc' =>  ($textConv==null)?'null':$textConv , 
1429
-			        ':display_hint' => ($dispHint==null)?'null':$dispHint ,
1430
-			        ':syntax' => ($syntax==null)?'null':$syntax,
1431
-			        ':type_enum' => ($type_enum==null)?'null':$type_enum, 
1432
-			        ':description' => ($description==null)?'null':$description,
1428
+			        ':tc' =>  ($textConv == null) ? 'null' : $textConv, 
1429
+			        ':display_hint' => ($dispHint == null) ? 'null' : $dispHint,
1430
+			        ':syntax' => ($syntax == null) ? 'null' : $syntax,
1431
+			        ':type_enum' => ($type_enum == null) ? 'null' : $type_enum, 
1432
+			        ':description' => ($description == null) ? 'null' : $description,
1433 1433
 			        ':id' => $this->dbOidAll[$this->dbOidIndex[$oid]['id']]
1434 1434
 			    );
1435 1435
 			    
1436 1436
 			    if ($sqlQuery->execute($sqlParam) === false) {
1437
-			        $this->logging->log('Error in query : ' . $sql,ERROR,'');
1437
+			        $this->logging->log('Error in query : '.$sql, ERROR, '');
1438 1438
 			    }
1439
-			    $this->logging->log('Trap updated : '.$name . ' / OID : '.$oid,DEBUG );
1439
+			    $this->logging->log('Trap updated : '.$name.' / OID : '.$oid, DEBUG);
1440 1440
 				return 1;
1441 1441
 			}
1442 1442
 			else
1443 1443
 			{
1444
-			    $this->logging->log('Trap unchanged : '.$name . ' / OID : '.$oid,DEBUG );
1444
+			    $this->logging->log('Trap unchanged : '.$name.' / OID : '.$oid, DEBUG);
1445 1445
 			    return 0;
1446 1446
 			}
1447 1447
 		}
@@ -1451,11 +1451,11 @@  discard block
 block discarded – undo
1451 1451
 
1452 1452
 		$sql='INSERT INTO '.$this->db_prefix.'mib_cache '.
1453 1453
 		      '(oid, name, type , mib, textual_convention, display_hint '.
1454
-              ', syntax, type_enum , description ) ' . 
1454
+              ', syntax, type_enum , description ) '. 
1455 1455
               'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
1456 1456
               ', :syntax, :type_enum, :description )';
1457 1457
         
1458
-		if ($this->trapsDB->trapDBType == 'pgsql') $sql .= 'RETURNING id';
1458
+		if ($this->trapsDB->trapDBType == 'pgsql') $sql.='RETURNING id';
1459 1459
 		
1460 1460
 		$sqlQuery=$db_conn->prepare($sql);
1461 1461
 		
@@ -1464,15 +1464,15 @@  discard block
 block discarded – undo
1464 1464
 		    ':name' => $name,
1465 1465
 		    ':type' => $type,
1466 1466
 		    ':mib' => $mib,
1467
-		    ':tc' =>  ($textConv==null)?'null':$textConv ,
1468
-		    ':display_hint' => ($dispHint==null)?'null':$dispHint ,
1469
-		    ':syntax' => ($syntax==null)?'null':$syntax,
1470
-		    ':type_enum' => ($type_enum==null)?'null':$type_enum,
1471
-		    ':description' => ($description==null)?'null':$description
1467
+		    ':tc' =>  ($textConv == null) ? 'null' : $textConv,
1468
+		    ':display_hint' => ($dispHint == null) ? 'null' : $dispHint,
1469
+		    ':syntax' => ($syntax == null) ? 'null' : $syntax,
1470
+		    ':type_enum' => ($type_enum == null) ? 'null' : $type_enum,
1471
+		    ':description' => ($description == null) ? 'null' : $description
1472 1472
 		);
1473 1473
 		
1474 1474
 		if ($sqlQuery->execute($sqlParam) === false) {
1475
-		    $this->logging->log('Error in query : ' . $sql,1,'');
1475
+		    $this->logging->log('Error in query : '.$sql, 1, '');
1476 1476
 		}
1477 1477
 		
1478 1478
 		switch ($this->trapsDB->trapDBType)
@@ -1480,10 +1480,10 @@  discard block
 block discarded – undo
1480 1480
 		    case 'pgsql':
1481 1481
 		        // Get last id to insert oid/values in secondary table
1482 1482
 		        if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {		            
1483
-		            $this->logging->log('Error getting id - pgsql - ',1,'');
1483
+		            $this->logging->log('Error getting id - pgsql - ', 1, '');
1484 1484
 		        }
1485
-		        if (! isset($inserted_id_ret['id'])) {
1486
-		            $this->logging->log('Error getting id - pgsql - empty.',1,'');
1485
+		        if (!isset($inserted_id_ret['id'])) {
1486
+		            $this->logging->log('Error getting id - pgsql - empty.', 1, '');
1487 1487
 		        }
1488 1488
 		        $this->dbOidIndex[$oid]['id']=$inserted_id_ret['id'];
1489 1489
 		        break;
@@ -1491,15 +1491,15 @@  discard block
 block discarded – undo
1491 1491
 		        // Get last id to insert oid/values in secondary table
1492 1492
 		        $sql='SELECT LAST_INSERT_ID();';
1493 1493
 		        if (($ret_code=$db_conn->query($sql)) === false) {
1494
-		            $this->logging->log('Erreur getting id - mysql - ',1,'');
1494
+		            $this->logging->log('Erreur getting id - mysql - ', 1, '');
1495 1495
 		        }
1496 1496
 		        
1497 1497
 		        $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
1498
-		        if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
1498
+		        if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
1499 1499
 		        $this->dbOidIndex[$oid]['id']=$inserted_id;
1500 1500
 		        break;
1501 1501
 		    default:
1502
-		        $this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType,1,'');
1502
+		        $this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType, 1, '');
1503 1503
 		}
1504 1504
 
1505 1505
 		// Set as newly created.
@@ -1514,21 +1514,21 @@  discard block
 block discarded – undo
1514 1514
      * @param array $objects : array of objects name (without MIB)
1515 1515
      * @param bool $check_existing : check instead of create
1516 1516
      */
1517
-	public function trap_objects($trapOID,$trapmib,$objects,$check_existing)
1517
+	public function trap_objects($trapOID, $trapmib, $objects, $check_existing)
1518 1518
 	{
1519 1519
 	    $dbObjects=null; // cache of objects for trap in db
1520 1520
 	    $db_conn=$this->trapsDB->db_connect_trap();
1521 1521
 	    
1522 1522
 	    // Get id of trapmib.
1523 1523
 
1524
-	    $trapId = $this->dbOidIndex[$trapOID]['id'];
1524
+	    $trapId=$this->dbOidIndex[$trapOID]['id'];
1525 1525
 	    if ($check_existing === true)
1526 1526
 	    {
1527 1527
 	        // Get all objects
1528 1528
 	        $sql='SELECT * FROM '.$this->db_prefix.'mib_cache_trap_object where trap_id='.$trapId.';';
1529
-	        $this->logging->log('SQL query get all traps: '.$sql,DEBUG );
1529
+	        $this->logging->log('SQL query get all traps: '.$sql, DEBUG);
1530 1530
 	        if (($ret_code=$db_conn->query($sql)) === false) {
1531
-	            $this->logging->log('No result in query : ' . $sql,1,'');
1531
+	            $this->logging->log('No result in query : '.$sql, 1, '');
1532 1532
 	        }
1533 1533
 	        $dbObjectsRaw=$ret_code->fetchAll();
1534 1534
 	        
@@ -1542,39 +1542,39 @@  discard block
 block discarded – undo
1542 1542
 	        $match=$snmptrans=array();
1543 1543
 	        $retVal=0;
1544 1544
 	        $objOid=$objTc=$objDispHint=$objSyntax=$objDesc=$objEnum=NULL;
1545
-	        $tmpdesc='';$indesc=false;
1545
+	        $tmpdesc=''; $indesc=false;
1546 1546
 	        
1547 1547
 	        $objMib=$trapmib;
1548
-	        exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1549
-	            ' -On -Td '.$objMib.'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
1550
-	        if ($retVal!=0)
1548
+	        exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
1549
+	            ' -On -Td '.$objMib.'::'.$object.' 2>/dev/null', $snmptrans, $retVal);
1550
+	        if ($retVal != 0)
1551 1551
 	        {
1552 1552
 	            // Maybe not trap mib, search with IR
1553
-	            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1554
-	                ' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
1555
-	            if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
1553
+	            exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
1554
+	                ' -IR '.$object.' 2>/dev/null', $snmptrans, $retVal);
1555
+	            if ($retVal != 0 || !preg_match('/(.*)::(.*)/', $snmptrans[0], $match))
1556 1556
 	            { // Not found -> continue with warning
1557
-	               $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
1557
+	               $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object, 2, '');
1558 1558
 	               continue;
1559 1559
 	            }
1560 1560
 	            $objMib=$match[1];
1561 1561
 	            
1562 1562
 	            // Do the snmptranslate again.
1563
-	            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1564
-	                ' -On -Td '.$objMib.'::'.$object,$snmptrans,$retVal);
1565
-	            if ($retVal!=0) {
1566
-	                $this->logging->log('Error finding trap object : '.$objMib.'::'.$object,2,'');
1563
+	            exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
1564
+	                ' -On -Td '.$objMib.'::'.$object, $snmptrans, $retVal);
1565
+	            if ($retVal != 0) {
1566
+	                $this->logging->log('Error finding trap object : '.$objMib.'::'.$object, 2, '');
1567 1567
 	            }
1568 1568
 	            
1569 1569
 	        }
1570 1570
 	        foreach ($snmptrans as $line)
1571 1571
 	        {
1572
-	            if ($indesc===true)
1572
+	            if ($indesc === true)
1573 1573
 	            {
1574
-	                $line=preg_replace('/[\t ]+/',' ',$line);
1575
-	                if (preg_match('/(.*)"$/', $line,$match))
1574
+	                $line=preg_replace('/[\t ]+/', ' ', $line);
1575
+	                if (preg_match('/(.*)"$/', $line, $match))
1576 1576
 	                {
1577
-	                    $objDesc = $tmpdesc . $match[1];
1577
+	                    $objDesc=$tmpdesc.$match[1];
1578 1578
 	                    $indesc=false;
1579 1579
 	                }
1580 1580
 	                $tmpdesc.=$line;
@@ -1585,43 +1585,43 @@  discard block
 block discarded – undo
1585 1585
 	                $objOid=$line;
1586 1586
 	                continue;
1587 1587
 	            }
1588
-	            if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
1588
+	            if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/', $line, $match))
1589 1589
 	            {
1590 1590
 	                $objSyntax=$match[1];
1591 1591
                     $objEnum=$match[2];
1592 1592
 	                continue;
1593 1593
 	            }
1594
-	            if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
1594
+	            if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/', $line, $match))
1595 1595
 	            {
1596 1596
 	                $objSyntax=$match[1];
1597 1597
 	                continue;
1598 1598
 	            }
1599
-	            if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
1599
+	            if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/', $line, $match))
1600 1600
 	            {
1601 1601
 	                $objDispHint=$match[1];
1602 1602
 	                continue;
1603 1603
 	            }
1604
-	            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
1604
+	            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/', $line, $match))
1605 1605
 	            {
1606 1606
 	                $objDesc=$match[1];
1607 1607
 	                continue;
1608 1608
 	            }
1609
-	            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
1609
+	            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/', $line, $match))
1610 1610
 	            {
1611 1611
 	                $tmpdesc=$match[1];
1612 1612
 	                $indesc=true;
1613 1613
 	                continue;
1614 1614
 	            }
1615
-	            if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
1615
+	            if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/', $line, $match))
1616 1616
 	            {
1617 1617
 	                $objTc=$match[1];
1618 1618
 	                continue;
1619 1619
 	            }
1620 1620
 	        }
1621
-	        $this->logging->log("Adding trap $object : $objOid / $objSyntax / $objEnum / $objDispHint / $objTc",DEBUG );
1621
+	        $this->logging->log("Adding trap $object : $objOid / $objSyntax / $objEnum / $objDispHint / $objTc", DEBUG);
1622 1622
 	        //echo "$object : $objOid / $objSyntax / $objEnum / $objDispHint / $objTc / $objDesc\n";
1623 1623
 	        // Update 
1624
-	        $this->update_oid($objOid, $objMib, $object, '3', $objTc, $objDispHint, $objSyntax, $objEnum,$objDesc);
1624
+	        $this->update_oid($objOid, $objMib, $object, '3', $objTc, $objDispHint, $objSyntax, $objEnum, $objDesc);
1625 1625
             
1626 1626
 	        if (isset($dbObjects[$this->dbOidIndex[$objOid]['id']]))
1627 1627
 	        {   // if link exists, continue
@@ -1642,7 +1642,7 @@  discard block
 block discarded – undo
1642 1642
 	        );
1643 1643
 	        
1644 1644
 	        if ($sqlQuery->execute($sqlParam) === false) {
1645
-	            $this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$objOid]['id'] ,1,'');
1645
+	            $this->logging->log('Error adding trap object : '.$sql.' / '.$trapId.'/'.$this->dbOidIndex[$objOid]['id'], 1, '');
1646 1646
 	        }
1647 1647
 	    }
1648 1648
 	    if ($check_existing === true)
@@ -1659,19 +1659,19 @@  discard block
 block discarded – undo
1659 1659
 	 * @param boolean $onlyTraps : only cache traps and objects (true) or all (false)
1660 1660
 	 * @param string $startOID : only cache under startOID (NOT IMPLEMENTED)
1661 1661
 	*/	
1662
-	public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,$startOID='.1')
1662
+	public function update_mib_database($display_progress=false, $check_change=false, $onlyTraps=true, $startOID='.1')
1663 1663
 	{
1664 1664
 		// Timing 
1665
-		$timeTaken = microtime(true);
1665
+		$timeTaken=microtime(true);
1666 1666
 		$retVal=0;
1667 1667
 		// Get all mib objects from all mibs
1668
-		$snmpCommand=$this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.' -On -Tto 2>/dev/null';
1669
-		$this->logging->log('Getting all traps : '.$snmpCommand,DEBUG );
1668
+		$snmpCommand=$this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.' -On -Tto 2>/dev/null';
1669
+		$this->logging->log('Getting all traps : '.$snmpCommand, DEBUG);
1670 1670
 		unset($this->objectsAll);
1671
-		exec($snmpCommand,$this->objectsAll,$retVal);		
1672
-		if ($retVal!=0)
1671
+		exec($snmpCommand, $this->objectsAll, $retVal);		
1672
+		if ($retVal != 0)
1673 1673
 		{
1674
-			$this->logging->log('error executing snmptranslate',ERROR,'');
1674
+			$this->logging->log('error executing snmptranslate', ERROR, '');
1675 1675
 		}
1676 1676
 		
1677 1677
 		// Get all mibs from databse to have a memory index
@@ -1679,14 +1679,14 @@  discard block
 block discarded – undo
1679 1679
 		$db_conn=$this->trapsDB->db_connect_trap();
1680 1680
 		
1681 1681
 		$sql='SELECT * from '.$this->db_prefix.'mib_cache;';
1682
-		$this->logging->log('SQL query : '.$sql,DEBUG );
1682
+		$this->logging->log('SQL query : '.$sql, DEBUG);
1683 1683
 		if (($ret_code=$db_conn->query($sql)) === false) {
1684
-			$this->logging->log('No result in query : ' . $sql,ERROR,'');
1684
+			$this->logging->log('No result in query : '.$sql, ERROR, '');
1685 1685
 		}
1686 1686
 		$this->dbOidAll=$ret_code->fetchAll();
1687 1687
 		$this->dbOidIndex=array();
1688 1688
 		// Create the index for db;
1689
-		foreach($this->dbOidAll as $key=>$val)
1689
+		foreach ($this->dbOidAll as $key=>$val)
1690 1690
 		{
1691 1691
 			$this->dbOidIndex[$val['oid']]['key']=$key;
1692 1692
 			$this->dbOidIndex[$val['oid']]['id']=$val['id'];
@@ -1694,11 +1694,11 @@  discard block
 block discarded – undo
1694 1694
 		
1695 1695
 		// Count elements to show progress
1696 1696
 		$numElements=count($this->objectsAll);
1697
-		$this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements,INFO );
1697
+		$this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements, INFO);
1698 1698
 		
1699
-		$step=$basestep=$numElements/10; // output display of % done
1699
+		$step=$basestep=$numElements / 10; // output display of % done
1700 1700
 		$num_step=0;
1701
-		$timeFiveSec = microtime(true); // Used for display a '.' every <n> seconds
1701
+		$timeFiveSec=microtime(true); // Used for display a '.' every <n> seconds
1702 1702
 		
1703 1703
 		// Create index for trap objects
1704 1704
 		$this->trapObjectsIndex=array();
@@ -1708,28 +1708,28 @@  discard block
 block discarded – undo
1708 1708
 		$time_parse1N=$time_check1N=$time_check2N=$time_check3N=$time_updateN=$time_objectsN=0;
1709 1709
 		$time_num_traps=0;
1710 1710
 		
1711
-		for ($curElement=0;$curElement < $numElements;$curElement++)
1711
+		for ($curElement=0; $curElement < $numElements; $curElement++)
1712 1712
 		{
1713
-		    $time_1= microtime(true);
1714
-			if ((microtime(true)-$timeFiveSec) > 2 && $display_progress)
1713
+		    $time_1=microtime(true);
1714
+			if ((microtime(true) - $timeFiveSec) > 2 && $display_progress)
1715 1715
 			{ // echo a . every 2 sec
1716 1716
 				echo '.';
1717
-				$timeFiveSec = microtime(true);
1717
+				$timeFiveSec=microtime(true);
1718 1718
 			}
1719
-			if ($curElement>$step) 
1719
+			if ($curElement > $step) 
1720 1720
 			{ // display progress
1721 1721
 				$num_step++;
1722 1722
 				$step+=$basestep;
1723 1723
 				if ($display_progress)
1724 1724
 				{				
1725
-					echo "\n" . ($num_step*10). '% : ';
1725
+					echo "\n".($num_step * 10).'% : ';
1726 1726
 				}
1727 1727
 			}
1728 1728
 			// Get oid or pass if not found
1729
-			if (!preg_match('/^\.[0-9\.]+$/',$this->objectsAll[$curElement]))
1729
+			if (!preg_match('/^\.[0-9\.]+$/', $this->objectsAll[$curElement]))
1730 1730
 			{
1731
-			    $time_parse1 += microtime(true) - $time_1;
1732
-			    $time_parse1N ++;
1731
+			    $time_parse1+=microtime(true) - $time_1;
1732
+			    $time_parse1N++;
1733 1733
 				continue;
1734 1734
 			}
1735 1735
 			$oid=$this->objectsAll[$curElement];
@@ -1738,9 +1738,9 @@  discard block
 block discarded – undo
1738 1738
 			$curElement++;
1739 1739
 			$match=$snmptrans=array();
1740 1740
 			if (!preg_match('/ +([^\(]+)\(.+\) type=([0-9]+)( tc=([0-9]+))?( hint=(.+))?/',
1741
-						$this->objectsAll[$curElement],$match))
1741
+						$this->objectsAll[$curElement], $match))
1742 1742
 			{
1743
-			    $time_check1 += microtime(true) - $time_1;
1743
+			    $time_check1+=microtime(true) - $time_1;
1744 1744
 				$time_check1N++;
1745 1745
 				continue;
1746 1746
 			}
@@ -1748,21 +1748,21 @@  discard block
 block discarded – undo
1748 1748
 			$name=$match[1]; // Name 
1749 1749
 			$type=$match[2]; // type (21=trap, 0: may be trap, else : not trap
1750 1750
 			
1751
-			if ($type==0) // object type=0 : check if v1 trap
1751
+			if ($type == 0) // object type=0 : check if v1 trap
1752 1752
 			{
1753 1753
 				// Check if next is suboid -> in that case is cannot be a trap
1754
-				if (preg_match("/^$oid/",$this->objectsAll[$curElement+1]))
1754
+				if (preg_match("/^$oid/", $this->objectsAll[$curElement + 1]))
1755 1755
 				{
1756
-				    $time_check2 += microtime(true) - $time_1;
1756
+				    $time_check2+=microtime(true) - $time_1;
1757 1757
 				    $time_check2N++;
1758 1758
 					continue;
1759 1759
 				}		
1760 1760
 				unset($snmptrans);
1761
-				exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1762
-					' -Td '.$oid . ' | grep OBJECTS ',$snmptrans,$retVal);
1763
-				if ($retVal!=0)
1761
+				exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
1762
+					' -Td '.$oid.' | grep OBJECTS ', $snmptrans, $retVal);
1763
+				if ($retVal != 0)
1764 1764
 				{
1765
-				    $time_check2 += microtime(true) - $time_1;
1765
+				    $time_check2+=microtime(true) - $time_1;
1766 1766
 				    $time_check2N++;
1767 1767
 					continue;
1768 1768
 				}
@@ -1770,56 +1770,56 @@  discard block
 block discarded – undo
1770 1770
 				// Force as trap.
1771 1771
 				$type=21;
1772 1772
 			}
1773
-			if ($onlyTraps===true && $type!=21) // if only traps and not a trap, continue
1773
+			if ($onlyTraps === true && $type != 21) // if only traps and not a trap, continue
1774 1774
 			{
1775
-			    $time_check3 += microtime(true) - $time_1;
1775
+			    $time_check3+=microtime(true) - $time_1;
1776 1776
 				$time_check3N++;
1777 1777
 				continue;
1778 1778
 			}
1779 1779
 			
1780 1780
 			$time_num_traps++;
1781 1781
 			
1782
-			$this->logging->log('Found trap : '.$match[1] . ' / OID : '.$oid,INFO );
1782
+			$this->logging->log('Found trap : '.$match[1].' / OID : '.$oid, INFO);
1783 1783
 			if ($display_progress) echo '#'; // echo a # when trap found
1784 1784
 				
1785 1785
 			// get trap objects & source MIB
1786 1786
 			unset($snmptrans);
1787
-			exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1788
-					' -Td '.$oid,$snmptrans,$retVal);
1789
-			if ($retVal!=0)
1787
+			exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
1788
+					' -Td '.$oid, $snmptrans, $retVal);
1789
+			if ($retVal != 0)
1790 1790
 			{
1791
-				$this->logging->log('error executing snmptranslate',ERROR,'');
1791
+				$this->logging->log('error executing snmptranslate', ERROR, '');
1792 1792
 			}
1793 1793
 			
1794
-			if (!preg_match('/^(.*)::/',$snmptrans[0],$match))
1794
+			if (!preg_match('/^(.*)::/', $snmptrans[0], $match))
1795 1795
 			{
1796
-			    $this->logging->log('Error getting mib from trap '.$oid.' : ' . $snmptrans[0],1,'');
1796
+			    $this->logging->log('Error getting mib from trap '.$oid.' : '.$snmptrans[0], 1, '');
1797 1797
 			}
1798 1798
 			$trapMib=$match[1];
1799 1799
 			
1800
-			$numLine=1;$trapDesc='';
1801
-			while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
1800
+			$numLine=1; $trapDesc='';
1801
+			while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/', $snmptrans[$numLine], $match)) $numLine++;
1802 1802
 			if (isset($snmptrans[$numLine]))
1803 1803
 			{
1804
-			    $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
1804
+			    $snmptrans[$numLine]=preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/', '', $snmptrans[$numLine]);
1805 1805
 
1806
-			    while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
1806
+			    while (isset($snmptrans[$numLine]) && !preg_match('/"/', $snmptrans[$numLine]))
1807 1807
 			    {
1808
-			        $trapDesc.=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
1808
+			        $trapDesc.=preg_replace('/[\t ]+/', ' ', $snmptrans[$numLine]);
1809 1809
 			        $numLine++;
1810 1810
 			    }
1811 1811
 			    if (isset($snmptrans[$numLine])) {
1812
-			        $trapDesc.=preg_replace('/".*/','',$snmptrans[$numLine]);
1813
-			        $trapDesc=preg_replace('/[\t ]+/',' ',$trapDesc);
1812
+			        $trapDesc.=preg_replace('/".*/', '', $snmptrans[$numLine]);
1813
+			        $trapDesc=preg_replace('/[\t ]+/', ' ', $trapDesc);
1814 1814
 			    }
1815 1815
 
1816 1816
 			}
1817
-			$update=$this->update_oid($oid,$trapMib,$name,$type,NULL,NULL,NULL,NULL,$trapDesc);
1818
-			$time_update += microtime(true) - $time_1; $time_1= microtime(true);
1817
+			$update=$this->update_oid($oid, $trapMib, $name, $type, NULL, NULL, NULL, NULL, $trapDesc);
1818
+			$time_update+=microtime(true) - $time_1; $time_1=microtime(true);
1819 1819
 			
1820
-			if (($update==0) && ($check_change===false))
1820
+			if (($update == 0) && ($check_change === false))
1821 1821
 			{ // Trapd didn't change & force check disabled
1822
-			    $time_objects += microtime(true) - $time_1;
1822
+			    $time_objects+=microtime(true) - $time_1;
1823 1823
 			    if ($display_progress) echo "C";
1824 1824
 			    continue;
1825 1825
 			}
@@ -1827,7 +1827,7 @@  discard block
 block discarded – undo
1827 1827
 			$synt=null;
1828 1828
 			foreach ($snmptrans as $line)
1829 1829
 			{	
1830
-    			if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
1830
+    			if (preg_match('/OBJECTS.*\{([^\}]+)\}/', $line, $match))
1831 1831
     				{
1832 1832
     					$synt=$match[1];
1833 1833
     				}
@@ -1835,30 +1835,30 @@  discard block
 block discarded – undo
1835 1835
 			if ($synt == null) 
1836 1836
 			{
1837 1837
 				//echo "No objects for $trapOID\n";
1838
-			    $time_objects += microtime(true) - $time_1;
1838
+			    $time_objects+=microtime(true) - $time_1;
1839 1839
 				continue;
1840 1840
 			}
1841 1841
 			//echo "$synt \n";
1842 1842
 			$trapObjects=array();
1843
-			while (preg_match('/ *([^ ,]+) *,* */',$synt,$match))
1843
+			while (preg_match('/ *([^ ,]+) *,* */', $synt, $match))
1844 1844
 			{
1845
-				array_push($trapObjects,$match[1]);
1846
-				$synt=preg_replace('/'.$match[0].'/','',$synt);
1845
+				array_push($trapObjects, $match[1]);
1846
+				$synt=preg_replace('/'.$match[0].'/', '', $synt);
1847 1847
 			}
1848 1848
 			
1849 1849
 			$this->trap_objects($oid, $trapMib, $trapObjects, false);
1850 1850
 			
1851
-			$time_objects += microtime(true) - $time_1;
1851
+			$time_objects+=microtime(true) - $time_1;
1852 1852
 			$time_objectsN++;
1853 1853
 		}
1854 1854
 		
1855 1855
 		if ($display_progress)
1856 1856
 		{
1857 1857
     		echo "\nNumber of processed traps : $time_num_traps \n";
1858
-    		echo "\nParsing : " . number_format($time_parse1+$time_check1,1) ." sec / " . ($time_parse1N+ $time_check1N)  . " occurences\n";
1859
-    		echo "Detecting traps : " . number_format($time_check2+$time_check3,1) . " sec / " . ($time_check2N+$time_check3N) ." occurences\n";
1860
-    		echo "Trap processing ($time_updateN): ".number_format($time_update,1)." sec , ";
1861
-    		echo "Objects processing ($time_objectsN) : ".number_format($time_objects,1)." sec \n";
1858
+    		echo "\nParsing : ".number_format($time_parse1 + $time_check1, 1)." sec / ".($time_parse1N + $time_check1N)." occurences\n";
1859
+    		echo "Detecting traps : ".number_format($time_check2 + $time_check3, 1)." sec / ".($time_check2N + $time_check3N)." occurences\n";
1860
+    		echo "Trap processing ($time_updateN): ".number_format($time_update, 1)." sec , ";
1861
+    		echo "Objects processing ($time_objectsN) : ".number_format($time_objects, 1)." sec \n";
1862 1862
 		}
1863 1863
 		
1864 1864
 		// Timing ends
Please login to merge, or discard this patch.
Braces   +119 added lines, -74 removed lines patch added patch discarded remove patch
@@ -71,9 +71,9 @@  discard block
 block discarded – undo
71 71
 		{
72 72
 		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
73 73
 		    $this->logSetup=true;
74
+		} else {
75
+				    $this->logSetup=false;
74 76
 		}
75
-		else 
76
-		    $this->logSetup=false;
77 77
 		$this->logging->log('Loggin started', INFO);
78 78
 
79 79
 		// Get options from ini files
@@ -86,7 +86,10 @@  discard block
 block discarded – undo
86 86
 		$this->setupDatabase($trapConfig); // Setup database class
87 87
 		
88 88
 		$this->getDatabaseOptions(); // Get options in database
89
-		if ($this->api_use === true) $this->getAPI(); // Setup API
89
+		if ($this->api_use === true) {
90
+			$this->getAPI();
91
+		}
92
+		// Setup API
90 93
 		
91 94
 		$this->trap_data=array(
92 95
 			'source_ip'	=> 'unknown',
@@ -118,8 +121,7 @@  discard block
 block discarded – undo
118 121
 	        }
119 122
 	        $this->logging->log($message,$log_level,'syslog');
120 123
 	        return false;
121
-	    }
122
-	    else
124
+	    } else
123 125
 	    {
124 126
 	        $option_var=$option_array[$option_category][$option_name];
125 127
 	        return true;
@@ -185,7 +187,10 @@  discard block
 block discarded – undo
185 187
 	    
186 188
         $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName]);
187 189
 	    
188
-	    if ($this->api_use === true) return; // In case of API use, no IDO is necessary
190
+	    if ($this->api_use === true) {
191
+	    	return;
192
+	    }
193
+	    // In case of API use, no IDO is necessary
189 194
         
190 195
 	    // IDO Database
191 196
 	    if (!array_key_exists('IDOdatabase',$trapConfig['config']))
@@ -210,9 +215,11 @@  discard block
 block discarded – undo
210 215
 	protected function getDatabaseOptions()
211 216
 	{
212 217
 		// Database options
213
-		if ($this->logSetup == false) // Only if logging was no setup in constructor
218
+		if ($this->logSetup == false) {
219
+			// Only if logging was no setup in constructor
214 220
 		{
215 221
     		$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
222
+		}
216 223
     		$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
217 224
     		$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
218 225
 		}
@@ -221,7 +228,9 @@  discard block
 block discarded – undo
221 228
 	protected function getDBConfigIfSet($element,&$variable)
222 229
 	{
223 230
 		$value=$this->getDBConfig($element);
224
-		if ($value != 'null') $variable=$value;
231
+		if ($value != 'null') {
232
+			$variable=$value;
233
+		}
225 234
 	}
226 235
 	
227 236
 	/** 
@@ -309,8 +318,7 @@  discard block
 block discarded – undo
309 318
 		{
310 319
 		    $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
311 320
 			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
312
-		} 
313
-		else 
321
+		} else 
314 322
 		{		
315 323
 			$this->trap_data['source_ip']=$matches[1];
316 324
 			$this->trap_data['destination_ip']=$matches[3];
@@ -325,14 +333,12 @@  discard block
 block discarded – undo
325 333
 			if ($ret_code===0 || $ret_code===false) 
326 334
 			{
327 335
 				$this->logging->log('No match on trap data : '.$vars,WARN,'');
328
-			}
329
-			else 
336
+			} else 
330 337
 			{
331 338
 			    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 339
 				{
333 340
 					$this->trap_data['trap_oid']=$matches[2];				
334
-				}
335
-				else
341
+				} else
336 342
 				{
337 343
 					$object= new stdClass;
338 344
 					$object->oid =$matches[1];
@@ -503,7 +509,9 @@  discard block
 block discarded – undo
503 509
 	            }
504 510
 	            
505 511
 	            $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");
512
+	            if ($inserted_id==false) {
513
+	            	throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
514
+	            }
507 515
 	            $this->trap_id=$inserted_id;
508 516
 	            break;
509 517
 	        default:
@@ -519,7 +527,9 @@  discard block
 block discarded – undo
519 527
 	{
520 528
 		
521 529
 		// If action is ignore -> don't send t DB
522
-		if ($this->trap_to_db === false) return;
530
+		if ($this->trap_to_db === false) {
531
+			return;
532
+		}
523 533
 		
524 534
 		
525 535
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -576,7 +586,9 @@  discard block
 block discarded – undo
576 586
 				}
577 587
 
578 588
 				$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");
589
+				if ($inserted_id==false) {
590
+					throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
591
+				}
580 592
 				$this->trap_id=$inserted_id;
581 593
 			break;
582 594
 			default: 
@@ -705,8 +717,7 @@  discard block
 block discarded – undo
705 717
     		// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
706 718
     		exec('echo "'.$send.'" > ' .$this->icinga2cmd);
707 719
     		return true;
708
-	    }
709
-	    else
720
+	    } else
710 721
 	    {
711 722
 	        $api = $this->getAPI();
712 723
 	        $api->setCredentials($this->api_username, $this->api_password);
@@ -715,8 +726,7 @@  discard block
 block discarded – undo
715 726
 	        {
716 727
 	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
717 728
 	            return false;
718
-	        }
719
-	        else 
729
+	        } else 
720 730
 	        {
721 731
 	            $this->logging->log( "Sent result : " .$retmessage,INFO );
722 732
 	            return true;
@@ -776,7 +786,9 @@  discard block
 block discarded – undo
776 786
 	/***************** Eval & tokenizer functions ****************/
777 787
 	protected function eval_getElement($rule,&$item)
778 788
 	{
779
-		while ($rule[$item]==' ') $item++;
789
+		while ($rule[$item]==' ') {
790
+			$item++;
791
+		}
780 792
 		if (preg_match('/[0-9\.]/',$rule[$item]))
781 793
 		{ // number
782 794
 	
@@ -803,14 +815,15 @@  discard block
 block discarded – undo
803 815
 			$start=$item;
804 816
 			$parenthesis_count=0; 
805 817
 			while (($item < strlen($rule)) // Not end of string AND
806
-			      && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
818
+			      && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) {
819
+				// Closing ')' or embeded ()
807 820
 			{ 
808 821
 				if ($rule[$item] == '"' )
809 822
 				{ // pass through string
810 823
 					$item++;
824
+			}
811 825
 					$item=$this->eval_getNext($rule,$item,'"');
812
-				} 
813
-				else{
826
+				} else{
814 827
 				    if ($rule[$item] == '(')
815 828
 				    {
816 829
 				        $parenthesis_count++;
@@ -838,13 +851,17 @@  discard block
 block discarded – undo
838 851
 	protected function eval_getNext($rule,$item,$tok)
839 852
 	{
840 853
 		while (($rule[$item] != $tok ) && ($item < strlen($rule))) { $item++;}
841
-		if ($item==strlen($rule)) throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
854
+		if ($item==strlen($rule)) {
855
+			throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
856
+		}
842 857
 		return $item+1;
843 858
 	}
844 859
 	
845 860
 	protected function eval_getOper($rule,&$item)
846 861
 	{
847
-		while ($rule[$item]==' ') $item++;
862
+		while ($rule[$item]==' ') {
863
+			$item++;
864
+		}
848 865
 		switch ($rule[$item])
849 866
 		{
850 867
 			case '<':
@@ -880,12 +897,13 @@  discard block
 block discarded – undo
880 897
 	public function evaluation($rule,&$item)
881 898
 	{
882 899
 	    //echo "Evaluation of ".substr($rule,$item)."\n";
883
-		if ( $rule[$item] == '!') // If '!' found, negate next expression.
900
+		if ( $rule[$item] == '!') {
901
+			// If '!' found, negate next expression.
884 902
 		{
885 903
 		    $negate=true;
886
-		    $item++;
887 904
 		}
888
-		else
905
+		    $item++;
906
+		} else
889 907
 		{
890 908
 		    $negate=false;
891 909
 		}
@@ -893,10 +911,14 @@  discard block
 block discarded – undo
893 911
 		list($type1,$val1) = $this->eval_getElement($rule,$item);
894 912
 		//echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
895 913
 		
896
-		if ($item==strlen($rule)) // If only element, return value, but only boolean
914
+		if ($item==strlen($rule)) {
915
+			// If only element, return value, but only boolean
897 916
 		{
898 917
 		  if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
899
-		  if ($negate === true) $val1= ! $val1;
918
+		}
919
+		  if ($negate === true) {
920
+		  	$val1= ! $val1;
921
+		  }
900 922
 		  return $val1;
901 923
 		}  
902 924
 		
@@ -905,27 +927,34 @@  discard block
 block discarded – undo
905 927
 		//echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
906 928
         
907 929
 		// Third element : number, string or ()
908
-		if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
930
+		if ( $rule[$item] == '!') {
931
+			// starts with a ! so evaluate whats next
909 932
 		{
910 933
 		    $item++;
911
-		    if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
934
+		}
935
+		    if ($typec != 1) {
936
+		    	throw new Exception("Mixing boolean and comparison : ".$rule);
937
+		    }
912 938
 		    $val2= ! $this->evaluation($rule,$item);
913 939
 		    $type2=2; // result is a boolean 
914
-		}
915
-		else 
940
+		} else 
916 941
 		{
917 942
 		    list($type2,$val2) = $this->eval_getElement($rule,$item);
918 943
 		}
919 944
 		//echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
920 945
 		
921
-		if ($type1!=$type2)  // cannot compare different types
946
+		if ($type1!=$type2) {
947
+			// cannot compare different types
922 948
 		{ 
923 949
 		    throw new Exception("Cannot compare string & number : ".$rule);
924 950
 		}
925
-		if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
951
+		}
952
+		if ($typec==1 && $type1 !=2) {
953
+			// cannot use & or | with string/number
926 954
 		{
927 955
 		    throw new Exception("Cannot use boolean operators with string & number : ".$rule);
928 956
 		}
957
+		}
929 958
 		
930 959
 		switch ($comp){
931 960
 			case '<':	$retVal= ($val1 < $val2); break;
@@ -939,9 +968,15 @@  discard block
 block discarded – undo
939 968
 			case '&':	$retVal= ($val1 && $val2); break;
940 969
 			default:  throw new Exception("Error in expression - unknown comp : ".$comp);
941 970
 		}
942
-		if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
971
+		if ($negate === true) {
972
+			$retVal = ! $retVal;
973
+		}
974
+		// Inverse result if negate before expression
943 975
 		
944
-		if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
976
+		if ($item==strlen($rule)) {
977
+			return $retVal;
978
+		}
979
+		// End of string : return evaluation
945 980
 		// check for logical operator :
946 981
 		switch ($rule[$item])
947 982
 		{
@@ -968,7 +1003,9 @@  discard block
 block discarded – undo
968 1003
 					$rule2.=$rule[$item];
969 1004
 					$item++;
970 1005
 				}
971
-				if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
1006
+				if ($item == strlen ($rule)) {
1007
+					throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
1008
+				}
972 1009
 				$rule2.=$rule[$item];
973 1010
 				$item++;
974 1011
 				continue;
@@ -988,10 +1025,12 @@  discard block
 block discarded – undo
988 1025
 	
989 1026
 	protected function eval_rule($rule)
990 1027
 	{
991
-		if ($rule==null || $rule == '') // Empty rule is always true
1028
+		if ($rule==null || $rule == '') {
1029
+			// Empty rule is always true
992 1030
 		{
993 1031
 			return true;
994 1032
 		}
1033
+		}
995 1034
 		$matches=array();
996 1035
 		while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
997 1036
 		{
@@ -1078,20 +1117,17 @@  discard block
 block discarded – undo
1078 1117
 						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
1079 1118
 						{
1080 1119
 						    $this->trap_action.='Error sending status : check cmd/API';
1081
-						}
1082
-						else
1120
+						} else
1083 1121
 						{
1084 1122
 						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
1085 1123
 						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1086 1124
 						}
1087
-					}
1088
-					else
1125
+					} else
1089 1126
 					{
1090 1127
 						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1091 1128
 					}
1092 1129
 					$this->trap_to_db=($action==-2)?false:true;
1093
-				}
1094
-				else
1130
+				} else
1095 1131
 				{
1096 1132
 					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
1097 1133
 					
@@ -1102,14 +1138,12 @@  discard block
 block discarded – undo
1102 1138
 					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
1103 1139
 					    {
1104 1140
 					        $this->trap_action.='Error sending status : check cmd/API';
1105
-					    }
1106
-					    else
1141
+					    } else
1107 1142
 					    {
1108 1143
     						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1109 1144
     						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1110 1145
 					    }
1111
-					}
1112
-					else
1146
+					} else
1113 1147
 					{
1114 1148
 						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1115 1149
 					}
@@ -1119,16 +1153,14 @@  discard block
 block discarded – undo
1119 1153
 				if (!isset($this->trap_data['source_name']))
1120 1154
 				{
1121 1155
 					$this->trap_data['source_name']=$rule['host_name'];
1122
-				}
1123
-				else
1156
+				} else
1124 1157
 				{
1125 1158
 					if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
1126 1159
 					{ // only add if not present
1127 1160
 						$this->trap_data['source_name'].=','.$rule['host_name'];
1128 1161
 					}
1129 1162
 				}
1130
-			}
1131
-			catch (Exception $e) 
1163
+			} catch (Exception $e) 
1132 1164
 			{ 
1133 1165
 			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
1134 1166
 			    $this->trap_action.=' ERR : '.$e->getMessage();
@@ -1139,8 +1171,7 @@  discard block
 block discarded – undo
1139 1171
 		if ($this->trap_data['status']=='error')
1140 1172
 		{
1141 1173
 		  $this->trap_to_db=true; // Always put errors in DB for the use can see
1142
-		}
1143
-		else
1174
+		} else
1144 1175
 		{
1145 1176
 		  $this->trap_data['status']='done';
1146 1177
 		}
@@ -1195,8 +1226,7 @@  discard block
 block discarded – undo
1195 1226
                 if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
1196 1227
                 {
1197 1228
                     $cur_table='table '.$cur_table_array[1];
1198
-                }
1199
-                else
1229
+                } else
1200 1230
                 {
1201 1231
                     $cur_table='secret SQL stuff :-)';
1202 1232
                 }
@@ -1240,8 +1270,7 @@  discard block
 block discarded – undo
1240 1270
 	    if ($this->trapsDB->trapDBType == 'pgsql')
1241 1271
 	    {
1242 1272
 	        $prefix .= 'update_pgsql/schema_';
1243
-	    }
1244
-	    else
1273
+	    } else
1245 1274
 	    {
1246 1275
 	        $prefix .= 'update_sql/schema_';
1247 1276
 	    }
@@ -1287,7 +1316,10 @@  discard block
 block discarded – undo
1287 1316
 	       $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
1288 1317
 	       while (($line=fgets($input_stream)) !== false)
1289 1318
 	       {
1290
-	           if (preg_match('/^#/', $line)) continue; // ignore comment lines
1319
+	           if (preg_match('/^#/', $line)) {
1320
+	           	continue;
1321
+	           }
1322
+	           // ignore comment lines
1291 1323
 	           $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
1292 1324
 	           if (preg_match('/; *$/', $newline))
1293 1325
 	           {
@@ -1299,8 +1331,7 @@  discard block
 block discarded – undo
1299 1331
 	               if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
1300 1332
 	               {
1301 1333
 	                   $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
1302
-	               }
1303
-	               else
1334
+	               } else
1304 1335
 	               {
1305 1336
 	                   $cur_table='secret SQL stuff :-)';
1306 1337
 	                   //$cur_table=$newline;
@@ -1438,8 +1469,7 @@  discard block
 block discarded – undo
1438 1469
 			    }
1439 1470
 			    $this->logging->log('Trap updated : '.$name . ' / OID : '.$oid,DEBUG );
1440 1471
 				return 1;
1441
-			}
1442
-			else
1472
+			} else
1443 1473
 			{
1444 1474
 			    $this->logging->log('Trap unchanged : '.$name . ' / OID : '.$oid,DEBUG );
1445 1475
 			    return 0;
@@ -1455,7 +1485,9 @@  discard block
 block discarded – undo
1455 1485
               'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
1456 1486
               ', :syntax, :type_enum, :description )';
1457 1487
         
1458
-		if ($this->trapsDB->trapDBType == 'pgsql') $sql .= 'RETURNING id';
1488
+		if ($this->trapsDB->trapDBType == 'pgsql') {
1489
+			$sql .= 'RETURNING id';
1490
+		}
1459 1491
 		
1460 1492
 		$sqlQuery=$db_conn->prepare($sql);
1461 1493
 		
@@ -1495,7 +1527,9 @@  discard block
 block discarded – undo
1495 1527
 		        }
1496 1528
 		        
1497 1529
 		        $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
1498
-		        if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
1530
+		        if ($inserted_id==false) {
1531
+		        	throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
1532
+		        }
1499 1533
 		        $this->dbOidIndex[$oid]['id']=$inserted_id;
1500 1534
 		        break;
1501 1535
 		    default:
@@ -1748,12 +1782,14 @@  discard block
 block discarded – undo
1748 1782
 			$name=$match[1]; // Name 
1749 1783
 			$type=$match[2]; // type (21=trap, 0: may be trap, else : not trap
1750 1784
 			
1751
-			if ($type==0) // object type=0 : check if v1 trap
1785
+			if ($type==0) {
1786
+				// object type=0 : check if v1 trap
1752 1787
 			{
1753 1788
 				// Check if next is suboid -> in that case is cannot be a trap
1754 1789
 				if (preg_match("/^$oid/",$this->objectsAll[$curElement+1]))
1755 1790
 				{
1756 1791
 				    $time_check2 += microtime(true) - $time_1;
1792
+			}
1757 1793
 				    $time_check2N++;
1758 1794
 					continue;
1759 1795
 				}		
@@ -1770,9 +1806,11 @@  discard block
 block discarded – undo
1770 1806
 				// Force as trap.
1771 1807
 				$type=21;
1772 1808
 			}
1773
-			if ($onlyTraps===true && $type!=21) // if only traps and not a trap, continue
1809
+			if ($onlyTraps===true && $type!=21) {
1810
+				// if only traps and not a trap, continue
1774 1811
 			{
1775 1812
 			    $time_check3 += microtime(true) - $time_1;
1813
+			}
1776 1814
 				$time_check3N++;
1777 1815
 				continue;
1778 1816
 			}
@@ -1780,7 +1818,10 @@  discard block
 block discarded – undo
1780 1818
 			$time_num_traps++;
1781 1819
 			
1782 1820
 			$this->logging->log('Found trap : '.$match[1] . ' / OID : '.$oid,INFO );
1783
-			if ($display_progress) echo '#'; // echo a # when trap found
1821
+			if ($display_progress) {
1822
+				echo '#';
1823
+			}
1824
+			// echo a # when trap found
1784 1825
 				
1785 1826
 			// get trap objects & source MIB
1786 1827
 			unset($snmptrans);
@@ -1798,7 +1839,9 @@  discard block
 block discarded – undo
1798 1839
 			$trapMib=$match[1];
1799 1840
 			
1800 1841
 			$numLine=1;$trapDesc='';
1801
-			while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
1842
+			while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) {
1843
+				$numLine++;
1844
+			}
1802 1845
 			if (isset($snmptrans[$numLine]))
1803 1846
 			{
1804 1847
 			    $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
@@ -1820,7 +1863,9 @@  discard block
 block discarded – undo
1820 1863
 			if (($update==0) && ($check_change===false))
1821 1864
 			{ // Trapd didn't change & force check disabled
1822 1865
 			    $time_objects += microtime(true) - $time_1;
1823
-			    if ($display_progress) echo "C";
1866
+			    if ($display_progress) {
1867
+			    	echo "C";
1868
+			    }
1824 1869
 			    continue;
1825 1870
 			}
1826 1871
 			
Please login to merge, or discard this patch.
bin/trap_in.php 3 patches
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -15,12 +15,12 @@  discard block
 block discarded – undo
15 15
 
16 16
 try
17 17
 {
18
-    $Trap = new Trap($icingaweb2_etc,4,'syslog');
19
-    //$Trap = new Trap($icingaweb2_etc,4,'display'); // For debug
20
-    //$Trap->setLogging(4,'syslog'); 
18
+	$Trap = new Trap($icingaweb2_etc,4,'syslog');
19
+	//$Trap = new Trap($icingaweb2_etc,4,'display'); // For debug
20
+	//$Trap->setLogging(4,'syslog'); 
21 21
     
22
-    // TODO : tranfer this to reset_trap cli command
23
-    $Trap->eraseOldTraps();
22
+	// TODO : tranfer this to reset_trap cli command
23
+	$Trap->eraseOldTraps();
24 24
 
25 25
 	$Trap->read_trap('php://stdin');
26 26
 
@@ -33,15 +33,15 @@  discard block
 block discarded – undo
33 33
 }
34 34
 catch (Exception $e) 
35 35
 {
36
-    if ($Trap == null)
37
-    {  // Exception in trap creation : log in display & syslog
38
-        $logging = new Logging();
39
-        $logging->log("Caught exception creating Trap class",2);
40
-    }
41
-    else
42
-    {
36
+	if ($Trap == null)
37
+	{  // Exception in trap creation : log in display & syslog
38
+		$logging = new Logging();
39
+		$logging->log("Caught exception creating Trap class",2);
40
+	}
41
+	else
42
+	{
43 43
 	   $Trap->trapLog("Exception : ". $e->getMessage(),2,0);
44
-    }
44
+	}
45 45
 }
46 46
 
47 47
 //end
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 use Trapdirector\Logging;
4 4
 
5 5
 // start
6
-$time1 = microtime(true);
6
+$time1=microtime(true);
7 7
 
8 8
 require_once ('trap_class.php');
9 9
 
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
 
16 16
 try
17 17
 {
18
-    $Trap = new Trap($icingaweb2_etc,4,'syslog');
18
+    $Trap=new Trap($icingaweb2_etc, 4, 'syslog');
19 19
     //$Trap = new Trap($icingaweb2_etc,4,'display'); // For debug
20 20
     //$Trap->setLogging(4,'syslog'); 
21 21
     
@@ -35,12 +35,12 @@  discard block
 block discarded – undo
35 35
 {
36 36
     if ($Trap == null)
37 37
     {  // Exception in trap creation : log in display & syslog
38
-        $logging = new Logging();
39
-        $logging->log("Caught exception creating Trap class",2);
38
+        $logging=new Logging();
39
+        $logging->log("Caught exception creating Trap class", 2);
40 40
     }
41 41
     else
42 42
     {
43
-	   $Trap->trapLog("Exception : ". $e->getMessage(),2,0);
43
+	   $Trap->trapLog("Exception : ".$e->getMessage(), 2, 0);
44 44
     }
45 45
 }
46 46
 
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -30,15 +30,13 @@
 block discarded – undo
30 30
 
31 31
 	$Trap->add_rule_final(microtime(true) - $time1);
32 32
 	
33
-}
34
-catch (Exception $e) 
33
+} catch (Exception $e) 
35 34
 {
36 35
     if ($Trap == null)
37 36
     {  // Exception in trap creation : log in display & syslog
38 37
         $logging = new Logging();
39 38
         $logging->log("Caught exception creating Trap class",2);
40
-    }
41
-    else
39
+    } else
42 40
     {
43 41
 	   $Trap->trapLog("Exception : ". $e->getMessage(),2,0);
44 42
     }
Please login to merge, or discard this patch.
library/Trapdirector/TrapsController.php 3 patches
Indentation   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -32,8 +32,8 @@  discard block
 block discarded – undo
32 32
 	protected $trapClass;		//< Trap class for bin/trap_class.php
33 33
 		
34 34
 	/** Get instance of TrapModuleConfig class
35
-	*	@return TrapModuleConfig
36
-	*/
35
+	 *	@return TrapModuleConfig
36
+	 */
37 37
 	public function getModuleConfig() 
38 38
 	{
39 39
 		if ($this->moduleConfig == Null) 
@@ -58,12 +58,12 @@  discard block
 block discarded – undo
58 58
 	
59 59
 	public function getTrapHostListTable()
60 60
 	{
61
-	    if ($this->trapTableHostList == Null) 
61
+		if ($this->trapTableHostList == Null) 
62 62
 		{
63
-	        $this->trapTableHostList = new TrapTableHostList();
64
-	        $this->trapTableHostList->setConfig($this->getModuleConfig());
65
-	    }
66
-	    return $this->trapTableHostList;
63
+			$this->trapTableHostList = new TrapTableHostList();
64
+			$this->trapTableHostList->setConfig($this->getModuleConfig());
65
+		}
66
+		return $this->trapTableHostList;
67 67
 	}
68 68
 	
69 69
 	public function getHandlerListTable() 
@@ -77,11 +77,11 @@  discard block
 block discarded – undo
77 77
 	}	
78 78
 	
79 79
 	/**	Get Database connexion
80
-	*	@param $DBname string DB name in resource.ini_ge
81
-	*	@param $test bool if set to true, returns error code and not database
82
-	*	@param $test_version bool if set to flase, does not test database version of trapDB
83
-	*	@return array<integer,mixed>|mixed : if test=false, returns DB connexion, else array(error_num,message) or null on error.
84
-	*/
80
+	 *	@param $DBname string DB name in resource.ini_ge
81
+	 *	@param $test bool if set to true, returns error code and not database
82
+	 *	@param $test_version bool if set to flase, does not test database version of trapDB
83
+	 *	@return array<integer,mixed>|mixed : if test=false, returns DB connexion, else array(error_num,message) or null on error.
84
+	 */
85 85
 	public function getDbByName($DBname,$test=false,$test_version=true)
86 86
 	{
87 87
 		try 
@@ -166,20 +166,20 @@  discard block
 block discarded – undo
166 166
 
167 167
 		if ( ! $dbresource )
168 168
 		{
169
-		    if ($test) return array(1,'No database in config.ini');
170
-		    $this->redirectNow('trapdirector/settings?idodberror=1');
171
-		    return null;
169
+			if ($test) return array(1,'No database in config.ini');
170
+			$this->redirectNow('trapdirector/settings?idodberror=1');
171
+			return null;
172 172
 		}
173 173
 		
174 174
 		try
175 175
 		{
176
-		    $dbconn = IcingaDbConnection::fromResourceName($dbresource);
176
+			$dbconn = IcingaDbConnection::fromResourceName($dbresource);
177 177
 		}
178 178
 		catch (Exception $e)
179 179
 		{
180
-		    if ($test) return array(2,"Database $dbresource does not exists in IcingaWeb2");
181
-		    $this->redirectNow('trapdirector/settings?idodberror=2');
182
-		    return null;
180
+			if ($test) return array(2,"Database $dbresource does not exists in IcingaWeb2");
181
+			$this->redirectNow('trapdirector/settings?idodberror=2');
182
+			return null;
183 183
 		}
184 184
 		
185 185
 		if ($test == false) 
@@ -190,13 +190,13 @@  discard block
 block discarded – undo
190 190
 		
191 191
 		try
192 192
 		{
193
-		    $query = $dbconn->select()
194
-		    ->from('icinga_dbversion',array('version'));
195
-		    $version=$dbconn->fetchRow($query);
196
-		    if ( ($version == null) || ! property_exists($version,'version') )
197
-		    {
198
-		        return array(4,"$dbresource does not look like an IDO database");
199
-		    }
193
+			$query = $dbconn->select()
194
+			->from('icinga_dbversion',array('version'));
195
+			$version=$dbconn->fetchRow($query);
196
+			if ( ($version == null) || ! property_exists($version,'version') )
197
+			{
198
+				return array(4,"$dbresource does not look like an IDO database");
199
+			}
200 200
 		}
201 201
 		catch (Exception $e)
202 202
 		{
@@ -206,15 +206,15 @@  discard block
 block discarded – undo
206 206
 		return array(0,'');
207 207
 	}
208 208
 	
209
-    protected function applyPaginationLimits(Paginatable $paginatable, $limit = 25, $offset = null)
210
-    {
211
-        $limit = $this->params->get('limit', $limit);
212
-        $page = $this->params->get('page', $offset);
209
+	protected function applyPaginationLimits(Paginatable $paginatable, $limit = 25, $offset = null)
210
+	{
211
+		$limit = $this->params->get('limit', $limit);
212
+		$page = $this->params->get('page', $offset);
213 213
 
214
-        $paginatable->limit($limit, $page > 0 ? ($page - 1) * $limit : 0);
214
+		$paginatable->limit($limit, $page > 0 ? ($page - 1) * $limit : 0);
215 215
 
216
-        return $paginatable;
217
-    }	
216
+		return $paginatable;
217
+	}	
218 218
 	
219 219
 	public function displayExitError($source,$message)
220 220
 	{	// TODO : check better ways to transmit data (with POST ?)
@@ -223,33 +223,33 @@  discard block
 block discarded – undo
223 223
 	
224 224
 	protected function checkReadPermission()
225 225
 	{
226
-        if (! $this->Auth()->hasPermission('trapdirector/view')) {
227
-            $this->displayExitError('Permissions','No permission fo view content');
228
-        }		
226
+		if (! $this->Auth()->hasPermission('trapdirector/view')) {
227
+			$this->displayExitError('Permissions','No permission fo view content');
228
+		}		
229 229
 	}
230 230
 
231 231
 	protected function checkConfigPermission()
232 232
 	{
233
-        if (! $this->Auth()->hasPermission('trapdirector/config')) {
234
-            $this->displayExitError('Permissions','No permission fo configure');
235
-        }		
233
+		if (! $this->Auth()->hasPermission('trapdirector/config')) {
234
+			$this->displayExitError('Permissions','No permission fo configure');
235
+		}		
236 236
 	}
237 237
 	
238
-    /**
239
-     * Check if user has write permission
240
-     * @param number $check optional : if set to 1, return true (user has permission) or false instead of displaying error page
241
-     * @return boolean : user has permission
242
-     */
238
+	/**
239
+	 * Check if user has write permission
240
+	 * @param number $check optional : if set to 1, return true (user has permission) or false instead of displaying error page
241
+	 * @return boolean : user has permission
242
+	 */
243 243
 	protected function checkModuleConfigPermission($check=0)
244 244
 	{
245
-        if (! $this->Auth()->hasPermission('trapdirector/module_config')) {
246
-            if ($check == 0)
247
-            {
248
-                $this->displayExitError('Permissions','No permission fo configure module');
249
-            }
250
-            return false;
251
-        }
252
-        return true;
245
+		if (! $this->Auth()->hasPermission('trapdirector/module_config')) {
246
+			if ($check == 0)
247
+			{
248
+				$this->displayExitError('Permissions','No permission fo configure module');
249
+			}
250
+			return false;
251
+		}
252
+		return true;
253 253
 	}
254 254
 
255 255
 	/*************************  Trap class get **********************/
@@ -269,8 +269,8 @@  discard block
 block discarded – undo
269 269
 	/************************** MIB related **************************/
270 270
 	
271 271
 	/** Get MIBLoader class
272
-	*	@return MIBLoader class
273
-	*/
272
+	 *	@return MIBLoader class
273
+	 */
274 274
 	protected function getMIB()
275 275
 	{
276 276
 		if ($this->MIBData == null)
@@ -288,9 +288,9 @@  discard block
 block discarded – undo
288 288
 	/**************************  Database queries *******************/
289 289
 	
290 290
 	/** Get host(s) by IP (v4 or v6) or by name in IDO database
291
-	*	does not catch exceptions
292
-	*	@return array of objects ( name, id (object_id), display_name)
293
-	*/
291
+	 *	does not catch exceptions
292
+	 *	@return array of objects ( name, id (object_id), display_name)
293
+	 */
294 294
 	protected function getHostByIP($ip) 
295 295
 	{
296 296
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -309,9 +309,9 @@  discard block
 block discarded – undo
309 309
 	}
310 310
 
311 311
 	/** Get host(s) by name in IDO database
312
-	*	does not catch exceptions
313
-	*	@return array of objects ( name, id (object_id), display_name)
314
-	*/
312
+	 *	does not catch exceptions
313
+	 *	@return array of objects ( name, id (object_id), display_name)
314
+	 */
315 315
 	protected function getHostByName($name) 
316 316
 	{
317 317
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -330,9 +330,9 @@  discard block
 block discarded – undo
330 330
 	}	
331 331
 	
332 332
 	/** Get host groups by  name in IDO database
333
-	*	does not catch exceptions
334
-	*	@return array of objects ( name, id (object_id), display_name)
335
-	*/
333
+	 *	does not catch exceptions
334
+	 *	@return array of objects ( name, id (object_id), display_name)
335
+	 */
336 336
 	protected function getHostGroupByName($ip) 
337 337
 	{
338 338
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -352,9 +352,9 @@  discard block
 block discarded – undo
352 352
 
353 353
 	
354 354
 	/** Get host IP (v4 and v6) by name in IDO database
355
-	*	does not catch exceptions
356
-	*	@return array ( name, display_name, ip4, ip6)
357
-	*/
355
+	 *	does not catch exceptions
356
+	 *	@return array ( name, display_name, ip4, ip6)
357
+	 */
358 358
 	protected function getHostInfoByID($id) 
359 359
 	{
360 360
 		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
@@ -373,9 +373,9 @@  discard block
 block discarded – undo
373 373
 
374 374
 	
375 375
 	/** Get host by objectid  in IDO database
376
-	*	does not catch exceptions
377
-	*	@return array of objects ( id, name, display_name, ip, ip6,  )
378
-	*/
376
+	 *	does not catch exceptions
377
+	 *	@return array of objects ( id, name, display_name, ip, ip6,  )
378
+	 */
379 379
 	protected function getHostByObjectID($id) // TODO : duplicate of getHostInfoByID above
380 380
 	{
381 381
 		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
@@ -393,10 +393,10 @@  discard block
 block discarded – undo
393 393
 	}	
394 394
 	
395 395
 	/** Get services from object ( host_object_id) in IDO database
396
-	*	does not catch exceptions
397
-	*	@param $id	int object_id
398
-	*	@return array display_name (of service), service_object_id
399
-	*/
396
+	 *	does not catch exceptions
397
+	 *	@param $id	int object_id
398
+	 *	@return array display_name (of service), service_object_id
399
+	 */
400 400
 	protected function getServicesByHostid($id) 
401 401
 	{
402 402
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -416,11 +416,11 @@  discard block
 block discarded – undo
416 416
 	}	
417 417
 	
418 418
 	/** Get services from hostgroup object id ( hostgroup_object_id) in IDO database
419
-	* 	gets all hosts in hostgroup and return common services
420
-	*	does not catch exceptions
421
-	*	@param $id	int object_id
422
-	*	@return array display_name (of service), service_object_id
423
-	*/
419
+	 * 	gets all hosts in hostgroup and return common services
420
+	 *	does not catch exceptions
421
+	 *	@param $id	int object_id
422
+	 *	@return array display_name (of service), service_object_id
423
+	 */
424 424
 	protected function getServicesByHostGroupid($id) 
425 425
 	{		
426 426
 		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
 		//print_r($common_services);
460 460
 		foreach (array_keys($common_services) as $key)
461 461
 		{
462
-		    if ($common_services[$key]['num'] == $num_hosts)
462
+			if ($common_services[$key]['num'] == $num_hosts)
463 463
 			{
464 464
 				array_push($result,array($key,$common_services[$key]['name']));
465 465
 			}
@@ -469,11 +469,11 @@  discard block
 block discarded – undo
469 469
 	}	
470 470
 
471 471
 	/** Get services object id by host name / service name in IDO database
472
-	*	does not catch exceptions
473
-	*	@param $hostname string host name
474
-	*	@param $name string service name
475
-	*	@return array  service id
476
-	*/
472
+	 *	does not catch exceptions
473
+	 *	@param $hostname string host name
474
+	 *	@param $name string service name
475
+	 *	@return array  service id
476
+	 */
477 477
 	protected function getServiceIDByName($hostname,$name) 
478 478
 	{
479 479
 		$db = $this->getIdoDb()->getConnection();
@@ -496,10 +496,10 @@  discard block
 block discarded – undo
496 496
 	}
497 497
 	
498 498
 	/** Get object name from object_id  in IDO database
499
-	*	does not catch exceptions
500
-	*	@param int $id object_id (default to null, used first if not null)
501
-	*	@return array name1 (host) name2 (service)
502
-	*/
499
+	 *	does not catch exceptions
500
+	 *	@param int $id object_id (default to null, used first if not null)
501
+	 *	@return array name1 (host) name2 (service)
502
+	 */
503 503
 	protected function getObjectNameByid($id) 
504 504
 	{
505 505
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -515,9 +515,9 @@  discard block
 block discarded – undo
515 515
 	}		
516 516
 
517 517
 	/** Add handler rule in traps DB
518
-	*	@param array $params : array(<db item>=><value>)
519
-	*	@return int inserted id
520
-	*/
518
+	 *	@param array $params : array(<db item>=><value>)
519
+	 *	@return int inserted id
520
+	 */
521 521
 	protected function addHandlerRule($params)
522 522
 	{
523 523
 		// TODO Check for rule consistency
@@ -539,9 +539,9 @@  discard block
 block discarded – undo
539 539
 	}	
540 540
 
541 541
 	/** Update handler rule in traps DB
542
-	*	@param array(<db item>=><value>)
543
-	*	@return array affected rows
544
-	*/
542
+	 *	@param array(<db item>=><value>)
543
+	 *	@return array affected rows
544
+	 */
545 545
 	protected function updateHandlerRule($params,$ruleID)
546 546
 	{
547 547
 		// TODO Check for rule consistency
@@ -559,8 +559,8 @@  discard block
 block discarded – undo
559 559
 	}	
560 560
 	
561 561
 	/** Delete rule by id
562
-	*	@param int $ruleID rule id
563
-	*/
562
+	 *	@param int $ruleID rule id
563
+	 */
564 564
 	protected function deleteRule($ruleID)
565 565
 	{
566 566
 		if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
@@ -574,9 +574,9 @@  discard block
 block discarded – undo
574 574
 	}
575 575
 
576 576
 	/** Delete trap by ip & oid
577
-	*	@param $ip string source IP (v4 or v6)
578
-	*	@param $oid string oid
579
-	*/
577
+	 *	@param $ip string source IP (v4 or v6)
578
+	 *	@param $oid string oid
579
+	 */
580 580
 	protected function deleteTrap($ip,$oid)
581 581
 	{
582 582
 		
@@ -602,9 +602,9 @@  discard block
 block discarded – undo
602 602
    
603 603
 
604 604
 	/** count trap by ip & oid
605
-	*	@param $ip string source IP (v4 or v6)
606
-	*	@param $oid string oid
607
-	*/
605
+	 *	@param $ip string source IP (v4 or v6)
606
+	 *	@param $oid string oid
607
+	 */
608 608
 	protected function countTrap($ip,$oid)
609 609
 	{
610 610
 		
@@ -630,8 +630,8 @@  discard block
 block discarded – undo
630 630
 	}		
631 631
 	
632 632
 	/** get configuration value
633
-	*	@param string $element : configuration name in db
634
-	*/
633
+	 *	@param string $element : configuration name in db
634
+	 */
635 635
 	protected function getDBConfigValue($element)
636 636
 	{
637 637
 	
@@ -662,9 +662,9 @@  discard block
 block discarded – undo
662 662
 	}
663 663
 
664 664
 	/** add configuration value
665
-	*	@param string $element : name of config element
666
-	*   @param string $value : value
667
-	*/
665
+	 *	@param string $element : name of config element
666
+	 *   @param string $value : value
667
+	 */
668 668
 		
669 669
 	protected function addDBConfigValue($element,$value)
670 670
 	{
@@ -682,9 +682,9 @@  discard block
 block discarded – undo
682 682
 	}
683 683
 
684 684
 	/** set configuration value
685
-	*	@param string $element : name of config element
686
-	*   @param string $value : value
687
-	*/
685
+	 *	@param string $element : name of config element
686
+	 *   @param string $value : value
687
+	 */
688 688
 	protected function setDBConfigValue($element,$value)
689 689
 	{
690 690
 	
@@ -698,13 +698,13 @@  discard block
 block discarded – undo
698 698
 	}
699 699
 	
700 700
 	/** Check if director is installed
701
-	*	@return bool true/false
702
-	*/
701
+	 *	@return bool true/false
702
+	 */
703 703
 	protected function isDirectorInstalled()
704 704
 	{
705
-	    $output=array();
706
-	    exec('icingacli module list',$output);
707
-	    foreach ($output as $line)
705
+		$output=array();
706
+		exec('icingacli module list',$output);
707
+		foreach ($output as $line)
708 708
 		{
709 709
 			if (preg_match('/^director .*enabled/',$line))
710 710
 			{
Please login to merge, or discard this patch.
Spacing   +112 added lines, -112 removed lines patch added patch discarded remove patch
@@ -22,14 +22,14 @@  discard block
 block discarded – undo
22 22
 
23 23
 class TrapsController extends Controller
24 24
 {
25
-	protected $moduleConfig;  	//< TrapModuleConfig instance
26
-	protected $trapTableList; 	//< TrapTableList (by date)
27
-	protected $trapTableHostList; 	//< TrapTableList (by hosts)
28
-	protected $handlerTableList; 	//< HandlerTableList instance
29
-	protected $trapDB;			//< Trap database
30
-	protected $icingaDB;		//< Icinga IDO database;
31
-	protected $MIBData; 		//< MIBLoader class
32
-	protected $trapClass;		//< Trap class for bin/trap_class.php
25
+	protected $moduleConfig; //< TrapModuleConfig instance
26
+	protected $trapTableList; //< TrapTableList (by date)
27
+	protected $trapTableHostList; //< TrapTableList (by hosts)
28
+	protected $handlerTableList; //< HandlerTableList instance
29
+	protected $trapDB; //< Trap database
30
+	protected $icingaDB; //< Icinga IDO database;
31
+	protected $MIBData; //< MIBLoader class
32
+	protected $trapClass; //< Trap class for bin/trap_class.php
33 33
 		
34 34
 	/** Get instance of TrapModuleConfig class
35 35
 	*	@return TrapModuleConfig
@@ -43,14 +43,14 @@  discard block
 block discarded – undo
43 43
 			{
44 44
 				$this->redirectNow('trapdirector/settings?message=No database prefix');
45 45
 			}
46
-			$this->moduleConfig = new TrapModuleConfig($db_prefix);
46
+			$this->moduleConfig=new TrapModuleConfig($db_prefix);
47 47
 		}
48 48
 		return $this->moduleConfig;
49 49
 	}
50 50
 	
51 51
 	public function getTrapListTable() {
52 52
 		if ($this->trapTableList == Null) {
53
-			$this->trapTableList = new TrapTableList();
53
+			$this->trapTableList=new TrapTableList();
54 54
 			$this->trapTableList->setConfig($this->getModuleConfig());
55 55
 		}
56 56
 		return $this->trapTableList;
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 	{
61 61
 	    if ($this->trapTableHostList == Null) 
62 62
 		{
63
-	        $this->trapTableHostList = new TrapTableHostList();
63
+	        $this->trapTableHostList=new TrapTableHostList();
64 64
 	        $this->trapTableHostList->setConfig($this->getModuleConfig());
65 65
 	    }
66 66
 	    return $this->trapTableHostList;
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 	{
71 71
 		if ($this->handlerTableList == Null) 
72 72
 		{
73
-			$this->handlerTableList = new HandlerTableList();
73
+			$this->handlerTableList=new HandlerTableList();
74 74
 			$this->handlerTableList->setConfig($this->getModuleConfig());
75 75
 		}
76 76
 		return $this->handlerTableList;
@@ -82,15 +82,15 @@  discard block
 block discarded – undo
82 82
 	*	@param $test_version bool if set to flase, does not test database version of trapDB
83 83
 	*	@return array<integer,mixed>|mixed : if test=false, returns DB connexion, else array(error_num,message) or null on error.
84 84
 	*/
85
-	public function getDbByName($DBname,$test=false,$test_version=true)
85
+	public function getDbByName($DBname, $test=false, $test_version=true)
86 86
 	{
87 87
 		try 
88 88
 		{
89
-			$dbconn = IcingaDbConnection::fromResourceName($DBname);
89
+			$dbconn=IcingaDbConnection::fromResourceName($DBname);
90 90
 		} 
91 91
 		catch (Exception $e)
92 92
 		{
93
-			if ($test) return array(2,$DBname);
93
+			if ($test) return array(2, $DBname);
94 94
 			$this->redirectNow('trapdirector/settings?dberror=2');
95 95
 			return null;
96 96
 		}
@@ -101,37 +101,37 @@  discard block
 block discarded – undo
101 101
 			}
102 102
 			catch (Exception $e) 
103 103
 			{
104
-				if ($test) return array(3,$DBname,$e->getMessage());
104
+				if ($test) return array(3, $DBname, $e->getMessage());
105 105
 				$this->redirectNow('trapdirector/settings?dberror=3');
106 106
 				return null;
107 107
 			}
108 108
 			try
109 109
 			{
110
-				$query = $db->select()
111
-					->from($this->getModuleConfig()->getDbConfigTableName(),'value')
110
+				$query=$db->select()
111
+					->from($this->getModuleConfig()->getDbConfigTableName(), 'value')
112 112
 					->where('name=\'db_version\'');
113 113
 				$version=$db->fetchRow($query);
114
-				if ( ($version == null) || ! property_exists($version,'value') )
114
+				if (($version == null) || !property_exists($version, 'value'))
115 115
 				{
116
-					if ($test) return array(4,$DBname);
116
+					if ($test) return array(4, $DBname);
117 117
 					$this->redirectNow('trapdirector/settings?dberror=4');
118 118
 					return null;
119 119
 				}
120 120
 				if ($version->value < $this->getModuleConfig()->getDbMinVersion()) 
121 121
 				{
122
-					if ($test) return array(5,$version->value,$this->getModuleConfig()->getDbMinVersion());
122
+					if ($test) return array(5, $version->value, $this->getModuleConfig()->getDbMinVersion());
123 123
 					$this->redirectNow('trapdirector/settings?dberror=5');
124 124
 					return null;
125 125
 				}
126 126
 			}
127 127
 			catch (Exception $e) 
128 128
 			{
129
-				if ($test) return array(3,$DBname,$e->getMessage());
129
+				if ($test) return array(3, $DBname, $e->getMessage());
130 130
 				$this->redirectNow('trapdirector/settings?dberror=4');
131 131
 				return null;
132 132
 			}
133 133
 		}
134
-		if ($test) return array(0,'');
134
+		if ($test) return array(0, '');
135 135
 		return $dbconn;
136 136
 	}
137 137
 
@@ -142,17 +142,17 @@  discard block
 block discarded – undo
142 142
 	 */
143 143
 	public function getDb($test=false)
144 144
 	{
145
-		if ($this->trapDB != null && $test = false) return $this->trapDB;
145
+		if ($this->trapDB != null && $test=false) return $this->trapDB;
146 146
 		
147 147
 		$dbresource=$this->Config()->get('config', 'database');
148 148
 		
149
-		if ( ! $dbresource )
149
+		if (!$dbresource)
150 150
 		{	
151
-			if ($test) return array(1,'');
151
+			if ($test) return array(1, '');
152 152
 			$this->redirectNow('trapdirector/settings?dberror=1');
153 153
 			return null;
154 154
 		}
155
-		$retDB=$this->getDbByName($dbresource,$test,true);
155
+		$retDB=$this->getDbByName($dbresource, $test, true);
156 156
 		if ($test == true) return $retDB;
157 157
 		$this->trapDB=$retDB;
158 158
 		return $this->trapDB;
@@ -160,78 +160,78 @@  discard block
 block discarded – undo
160 160
 	
161 161
 	public function getIdoDb($test=false)
162 162
 	{
163
-		if ($this->icingaDB != null && $test = false) return $this->icingaDB;
163
+		if ($this->icingaDB != null && $test=false) return $this->icingaDB;
164 164
 		// TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
165
-		$dbresource=$this->Config()->get('config', 'IDOdatabase');;
165
+		$dbresource=$this->Config()->get('config', 'IDOdatabase'); ;
166 166
 
167
-		if ( ! $dbresource )
167
+		if (!$dbresource)
168 168
 		{
169
-		    if ($test) return array(1,'No database in config.ini');
169
+		    if ($test) return array(1, 'No database in config.ini');
170 170
 		    $this->redirectNow('trapdirector/settings?idodberror=1');
171 171
 		    return null;
172 172
 		}
173 173
 		
174 174
 		try
175 175
 		{
176
-		    $dbconn = IcingaDbConnection::fromResourceName($dbresource);
176
+		    $dbconn=IcingaDbConnection::fromResourceName($dbresource);
177 177
 		}
178 178
 		catch (Exception $e)
179 179
 		{
180
-		    if ($test) return array(2,"Database $dbresource does not exists in IcingaWeb2");
180
+		    if ($test) return array(2, "Database $dbresource does not exists in IcingaWeb2");
181 181
 		    $this->redirectNow('trapdirector/settings?idodberror=2');
182 182
 		    return null;
183 183
 		}
184 184
 		
185 185
 		if ($test == false) 
186 186
 		{ 
187
-			$this->icingaDB = $dbconn; 
187
+			$this->icingaDB=$dbconn; 
188 188
 			return $this->icingaDB;
189 189
 		}
190 190
 		
191 191
 		try
192 192
 		{
193
-		    $query = $dbconn->select()
194
-		    ->from('icinga_dbversion',array('version'));
193
+		    $query=$dbconn->select()
194
+		    ->from('icinga_dbversion', array('version'));
195 195
 		    $version=$dbconn->fetchRow($query);
196
-		    if ( ($version == null) || ! property_exists($version,'version') )
196
+		    if (($version == null) || !property_exists($version, 'version'))
197 197
 		    {
198
-		        return array(4,"$dbresource does not look like an IDO database");
198
+		        return array(4, "$dbresource does not look like an IDO database");
199 199
 		    }
200 200
 		}
201 201
 		catch (Exception $e)
202 202
 		{
203
-			return array(3,"Error connecting to $dbresource : " . $e->getMessage());
203
+			return array(3, "Error connecting to $dbresource : ".$e->getMessage());
204 204
 		}
205 205
 		
206
-		return array(0,'');
206
+		return array(0, '');
207 207
 	}
208 208
 	
209
-    protected function applyPaginationLimits(Paginatable $paginatable, $limit = 25, $offset = null)
209
+    protected function applyPaginationLimits(Paginatable $paginatable, $limit=25, $offset=null)
210 210
     {
211
-        $limit = $this->params->get('limit', $limit);
212
-        $page = $this->params->get('page', $offset);
211
+        $limit=$this->params->get('limit', $limit);
212
+        $page=$this->params->get('page', $offset);
213 213
 
214 214
         $paginatable->limit($limit, $page > 0 ? ($page - 1) * $limit : 0);
215 215
 
216 216
         return $paginatable;
217 217
     }	
218 218
 	
219
-	public function displayExitError($source,$message)
219
+	public function displayExitError($source, $message)
220 220
 	{	// TODO : check better ways to transmit data (with POST ?)
221 221
 		$this->redirectNow('trapdirector/error?source='.$source.'&message='.$message);
222 222
 	}
223 223
 	
224 224
 	protected function checkReadPermission()
225 225
 	{
226
-        if (! $this->Auth()->hasPermission('trapdirector/view')) {
227
-            $this->displayExitError('Permissions','No permission fo view content');
226
+        if (!$this->Auth()->hasPermission('trapdirector/view')) {
227
+            $this->displayExitError('Permissions', 'No permission fo view content');
228 228
         }		
229 229
 	}
230 230
 
231 231
 	protected function checkConfigPermission()
232 232
 	{
233
-        if (! $this->Auth()->hasPermission('trapdirector/config')) {
234
-            $this->displayExitError('Permissions','No permission fo configure');
233
+        if (!$this->Auth()->hasPermission('trapdirector/config')) {
234
+            $this->displayExitError('Permissions', 'No permission fo configure');
235 235
         }		
236 236
 	}
237 237
 	
@@ -242,10 +242,10 @@  discard block
 block discarded – undo
242 242
      */
243 243
 	protected function checkModuleConfigPermission($check=0)
244 244
 	{
245
-        if (! $this->Auth()->hasPermission('trapdirector/module_config')) {
245
+        if (!$this->Auth()->hasPermission('trapdirector/module_config')) {
246 246
             if ($check == 0)
247 247
             {
248
-                $this->displayExitError('Permissions','No permission fo configure module');
248
+                $this->displayExitError('Permissions', 'No permission fo configure module');
249 249
             }
250 250
             return false;
251 251
         }
@@ -257,10 +257,10 @@  discard block
 block discarded – undo
257 257
 	{ // TODO : try/catch here ? or within caller
258 258
 		if ($this->trapClass == null)
259 259
 		{
260
-			require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
260
+			require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
261 261
 			$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
262 262
 			//$debug_level=4;
263
-			$this->trapClass = new Trap($icingaweb2_etc);
263
+			$this->trapClass=new Trap($icingaweb2_etc);
264 264
 			//$Trap->setLogging($debug_level,'syslog');
265 265
 		}
266 266
 		return $this->trapClass;
@@ -294,12 +294,12 @@  discard block
 block discarded – undo
294 294
 	protected function getHostByIP($ip) 
295 295
 	{
296 296
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
297
-		$db = $this->getIdoDb()->getConnection();
297
+		$db=$this->getIdoDb()->getConnection();
298 298
 		// TODO : check for SQL injections
299 299
 		$query=$db->select()
300 300
 				->from(
301 301
 					array('a' => 'icinga_objects'),
302
-					array('name' => 'a.name1','id' => 'object_id'))
302
+					array('name' => 'a.name1', 'id' => 'object_id'))
303 303
 				->join(
304 304
 					array('b' => 'icinga_hosts'),
305 305
 					'b.host_object_id=a.object_id',
@@ -315,12 +315,12 @@  discard block
 block discarded – undo
315 315
 	protected function getHostByName($name) 
316 316
 	{
317 317
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
318
-		$db = $this->getIdoDb()->getConnection();
318
+		$db=$this->getIdoDb()->getConnection();
319 319
 		// TODO : check for SQL injections
320 320
 		$query=$db->select()
321 321
 				->from(
322 322
 					array('a' => 'icinga_objects'),
323
-					array('name' => 'a.name1','id' => 'object_id'))
323
+					array('name' => 'a.name1', 'id' => 'object_id'))
324 324
 				->join(
325 325
 					array('b' => 'icinga_hosts'),
326 326
 					'b.host_object_id=a.object_id',
@@ -336,12 +336,12 @@  discard block
 block discarded – undo
336 336
 	protected function getHostGroupByName($ip) 
337 337
 	{
338 338
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
339
-		$db = $this->getIdoDb()->getConnection();
339
+		$db=$this->getIdoDb()->getConnection();
340 340
 		// TODO : check for SQL injections
341 341
 		$query=$db->select()
342 342
 				->from(
343 343
 					array('a' => 'icinga_objects'),
344
-					array('name' => 'a.name1','id' => 'object_id'))
344
+					array('name' => 'a.name1', 'id' => 'object_id'))
345 345
 				->join(
346 346
 					array('b' => 'icinga_hostgroups'),
347 347
 					'b.hostgroup_object_id=a.object_id',
@@ -357,8 +357,8 @@  discard block
 block discarded – undo
357 357
 	*/
358 358
 	protected function getHostInfoByID($id) 
359 359
 	{
360
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
361
-		$db = $this->getIdoDb()->getConnection();
360
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
361
+		$db=$this->getIdoDb()->getConnection();
362 362
 		$query=$db->select()
363 363
 				->from(
364 364
 					array('a' => 'icinga_objects'),
@@ -378,17 +378,17 @@  discard block
 block discarded – undo
378 378
 	*/
379 379
 	protected function getHostByObjectID($id) // TODO : duplicate of getHostInfoByID above
380 380
 	{
381
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
382
-		$db = $this->getIdoDb()->getConnection();
381
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
382
+		$db=$this->getIdoDb()->getConnection();
383 383
 		$query=$db->select()
384 384
 				->from(
385 385
 					array('a' => 'icinga_objects'),
386
-					array('name' => 'a.name1','id' => 'a.object_id'))
386
+					array('name' => 'a.name1', 'id' => 'a.object_id'))
387 387
 				->join(
388 388
 					array('b' => 'icinga_hosts'),
389 389
 					'b.host_object_id=a.object_id',
390
-					array('display_name' => 'b.display_name' , 'ip' => 'b.address', 'ip6' => 'b.address6'))
391
-				->where('a.object_id = ?',$id);
390
+					array('display_name' => 'b.display_name', 'ip' => 'b.address', 'ip6' => 'b.address6'))
391
+				->where('a.object_id = ?', $id);
392 392
 		return $db->fetchRow($query);
393 393
 	}	
394 394
 	
@@ -400,16 +400,16 @@  discard block
 block discarded – undo
400 400
 	protected function getServicesByHostid($id) 
401 401
 	{
402 402
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
403
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
404
-		$db = $this->getIdoDb()->getConnection();
403
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
404
+		$db=$this->getIdoDb()->getConnection();
405 405
 		$query=$db->select()
406 406
 				->from(
407 407
 					array('s' => 'icinga_services'),
408
-					array('name' => 's.display_name','id' => 's.service_object_id'))
408
+					array('name' => 's.display_name', 'id' => 's.service_object_id'))
409 409
 				->join(
410 410
 					array('a' => 'icinga_objects'),
411 411
 					's.service_object_id=a.object_id',
412
-					array('is_active'=>'a.is_active','name2'=>'a.name2'))
412
+					array('is_active'=>'a.is_active', 'name2'=>'a.name2'))
413 413
 				->where('s.host_object_id='.$id.' AND a.is_active = 1');
414 414
 
415 415
 		return $db->fetchAll($query);
@@ -423,8 +423,8 @@  discard block
 block discarded – undo
423 423
 	*/
424 424
 	protected function getServicesByHostGroupid($id) 
425 425
 	{		
426
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
427
-		$db = $this->getIdoDb()->getConnection();
426
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
427
+		$db=$this->getIdoDb()->getConnection();
428 428
 		$query=$db->select()
429 429
 				->from(
430 430
 					array('s' => 'icinga_hostgroup_members'),
@@ -441,11 +441,11 @@  discard block
 block discarded – undo
441 441
 		foreach ($hosts as $key => $host)
442 442
 		{ // For each host, get all services and add in common_services if not found or add counter
443 443
 			$host_services=$this->getServicesByHostid($host->host_object_id);
444
-			foreach($host_services as $service)
444
+			foreach ($host_services as $service)
445 445
 			{
446 446
 				if (isset($common_services[$service->name2]['num']))
447 447
 				{
448
-					$common_services[$service->name2]['num'] +=1;
448
+					$common_services[$service->name2]['num']+=1;
449 449
 				}
450 450
 				else
451 451
 				{
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
 		{
462 462
 		    if ($common_services[$key]['num'] == $num_hosts)
463 463
 			{
464
-				array_push($result,array($key,$common_services[$key]['name']));
464
+				array_push($result, array($key, $common_services[$key]['name']));
465 465
 			}
466 466
 		}
467 467
 		
@@ -474,9 +474,9 @@  discard block
 block discarded – undo
474 474
 	*	@param $name string service name
475 475
 	*	@return array  service id
476 476
 	*/
477
-	protected function getServiceIDByName($hostname,$name) 
477
+	protected function getServiceIDByName($hostname, $name) 
478 478
 	{
479
-		$db = $this->getIdoDb()->getConnection();
479
+		$db=$this->getIdoDb()->getConnection();
480 480
 		if ($name == null)
481 481
 		{
482 482
 			return array();
@@ -485,7 +485,7 @@  discard block
 block discarded – undo
485 485
 		$query=$db->select()
486 486
 				->from(
487 487
 					array('s' => 'icinga_services'),
488
-					array('name' => 's.display_name','id' => 's.service_object_id'))
488
+					array('name' => 's.display_name', 'id' => 's.service_object_id'))
489 489
 				->join(
490 490
 					array('a' => 'icinga_objects'),
491 491
 					's.service_object_id=a.object_id',
@@ -503,12 +503,12 @@  discard block
 block discarded – undo
503 503
 	protected function getObjectNameByid($id) 
504 504
 	{
505 505
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
506
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
507
-		$db = $this->getIdoDb()->getConnection();
506
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
507
+		$db=$this->getIdoDb()->getConnection();
508 508
 		$query=$db->select()
509 509
 				->from(
510 510
 					array('a' => 'icinga_objects'),
511
-					array('name1' => 'a.name1','name2' => 'a.name2'))
511
+					array('name1' => 'a.name1', 'name2' => 'a.name2'))
512 512
 				->where('a.object_id='.$id.' AND a.is_active = 1');
513 513
 
514 514
 		return $db->fetchRow($query);
@@ -521,17 +521,17 @@  discard block
 block discarded – undo
521 521
 	protected function addHandlerRule($params)
522 522
 	{
523 523
 		// TODO Check for rule consistency
524
-		$db = $this->getDb()->getConnection();
524
+		$db=$this->getDb()->getConnection();
525 525
 		// Add last modified date = creation date and username
526
-		$params['created'] = new Zend_Db_Expr('NOW()');
527
-		$params['modified'] = new 	Zend_Db_Expr('NOW()');
528
-		$params['modifier'] = $this->Auth()->getUser()->getUsername();
526
+		$params['created']=new Zend_Db_Expr('NOW()');
527
+		$params['modified']=new 	Zend_Db_Expr('NOW()');
528
+		$params['modifier']=$this->Auth()->getUser()->getUsername();
529 529
 		
530 530
 		$query=$db->insert(
531 531
 			$this->getModuleConfig()->getTrapRuleName(),
532 532
 			$params
533 533
 		);
534
-		if($query==false)
534
+		if ($query == false)
535 535
 		{
536 536
 		  return null;
537 537
 		}
@@ -542,13 +542,13 @@  discard block
 block discarded – undo
542 542
 	*	@param array(<db item>=><value>)
543 543
 	*	@return array affected rows
544 544
 	*/
545
-	protected function updateHandlerRule($params,$ruleID)
545
+	protected function updateHandlerRule($params, $ruleID)
546 546
 	{
547 547
 		// TODO Check for rule consistency
548
-		$db = $this->getDb()->getConnection();
548
+		$db=$this->getDb()->getConnection();
549 549
 		// Add last modified date = creation date and username
550
-		$params['modified'] = new 	Zend_Db_Expr('NOW()');
551
-		$params['modifier'] = $this->Auth()->getUser()->getUsername();
550
+		$params['modified']=new 	Zend_Db_Expr('NOW()');
551
+		$params['modifier']=$this->Auth()->getUser()->getUsername();
552 552
 		
553 553
 		$numRows=$db->update(
554 554
 			$this->getModuleConfig()->getTrapRuleName(),
@@ -563,8 +563,8 @@  discard block
 block discarded – undo
563 563
 	*/
564 564
 	protected function deleteRule($ruleID)
565 565
 	{
566
-		if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
567
-		$db = $this->getDb()->getConnection();
566
+		if (!preg_match('/^[0-9]+$/', $ruleID)) { throw new Exception('Invalid id'); }
567
+		$db=$this->getDb()->getConnection();
568 568
 		
569 569
 		$query=$db->delete(
570 570
 			$this->getModuleConfig()->getTrapRuleName(),
@@ -577,10 +577,10 @@  discard block
 block discarded – undo
577 577
 	*	@param $ip string source IP (v4 or v6)
578 578
 	*	@param $oid string oid
579 579
 	*/
580
-	protected function deleteTrap($ip,$oid)
580
+	protected function deleteTrap($ip, $oid)
581 581
 	{
582 582
 		
583
-		$db = $this->getDb()->getConnection();
583
+		$db=$this->getDb()->getConnection();
584 584
 		$condition=null;
585 585
 		if ($ip != null)
586 586
 		{
@@ -588,10 +588,10 @@  discard block
 block discarded – undo
588 588
 		}
589 589
 		if ($oid != null)
590 590
 		{
591
-			$condition=($condition===null)?'':$condition.' AND ';
591
+			$condition=($condition === null) ? '' : $condition.' AND ';
592 592
 			$condition.="trap_oid='$oid'";
593 593
 		}
594
-		if($condition === null) return null;
594
+		if ($condition === null) return null;
595 595
 		$query=$db->delete(
596 596
 			$this->getModuleConfig()->getTrapTableName(),
597 597
 			$condition
@@ -605,10 +605,10 @@  discard block
 block discarded – undo
605 605
 	*	@param $ip string source IP (v4 or v6)
606 606
 	*	@param $oid string oid
607 607
 	*/
608
-	protected function countTrap($ip,$oid)
608
+	protected function countTrap($ip, $oid)
609 609
 	{
610 610
 		
611
-		$db = $this->getDb()->getConnection();
611
+		$db=$this->getDb()->getConnection();
612 612
 		$condition=null;
613 613
 		if ($ip != null)
614 614
 		{
@@ -616,10 +616,10 @@  discard block
 block discarded – undo
616 616
 		}
617 617
 		if ($oid != null)
618 618
 		{
619
-			$condition=($condition===null)?'':$condition.' AND ';
619
+			$condition=($condition === null) ? '' : $condition.' AND ';
620 620
 			$condition.="trap_oid='$oid'";
621 621
 		}
622
-		if($condition ==null) return 0;
622
+		if ($condition == null) return 0;
623 623
 		$query=$db->select()
624 624
 			->from(
625 625
 				$this->getModuleConfig()->getTrapTableName(),
@@ -635,27 +635,27 @@  discard block
 block discarded – undo
635 635
 	protected function getDBConfigValue($element)
636 636
 	{
637 637
 	
638
-		$db = $this->getDb()->getConnection();
638
+		$db=$this->getDb()->getConnection();
639 639
 		
640 640
 		$query=$db->select()
641 641
 			->from(
642 642
 				$this->getModuleConfig()->getDbConfigTableName(),
643 643
 				array('value'=>'value'))
644
-			->where('name=?',$element);
644
+			->where('name=?', $element);
645 645
 		$return_row=$db->fetchRow($query);
646
-		if ($return_row==null)  // value does not exists
646
+		if ($return_row == null)  // value does not exists
647 647
 		{
648 648
 			$default=$this->getModuleConfig()->getDBConfigDefaults();
649
-			if ( ! isset($default[$element])) return null; // no default and not value
649
+			if (!isset($default[$element])) return null; // no default and not value
650 650
 			
651
-			$this->addDBConfigValue($element,$default[$element]);
651
+			$this->addDBConfigValue($element, $default[$element]);
652 652
 			return $default[$element];
653 653
 		}
654 654
 		if ($return_row->value == null) // value id empty
655 655
 		{
656 656
 			$default=$this->getModuleConfig()->getDBConfigDefaults();
657
-			if ( ! isset($default[$element])) return null; // no default and not value
658
-			$this->setDBConfigValue($element,$default[$element]);
657
+			if (!isset($default[$element])) return null; // no default and not value
658
+			$this->setDBConfigValue($element, $default[$element]);
659 659
 			return $default[$element];			
660 660
 		}
661 661
 		return $return_row->value;		
@@ -666,10 +666,10 @@  discard block
 block discarded – undo
666 666
 	*   @param string $value : value
667 667
 	*/
668 668
 		
669
-	protected function addDBConfigValue($element,$value)
669
+	protected function addDBConfigValue($element, $value)
670 670
 	{
671 671
 	
672
-		$db = $this->getDb()->getConnection();
672
+		$db=$this->getDb()->getConnection();
673 673
 		
674 674
 		$query=$db->insert(
675 675
 				$this->getModuleConfig()->getDbConfigTableName(),
@@ -685,10 +685,10 @@  discard block
 block discarded – undo
685 685
 	*	@param string $element : name of config element
686 686
 	*   @param string $value : value
687 687
 	*/
688
-	protected function setDBConfigValue($element,$value)
688
+	protected function setDBConfigValue($element, $value)
689 689
 	{
690 690
 	
691
-		$db = $this->getDb()->getConnection();
691
+		$db=$this->getDb()->getConnection();
692 692
 		$query=$db->update(
693 693
 				$this->getModuleConfig()->getDbConfigTableName(),
694 694
 				array('value'=>$value),
@@ -703,10 +703,10 @@  discard block
 block discarded – undo
703 703
 	protected function isDirectorInstalled()
704 704
 	{
705 705
 	    $output=array();
706
-	    exec('icingacli module list',$output);
706
+	    exec('icingacli module list', $output);
707 707
 	    foreach ($output as $line)
708 708
 		{
709
-			if (preg_match('/^director .*enabled/',$line))
709
+			if (preg_match('/^director .*enabled/', $line))
710 710
 			{
711 711
 				return true;
712 712
 			}
Please login to merge, or discard this patch.
Braces   +62 added lines, -30 removed lines patch added patch discarded remove patch
@@ -87,10 +87,11 @@  discard block
 block discarded – undo
87 87
 		try 
88 88
 		{
89 89
 			$dbconn = IcingaDbConnection::fromResourceName($DBname);
90
-		} 
91
-		catch (Exception $e)
90
+		} catch (Exception $e)
92 91
 		{
93
-			if ($test) return array(2,$DBname);
92
+			if ($test) {
93
+				return array(2,$DBname);
94
+			}
94 95
 			$this->redirectNow('trapdirector/settings?dberror=2');
95 96
 			return null;
96 97
 		}
@@ -98,10 +99,11 @@  discard block
 block discarded – undo
98 99
 			try 
99 100
 			{
100 101
 				$db=$dbconn->getConnection();
101
-			}
102
-			catch (Exception $e) 
102
+			} catch (Exception $e) 
103 103
 			{
104
-				if ($test) return array(3,$DBname,$e->getMessage());
104
+				if ($test) {
105
+					return array(3,$DBname,$e->getMessage());
106
+				}
105 107
 				$this->redirectNow('trapdirector/settings?dberror=3');
106 108
 				return null;
107 109
 			}
@@ -113,25 +115,32 @@  discard block
 block discarded – undo
113 115
 				$version=$db->fetchRow($query);
114 116
 				if ( ($version == null) || ! property_exists($version,'value') )
115 117
 				{
116
-					if ($test) return array(4,$DBname);
118
+					if ($test) {
119
+						return array(4,$DBname);
120
+					}
117 121
 					$this->redirectNow('trapdirector/settings?dberror=4');
118 122
 					return null;
119 123
 				}
120 124
 				if ($version->value < $this->getModuleConfig()->getDbMinVersion()) 
121 125
 				{
122
-					if ($test) return array(5,$version->value,$this->getModuleConfig()->getDbMinVersion());
126
+					if ($test) {
127
+						return array(5,$version->value,$this->getModuleConfig()->getDbMinVersion());
128
+					}
123 129
 					$this->redirectNow('trapdirector/settings?dberror=5');
124 130
 					return null;
125 131
 				}
126
-			}
127
-			catch (Exception $e) 
132
+			} catch (Exception $e) 
128 133
 			{
129
-				if ($test) return array(3,$DBname,$e->getMessage());
134
+				if ($test) {
135
+					return array(3,$DBname,$e->getMessage());
136
+				}
130 137
 				$this->redirectNow('trapdirector/settings?dberror=4');
131 138
 				return null;
132 139
 			}
133 140
 		}
134
-		if ($test) return array(0,'');
141
+		if ($test) {
142
+			return array(0,'');
143
+		}
135 144
 		return $dbconn;
136 145
 	}
137 146
 
@@ -142,31 +151,41 @@  discard block
 block discarded – undo
142 151
 	 */
143 152
 	public function getDb($test=false)
144 153
 	{
145
-		if ($this->trapDB != null && $test = false) return $this->trapDB;
154
+		if ($this->trapDB != null && $test = false) {
155
+			return $this->trapDB;
156
+		}
146 157
 		
147 158
 		$dbresource=$this->Config()->get('config', 'database');
148 159
 		
149 160
 		if ( ! $dbresource )
150 161
 		{	
151
-			if ($test) return array(1,'');
162
+			if ($test) {
163
+				return array(1,'');
164
+			}
152 165
 			$this->redirectNow('trapdirector/settings?dberror=1');
153 166
 			return null;
154 167
 		}
155 168
 		$retDB=$this->getDbByName($dbresource,$test,true);
156
-		if ($test == true) return $retDB;
169
+		if ($test == true) {
170
+			return $retDB;
171
+		}
157 172
 		$this->trapDB=$retDB;
158 173
 		return $this->trapDB;
159 174
 	}
160 175
 	
161 176
 	public function getIdoDb($test=false)
162 177
 	{
163
-		if ($this->icingaDB != null && $test = false) return $this->icingaDB;
178
+		if ($this->icingaDB != null && $test = false) {
179
+			return $this->icingaDB;
180
+		}
164 181
 		// TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
165 182
 		$dbresource=$this->Config()->get('config', 'IDOdatabase');;
166 183
 
167 184
 		if ( ! $dbresource )
168 185
 		{
169
-		    if ($test) return array(1,'No database in config.ini');
186
+		    if ($test) {
187
+		    	return array(1,'No database in config.ini');
188
+		    }
170 189
 		    $this->redirectNow('trapdirector/settings?idodberror=1');
171 190
 		    return null;
172 191
 		}
@@ -174,10 +193,11 @@  discard block
 block discarded – undo
174 193
 		try
175 194
 		{
176 195
 		    $dbconn = IcingaDbConnection::fromResourceName($dbresource);
177
-		}
178
-		catch (Exception $e)
196
+		} catch (Exception $e)
179 197
 		{
180
-		    if ($test) return array(2,"Database $dbresource does not exists in IcingaWeb2");
198
+		    if ($test) {
199
+		    	return array(2,"Database $dbresource does not exists in IcingaWeb2");
200
+		    }
181 201
 		    $this->redirectNow('trapdirector/settings?idodberror=2');
182 202
 		    return null;
183 203
 		}
@@ -197,8 +217,7 @@  discard block
 block discarded – undo
197 217
 		    {
198 218
 		        return array(4,"$dbresource does not look like an IDO database");
199 219
 		    }
200
-		}
201
-		catch (Exception $e)
220
+		} catch (Exception $e)
202 221
 		{
203 222
 			return array(3,"Error connecting to $dbresource : " . $e->getMessage());
204 223
 		}
@@ -446,8 +465,7 @@  discard block
 block discarded – undo
446 465
 				if (isset($common_services[$service->name2]['num']))
447 466
 				{
448 467
 					$common_services[$service->name2]['num'] +=1;
449
-				}
450
-				else
468
+				} else
451 469
 				{
452 470
 					$common_services[$service->name2]['num']=1;
453 471
 					$common_services[$service->name2]['name']=$service->name;
@@ -591,7 +609,9 @@  discard block
 block discarded – undo
591 609
 			$condition=($condition===null)?'':$condition.' AND ';
592 610
 			$condition.="trap_oid='$oid'";
593 611
 		}
594
-		if($condition === null) return null;
612
+		if($condition === null) {
613
+			return null;
614
+		}
595 615
 		$query=$db->delete(
596 616
 			$this->getModuleConfig()->getTrapTableName(),
597 617
 			$condition
@@ -619,7 +639,9 @@  discard block
 block discarded – undo
619 639
 			$condition=($condition===null)?'':$condition.' AND ';
620 640
 			$condition.="trap_oid='$oid'";
621 641
 		}
622
-		if($condition ==null) return 0;
642
+		if($condition ==null) {
643
+			return 0;
644
+		}
623 645
 		$query=$db->select()
624 646
 			->from(
625 647
 				$this->getModuleConfig()->getTrapTableName(),
@@ -643,18 +665,28 @@  discard block
 block discarded – undo
643 665
 				array('value'=>'value'))
644 666
 			->where('name=?',$element);
645 667
 		$return_row=$db->fetchRow($query);
646
-		if ($return_row==null)  // value does not exists
668
+		if ($return_row==null) {
669
+			// value does not exists
647 670
 		{
648 671
 			$default=$this->getModuleConfig()->getDBConfigDefaults();
649
-			if ( ! isset($default[$element])) return null; // no default and not value
672
+		}
673
+			if ( ! isset($default[$element])) {
674
+				return null;
675
+			}
676
+			// no default and not value
650 677
 			
651 678
 			$this->addDBConfigValue($element,$default[$element]);
652 679
 			return $default[$element];
653 680
 		}
654
-		if ($return_row->value == null) // value id empty
681
+		if ($return_row->value == null) {
682
+			// value id empty
655 683
 		{
656 684
 			$default=$this->getModuleConfig()->getDBConfigDefaults();
657
-			if ( ! isset($default[$element])) return null; // no default and not value
685
+		}
686
+			if ( ! isset($default[$element])) {
687
+				return null;
688
+			}
689
+			// no default and not value
658 690
 			$this->setDBConfigValue($element,$default[$element]);
659 691
 			return $default[$element];			
660 692
 		}
Please login to merge, or discard this patch.
library/Trapdirector/Config/MIBLoader.php 3 patches
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -31,10 +31,10 @@  discard block
 block discarded – undo
31 31
 				
32 32
 	}
33 33
 
34
-    /**
35
-     * Get all mibs in db which have at least one trap
36
-     * @return array
37
-     */	
34
+	/**
35
+	 * Get all mibs in db which have at least one trap
36
+	 * @return array
37
+	 */	
38 38
 	
39 39
 	public function getMIBList()
40 40
 	{
@@ -58,9 +58,9 @@  discard block
 block discarded – undo
58 58
 	
59 59
 	
60 60
 	/** Get trap list from a mib 
61
-	*	@param $mib string mib name
62
-	*	@return array : traps
63
-	*/
61
+	 *	@param $mib string mib name
62
+	 *	@return array : traps
63
+	 */
64 64
 	public function getTrapList($mib)
65 65
 	{
66 66
 		$traps=array();
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 		$query=$dbconn->select()
69 69
 				->from(
70 70
 					$this->config->getMIBCacheTableName(),
71
-				    array('name' => 'name', 'oid' => 'oid', 'description' => 'description'))
71
+					array('name' => 'name', 'oid' => 'oid', 'description' => 'description'))
72 72
 				->where("mib = '".$mib."' AND type='21'") ;
73 73
 		$names=$dbconn->fetchAll($query);
74 74
 		foreach ($names as $val)
@@ -79,9 +79,9 @@  discard block
 block discarded – undo
79 79
 	}
80 80
 	
81 81
 	/** Get objects a trap can have
82
-	*	@param int $trap oid of trap
83
-	*	@return array|null : null if trap not found, or array ( <oid> => name/mib/type )
84
-	*/
82
+	 *	@param int $trap oid of trap
83
+	 *	@return array|null : null if trap not found, or array ( <oid> => name/mib/type )
84
+	 */
85 85
 	public function getObjectList($trap)
86 86
 	{
87 87
 		$objects=array();
@@ -97,15 +97,15 @@  discard block
 block discarded – undo
97 97
 		if ( ($id == null) || ! property_exists($id,'id') ) return null;
98 98
 		
99 99
 		$query=$dbconn->select()
100
-		        ->from(
101
-		            array('c' => $this->config->getMIBCacheTableName()),
102
-		            array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
103
-		                'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
104
-		                'description' => 'c.description'))
105
-		        ->join(
106
-		            array('o' => $this->config->getMIBCacheTableTrapObjName()),
107
-		            'o.trap_id='.$id->id )
108
-		        ->where("o.object_id = c.id");
100
+				->from(
101
+					array('c' => $this->config->getMIBCacheTableName()),
102
+					array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
103
+						'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
104
+						'description' => 'c.description'))
105
+				->join(
106
+					array('o' => $this->config->getMIBCacheTableTrapObjName()),
107
+					'o.trap_id='.$id->id )
108
+				->where("o.object_id = c.id");
109 109
 		$listObjects=$dbconn->fetchAll($query);
110 110
 		if ( count($listObjects)==0 ) return null;
111 111
 		
@@ -123,12 +123,12 @@  discard block
 block discarded – undo
123 123
 	}
124 124
 
125 125
 	/** translate oid in MIB::Name 
126
-	*	@param string oid
127
-	*	@return array|null :  return array with index (oid -> oid, mib -> mib name, name -> oid name, type -> oid type)
128
-	*/
126
+	 *	@param string oid
127
+	 *	@return array|null :  return array with index (oid -> oid, mib -> mib name, name -> oid name, type -> oid type)
128
+	 */
129 129
 	public function translateOID($oid)
130 130
 	{
131
-	    if (!preg_match('/^\./',$oid)) $oid = '.' . $oid; // Add a leading '.'
131
+		if (!preg_match('/^\./',$oid)) $oid = '.' . $oid; // Add a leading '.'
132 132
 		$retArray=array('oid' => $oid, 'mib' => null, 'name'=>null,'type'=>null);
133 133
 		$dbconn = $this->db->getConnection();
134 134
 
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
 				->from(
137 137
 					array('o' => $this->config->getMIBCacheTableName()),
138 138
 					array('mib'=>'o.mib','name' => 'o.name','type'=>'o.syntax',
139
-					    'type_enum'=>'o.type_enum', 'description'=>'o.description'))
139
+						'type_enum'=>'o.type_enum', 'description'=>'o.description'))
140 140
 				->where('o.oid=\''.$oid.'\'');
141 141
 		$object=$dbconn->fetchRow($query);
142 142
 		if ($object != null) 
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
 		// Try to get oid name from snmptranslate
153 153
 		$matches=array();
154 154
 		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
155
-		    ' '.$oid);
155
+			' '.$oid);
156 156
 		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
157 157
 		if ($ret_code===0 || $ret_code===false) {
158 158
 			return null;
@@ -164,8 +164,8 @@  discard block
 block discarded – undo
164 164
 			" | grep SYNTAX | sed 's/SYNTAX[[:blank:]]*//'");
165 165
 		if (preg_match('/(.*)\{(.*)\}/',$translate,$matches))
166 166
 		{
167
-		    $retArray['type']=$matches[1];
168
-		    $retArray['type_enum']=$matches[2];
167
+			$retArray['type']=$matches[1];
168
+			$retArray['type_enum']=$matches[2];
169 169
 		}
170 170
 		else
171 171
 		{
@@ -229,25 +229,25 @@  discard block
 block discarded – undo
229 229
 	 */
230 230
 	public function getTrapDetails($oid=null,$id=null)
231 231
 	{	    
232
-	    // Get trap id in DB
233
-	    if ($oid===null)
234
-	    {
235
-	        $where="c.id = '$id'";
236
-	    }
237
-	    else
238
-	    {
239
-	        $where="c.oid = '$oid'";
240
-	    }
241
-	    $query=$this->db->getConnection()->select()
242
-           ->from(
243
-            array('c' => $this->config->getMIBCacheTableName()),
244
-            array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
245
-                'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
246
-                'description' => 'c.description'))
247
-            ->where($where);
248
-        $trap=$this->db->getConnection()->fetchRow($query);
232
+		// Get trap id in DB
233
+		if ($oid===null)
234
+		{
235
+			$where="c.id = '$id'";
236
+		}
237
+		else
238
+		{
239
+			$where="c.oid = '$oid'";
240
+		}
241
+		$query=$this->db->getConnection()->select()
242
+		   ->from(
243
+			array('c' => $this->config->getMIBCacheTableName()),
244
+			array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
245
+				'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
246
+				'description' => 'c.description'))
247
+			->where($where);
248
+		$trap=$this->db->getConnection()->fetchRow($query);
249 249
         
250
-        return $trap;
250
+		return $trap;
251 251
 	}
252 252
 	
253 253
 }
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
 	 * @param string $db current database
22 22
 	 * @param TrapModuleConfig $config TrapModuleConfig class instance
23 23
 	 */
24
-	public function __construct($snmptranslate,$snmptranslate_dirs,$db,$config)
24
+	public function __construct($snmptranslate, $snmptranslate_dirs, $db, $config)
25 25
 	{
26 26
 		$this->snmptranslate=$snmptranslate;
27 27
 		$this->snmptranslate_dirs=$snmptranslate_dirs;
@@ -38,19 +38,19 @@  discard block
 block discarded – undo
38 38
 	
39 39
 	public function getMIBList()
40 40
 	{
41
-		$dbconn = $this->db->getConnection();
41
+		$dbconn=$this->db->getConnection();
42 42
 		$query=$dbconn->select()
43 43
 				->distinct()
44 44
 				->from(
45 45
 					$this->config->getMIBCacheTableName(),
46 46
 					array('mib' => 'mib'))
47 47
 				->where("type = '21'")
48
-				->order('mib ASC');				;
48
+				->order('mib ASC'); ;
49 49
 		$names=$dbconn->fetchAll($query);
50 50
 		$mib=array();
51
-		foreach($names as $val)
51
+		foreach ($names as $val)
52 52
 		{
53
-			array_push($mib,$val->mib);
53
+			array_push($mib, $val->mib);
54 54
 		}
55 55
 		return $mib;
56 56
 		
@@ -64,12 +64,12 @@  discard block
 block discarded – undo
64 64
 	public function getTrapList($mib)
65 65
 	{
66 66
 		$traps=array();
67
-		$dbconn = $this->db->getConnection();
67
+		$dbconn=$this->db->getConnection();
68 68
 		$query=$dbconn->select()
69 69
 				->from(
70 70
 					$this->config->getMIBCacheTableName(),
71 71
 				    array('name' => 'name', 'oid' => 'oid', 'description' => 'description'))
72
-				->where("mib = '".$mib."' AND type='21'") ;
72
+				->where("mib = '".$mib."' AND type='21'");
73 73
 		$names=$dbconn->fetchAll($query);
74 74
 		foreach ($names as $val)
75 75
 		{
@@ -87,19 +87,19 @@  discard block
 block discarded – undo
87 87
 		$objects=array();
88 88
 		
89 89
 		// Get trap id in DB
90
-		$dbconn = $this->db->getConnection();
90
+		$dbconn=$this->db->getConnection();
91 91
 		$query=$dbconn->select()
92 92
 				->from(
93 93
 					$this->config->getMIBCacheTableName(),
94 94
 					array('id' => 'id'))
95
-				->where("oid = '".$trap."'") ;
95
+				->where("oid = '".$trap."'");
96 96
 		$id=$dbconn->fetchRow($query);
97
-		if ( ($id == null) || ! property_exists($id,'id') ) return null;
97
+		if (($id == null) || !property_exists($id, 'id')) return null;
98 98
 		
99 99
 		$query=$dbconn->select()
100 100
 		        ->from(
101 101
 		            array('c' => $this->config->getMIBCacheTableName()),
102
-		            array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
102
+		            array('name' => 'c.name', 'mib' => 'c.mib', 'oid' => 'c.oid', 'type_enum'=>'c.type_enum',
103 103
 		                'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
104 104
 		                'description' => 'c.description'))
105 105
 		        ->join(
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 		            'o.trap_id='.$id->id )
108 108
 		        ->where("o.object_id = c.id");
109 109
 		$listObjects=$dbconn->fetchAll($query);
110
-		if ( count($listObjects)==0 ) return null;
110
+		if (count($listObjects) == 0) return null;
111 111
 		
112 112
 		foreach ($listObjects as $val)
113 113
 		{
@@ -128,14 +128,14 @@  discard block
 block discarded – undo
128 128
 	*/
129 129
 	public function translateOID($oid)
130 130
 	{
131
-	    if (!preg_match('/^\./',$oid)) $oid = '.' . $oid; // Add a leading '.'
132
-		$retArray=array('oid' => $oid, 'mib' => null, 'name'=>null,'type'=>null);
133
-		$dbconn = $this->db->getConnection();
131
+	    if (!preg_match('/^\./', $oid)) $oid='.'.$oid; // Add a leading '.'
132
+		$retArray=array('oid' => $oid, 'mib' => null, 'name'=>null, 'type'=>null);
133
+		$dbconn=$this->db->getConnection();
134 134
 
135 135
 		$query=$dbconn->select()
136 136
 				->from(
137 137
 					array('o' => $this->config->getMIBCacheTableName()),
138
-					array('mib'=>'o.mib','name' => 'o.name','type'=>'o.syntax',
138
+					array('mib'=>'o.mib', 'name' => 'o.name', 'type'=>'o.syntax',
139 139
 					    'type_enum'=>'o.type_enum', 'description'=>'o.description'))
140 140
 				->where('o.oid=\''.$oid.'\'');
141 141
 		$object=$dbconn->fetchRow($query);
@@ -151,18 +151,18 @@  discard block
 block discarded – undo
151 151
 		
152 152
 		// Try to get oid name from snmptranslate
153 153
 		$matches=array();
154
-		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
154
+		$translate=exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
155 155
 		    ' '.$oid);
156
-		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
157
-		if ($ret_code===0 || $ret_code===false) {
156
+		$ret_code=preg_match('/(.*)::(.*)/', $translate, $matches);
157
+		if ($ret_code === 0 || $ret_code === false) {
158 158
 			return null;
159 159
 		} 
160 160
 		$retArray['mib']=$matches[1];
161 161
 		$retArray['name']=$matches[2];
162 162
 		
163
-		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.' -Td -On ' . $matches[0] .
163
+		$translate=exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.' -Td -On '.$matches[0].
164 164
 			" | grep SYNTAX | sed 's/SYNTAX[[:blank:]]*//'");
165
-		if (preg_match('/(.*)\{(.*)\}/',$translate,$matches))
165
+		if (preg_match('/(.*)\{(.*)\}/', $translate, $matches))
166 166
 		{
167 167
 		    $retArray['type']=$matches[1];
168 168
 		    $retArray['type_enum']=$matches[2];
@@ -197,9 +197,9 @@  discard block
 block discarded – undo
197 197
 	 * @param string $type filter by type (21=trap)
198 198
 	 * @return number number of entries in db.
199 199
 	 */
200
-	public function countObjects($mib=null,$type=null)
200
+	public function countObjects($mib=null, $type=null)
201 201
 	{
202
-		$dbconn = $this->db->getConnection();
202
+		$dbconn=$this->db->getConnection();
203 203
 		$query=$dbconn->select()
204 204
 				->from(
205 205
 					$this->config->getMIBCacheTableName(),
@@ -207,11 +207,11 @@  discard block
 block discarded – undo
207 207
 		$where=null;
208 208
 		if ($mib !== null)
209 209
 		{
210
-			$where ="mib = '$mib' ";
210
+			$where="mib = '$mib' ";
211 211
 		}
212 212
 		if ($type !== null)
213 213
 		{
214
-			$where=($where != null)?' AND ':'';
214
+			$where=($where != null) ? ' AND ' : '';
215 215
 			$where.="type='$type'";
216 216
 		}
217 217
 		if ($where !== null)
@@ -227,10 +227,10 @@  discard block
 block discarded – undo
227 227
 	 * @param integer $id
228 228
 	 * @return array trap details
229 229
 	 */
230
-	public function getTrapDetails($oid=null,$id=null)
230
+	public function getTrapDetails($oid=null, $id=null)
231 231
 	{	    
232 232
 	    // Get trap id in DB
233
-	    if ($oid===null)
233
+	    if ($oid === null)
234 234
 	    {
235 235
 	        $where="c.id = '$id'";
236 236
 	    }
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
 	    $query=$this->db->getConnection()->select()
242 242
            ->from(
243 243
             array('c' => $this->config->getMIBCacheTableName()),
244
-            array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
244
+            array('name' => 'c.name', 'mib' => 'c.mib', 'oid' => 'c.oid', 'type_enum'=>'c.type_enum',
245 245
                 'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
246 246
                 'description' => 'c.description'))
247 247
             ->where($where);
Please login to merge, or discard this patch.
Braces   +12 added lines, -7 removed lines patch added patch discarded remove patch
@@ -94,7 +94,9 @@  discard block
 block discarded – undo
94 94
 					array('id' => 'id'))
95 95
 				->where("oid = '".$trap."'") ;
96 96
 		$id=$dbconn->fetchRow($query);
97
-		if ( ($id == null) || ! property_exists($id,'id') ) return null;
97
+		if ( ($id == null) || ! property_exists($id,'id') ) {
98
+			return null;
99
+		}
98 100
 		
99 101
 		$query=$dbconn->select()
100 102
 		        ->from(
@@ -107,7 +109,9 @@  discard block
 block discarded – undo
107 109
 		            'o.trap_id='.$id->id )
108 110
 		        ->where("o.object_id = c.id");
109 111
 		$listObjects=$dbconn->fetchAll($query);
110
-		if ( count($listObjects)==0 ) return null;
112
+		if ( count($listObjects)==0 ) {
113
+			return null;
114
+		}
111 115
 		
112 116
 		foreach ($listObjects as $val)
113 117
 		{
@@ -128,7 +132,10 @@  discard block
 block discarded – undo
128 132
 	*/
129 133
 	public function translateOID($oid)
130 134
 	{
131
-	    if (!preg_match('/^\./',$oid)) $oid = '.' . $oid; // Add a leading '.'
135
+	    if (!preg_match('/^\./',$oid)) {
136
+	    	$oid = '.' . $oid;
137
+	    }
138
+	    // Add a leading '.'
132 139
 		$retArray=array('oid' => $oid, 'mib' => null, 'name'=>null,'type'=>null);
133 140
 		$dbconn = $this->db->getConnection();
134 141
 
@@ -166,8 +173,7 @@  discard block
 block discarded – undo
166 173
 		{
167 174
 		    $retArray['type']=$matches[1];
168 175
 		    $retArray['type_enum']=$matches[2];
169
-		}
170
-		else
176
+		} else
171 177
 		{
172 178
 			$retArray['type']=$translate;
173 179
 			$retArray['type_enum']='';			
@@ -233,8 +239,7 @@  discard block
 block discarded – undo
233 239
 	    if ($oid===null)
234 240
 	    {
235 241
 	        $where="c.id = '$id'";
236
-	    }
237
-	    else
242
+	    } else
238 243
 	    {
239 244
 	        $where="c.oid = '$oid'";
240 245
 	    }
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Logging.php 3 patches
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -9,113 +9,113 @@
 block discarded – undo
9 9
 class Logging
10 10
 {
11 11
 
12
-    //**** Options from config database
13
-    // Default values
14
-    public $debugLevel=2;  // 0=No output 1=critical 2=warning 3=trace 4=ALL
15
-    public $outputMode='syslog'; // alert type : file, syslog, display
16
-    public $outputFile="/tmp/trapdebug.txt";
17
-    protected $logLevels=array("","Error","Warning","Info","Debug");
18
-    protected $outputList=array('file', 'syslog', 'display');
12
+	//**** Options from config database
13
+	// Default values
14
+	public $debugLevel=2;  // 0=No output 1=critical 2=warning 3=trace 4=ALL
15
+	public $outputMode='syslog'; // alert type : file, syslog, display
16
+	public $outputFile="/tmp/trapdebug.txt";
17
+	protected $logLevels=array("","Error","Warning","Info","Debug");
18
+	protected $outputList=array('file', 'syslog', 'display');
19 19
     
20
-    /** Send log. Throws exception on critical error
21
-     *	@param	string $message Message to log
22
-     *	@param	int $level 1=critical 2=warning 3=trace 4=debug
23
-     *	@param  string $destination file/syslog/display
24
-     *	@return void
25
-     *  @throws Exception
26
-     **/
27
-    public function log( $message, $level, $destination ='')
28
-    {
29
-        if ($this->debugLevel >= $level)
30
-        {
31
-            $message = '['.  date("Y/m/d H:i:s") . '] ' .
32
-                '[TrapDirector] ['.$this->logLevels[$level].']: ' .$message . "\n";
20
+	/** Send log. Throws exception on critical error
21
+	 *	@param	string $message Message to log
22
+	 *	@param	int $level 1=critical 2=warning 3=trace 4=debug
23
+	 *	@param  string $destination file/syslog/display
24
+	 *	@return void
25
+	 *  @throws Exception
26
+	 **/
27
+	public function log( $message, $level, $destination ='')
28
+	{
29
+		if ($this->debugLevel >= $level)
30
+		{
31
+			$message = '['.  date("Y/m/d H:i:s") . '] ' .
32
+				'[TrapDirector] ['.$this->logLevels[$level].']: ' .$message . "\n";
33 33
             
34
-            $output = ( $destination != '' ) ? $destination : $this->outputMode;
35
-            switch ($output)
36
-            {
37
-                case 'file':
38
-                    file_put_contents ($this->outputFile, $message , FILE_APPEND);
39
-                    break;
40
-                case 'syslog':
41
-                    switch($level)
42
-                    {
43
-                        case 1 : $prio = LOG_ERR;break;
44
-                        case 2 : $prio = LOG_WARNING;break;
45
-                        case 3 : $prio = LOG_INFO;break;
46
-                        case 4 : $prio = LOG_DEBUG;break;
47
-                        default: $prio = LOG_ERR;
48
-                    }
49
-                    syslog($prio,$message);
50
-                    break;
51
-                case 'display':
52
-                    echo $message;
53
-                    break;
54
-                default : // nothing we can do at this point
55
-                    throw new Exception($message);
56
-            }
57
-        }
58
-        if ($level == 1)
59
-        {
60
-            throw new Exception($message);
61
-        }
62
-    }
34
+			$output = ( $destination != '' ) ? $destination : $this->outputMode;
35
+			switch ($output)
36
+			{
37
+				case 'file':
38
+					file_put_contents ($this->outputFile, $message , FILE_APPEND);
39
+					break;
40
+				case 'syslog':
41
+					switch($level)
42
+					{
43
+						case 1 : $prio = LOG_ERR;break;
44
+						case 2 : $prio = LOG_WARNING;break;
45
+						case 3 : $prio = LOG_INFO;break;
46
+						case 4 : $prio = LOG_DEBUG;break;
47
+						default: $prio = LOG_ERR;
48
+					}
49
+					syslog($prio,$message);
50
+					break;
51
+				case 'display':
52
+					echo $message;
53
+					break;
54
+				default : // nothing we can do at this point
55
+					throw new Exception($message);
56
+			}
57
+		}
58
+		if ($level == 1)
59
+		{
60
+			throw new Exception($message);
61
+		}
62
+	}
63 63
     
64 64
         
65
-    public function setLogging($debugLvl,$outputType,$outputFile=null)
66
-    {
67
-        $this->setLevel($debugLvl);
68
-        switch ($outputType)
69
-        {
70
-            case 'file':
71
-                if ($outputFile == null) throw new Exception("File logging without file !");
72
-                $this->setFile($outputFile);
73
-                $this->setDestination('file');
74
-                break;
75
-            default:
76
-                $this->setDestination($outputType);
77
-        }
78
-    }
65
+	public function setLogging($debugLvl,$outputType,$outputFile=null)
66
+	{
67
+		$this->setLevel($debugLvl);
68
+		switch ($outputType)
69
+		{
70
+			case 'file':
71
+				if ($outputFile == null) throw new Exception("File logging without file !");
72
+				$this->setFile($outputFile);
73
+				$this->setDestination('file');
74
+				break;
75
+			default:
76
+				$this->setDestination($outputType);
77
+		}
78
+	}
79 79
     
80
-    /**
81
-     * Set logging level
82
-     * @param integer $level
83
-     * @throws Exception
84
-     */
85
-    public function setLevel($level)
86
-    {
87
-        if (!is_integer($level) || $level < 0 || $level > 10)
88
-        {
89
-            throw new Exception('Invalid log level');
90
-        }
91
-        $this->debugLevel=$level;
92
-    }
80
+	/**
81
+	 * Set logging level
82
+	 * @param integer $level
83
+	 * @throws Exception
84
+	 */
85
+	public function setLevel($level)
86
+	{
87
+		if (!is_integer($level) || $level < 0 || $level > 10)
88
+		{
89
+			throw new Exception('Invalid log level');
90
+		}
91
+		$this->debugLevel=$level;
92
+	}
93 93
 
94
-    /**
95
-     * Set logging destination
96
-     * @param string $destination
97
-     * @throws Exception
98
-     */
99
-    public function setDestination($destination)
100
-    {
101
-        if (!is_string($destination) || ! in_array($destination, $this->outputList))
102
-        {
103
-            throw new Exception('Invalid log destination');
104
-        }
105
-        $this->outputMode=$destination;
106
-    }
107
-    /**
108
-     * Set file destination
109
-     * @param string $file
110
-     * @throws Exception
111
-     */
112
-    public function setFile($file)
113
-    {
114
-        if (!is_string($file))
115
-        {
116
-            throw new Exception('Invalid log file');
117
-        }
118
-        $this->outputFile=$file;
119
-    }
94
+	/**
95
+	 * Set logging destination
96
+	 * @param string $destination
97
+	 * @throws Exception
98
+	 */
99
+	public function setDestination($destination)
100
+	{
101
+		if (!is_string($destination) || ! in_array($destination, $this->outputList))
102
+		{
103
+			throw new Exception('Invalid log destination');
104
+		}
105
+		$this->outputMode=$destination;
106
+	}
107
+	/**
108
+	 * Set file destination
109
+	 * @param string $file
110
+	 * @throws Exception
111
+	 */
112
+	public function setFile($file)
113
+	{
114
+		if (!is_string($file))
115
+		{
116
+			throw new Exception('Invalid log file');
117
+		}
118
+		$this->outputFile=$file;
119
+	}
120 120
     
121 121
 }
122 122
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -4,17 +4,17 @@  discard block
 block discarded – undo
4 4
 
5 5
 use Exception;
6 6
 
7
-define("ERROR", 1);define("WARN", 2);define("INFO", 3);define("DEBUG", 4);
7
+define("ERROR", 1); define("WARN", 2); define("INFO", 3); define("DEBUG", 4);
8 8
 
9 9
 class Logging
10 10
 {
11 11
 
12 12
     //**** Options from config database
13 13
     // Default values
14
-    public $debugLevel=2;  // 0=No output 1=critical 2=warning 3=trace 4=ALL
14
+    public $debugLevel=2; // 0=No output 1=critical 2=warning 3=trace 4=ALL
15 15
     public $outputMode='syslog'; // alert type : file, syslog, display
16 16
     public $outputFile="/tmp/trapdebug.txt";
17
-    protected $logLevels=array("","Error","Warning","Info","Debug");
17
+    protected $logLevels=array("", "Error", "Warning", "Info", "Debug");
18 18
     protected $outputList=array('file', 'syslog', 'display');
19 19
     
20 20
     /** Send log. Throws exception on critical error
@@ -24,29 +24,29 @@  discard block
 block discarded – undo
24 24
      *	@return void
25 25
      *  @throws Exception
26 26
      **/
27
-    public function log( $message, $level, $destination ='')
27
+    public function log($message, $level, $destination='')
28 28
     {
29 29
         if ($this->debugLevel >= $level)
30 30
         {
31
-            $message = '['.  date("Y/m/d H:i:s") . '] ' .
32
-                '[TrapDirector] ['.$this->logLevels[$level].']: ' .$message . "\n";
31
+            $message='['.date("Y/m/d H:i:s").'] '.
32
+                '[TrapDirector] ['.$this->logLevels[$level].']: '.$message."\n";
33 33
             
34
-            $output = ( $destination != '' ) ? $destination : $this->outputMode;
34
+            $output=($destination != '') ? $destination : $this->outputMode;
35 35
             switch ($output)
36 36
             {
37 37
                 case 'file':
38
-                    file_put_contents ($this->outputFile, $message , FILE_APPEND);
38
+                    file_put_contents($this->outputFile, $message, FILE_APPEND);
39 39
                     break;
40 40
                 case 'syslog':
41
-                    switch($level)
41
+                    switch ($level)
42 42
                     {
43
-                        case 1 : $prio = LOG_ERR;break;
44
-                        case 2 : $prio = LOG_WARNING;break;
45
-                        case 3 : $prio = LOG_INFO;break;
46
-                        case 4 : $prio = LOG_DEBUG;break;
47
-                        default: $prio = LOG_ERR;
43
+                        case 1 : $prio=LOG_ERR; break;
44
+                        case 2 : $prio=LOG_WARNING; break;
45
+                        case 3 : $prio=LOG_INFO; break;
46
+                        case 4 : $prio=LOG_DEBUG; break;
47
+                        default: $prio=LOG_ERR;
48 48
                     }
49
-                    syslog($prio,$message);
49
+                    syslog($prio, $message);
50 50
                     break;
51 51
                 case 'display':
52 52
                     echo $message;
@@ -62,7 +62,7 @@  discard block
 block discarded – undo
62 62
     }
63 63
     
64 64
         
65
-    public function setLogging($debugLvl,$outputType,$outputFile=null)
65
+    public function setLogging($debugLvl, $outputType, $outputFile=null)
66 66
     {
67 67
         $this->setLevel($debugLvl);
68 68
         switch ($outputType)
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
      */
99 99
     public function setDestination($destination)
100 100
     {
101
-        if (!is_string($destination) || ! in_array($destination, $this->outputList))
101
+        if (!is_string($destination) || !in_array($destination, $this->outputList))
102 102
         {
103 103
             throw new Exception('Invalid log destination');
104 104
         }
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -68,7 +68,9 @@
 block discarded – undo
68 68
         switch ($outputType)
69 69
         {
70 70
             case 'file':
71
-                if ($outputFile == null) throw new Exception("File logging without file !");
71
+                if ($outputFile == null) {
72
+                	throw new Exception("File logging without file !");
73
+                }
72 74
                 $this->setFile($outputFile);
73 75
                 $this->setDestination('file');
74 76
                 break;
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Database.php 2 patches
Indentation   +110 added lines, -110 removed lines patch added patch discarded remove patch
@@ -11,128 +11,128 @@
 block discarded – undo
11 11
 class Database
12 12
 {
13 13
 
14
-    // Databases
15
-    protected $trapDB=null; //< trap database
16
-    protected $idoDB=null; //< ido database
17
-    public $trapDBType; //< Type of database for traps (mysql, pgsql)
18
-    public $idoDBType; //< Type of database for ido (mysql, pgsql)
14
+	// Databases
15
+	protected $trapDB=null; //< trap database
16
+	protected $idoDB=null; //< ido database
17
+	public $trapDBType; //< Type of database for traps (mysql, pgsql)
18
+	public $idoDBType; //< Type of database for ido (mysql, pgsql)
19 19
     
20
-    protected $trapDSN; //< trap database connection params
21
-    protected $trapUsername; //< trap database connection params
22
-    protected $trapPass; //< trap database connection params
20
+	protected $trapDSN; //< trap database connection params
21
+	protected $trapUsername; //< trap database connection params
22
+	protected $trapPass; //< trap database connection params
23 23
     
24
-    protected $idoSet; //< bool true is ido database set
25
-    protected $idoDSN; //< trap database connection params
26
-    protected $idoUsername; //< trap database connection params
27
-    protected $idoPass; //< trap database connection params
24
+	protected $idoSet; //< bool true is ido database set
25
+	protected $idoDSN; //< trap database connection params
26
+	protected $idoUsername; //< trap database connection params
27
+	protected $idoPass; //< trap database connection params
28 28
     
29
-    // Logging function
29
+	// Logging function
30 30
     
31
-    protected $logging; //< logging class
31
+	protected $logging; //< logging class
32 32
     
33
-    /**
34
-     * @param Logging $logClass : where to log
35
-     * @param array $dbParam : array of named params  type,host,dbname,username,[port],[password]
36
-     */
37
-    function __construct($logClass,$dbParam)
38
-    {
39
-        $this->logging=$logClass;
33
+	/**
34
+	 * @param Logging $logClass : where to log
35
+	 * @param array $dbParam : array of named params  type,host,dbname,username,[port],[password]
36
+	 */
37
+	function __construct($logClass,$dbParam)
38
+	{
39
+		$this->logging=$logClass;
40 40
         
41
-        $this->trapDSN=$this->setupDSN($dbParam);
42
-        $this->trapUsername = $dbParam['username'];
43
-        $this->trapPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
44
-        $this->trapDBType=$dbParam['db'];
45
-        $this->logging->log('DSN : '.$this->trapDSN. ';user '.$this->trapUsername,INFO);
46
-        $this->db_connect_trap();
41
+		$this->trapDSN=$this->setupDSN($dbParam);
42
+		$this->trapUsername = $dbParam['username'];
43
+		$this->trapPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
44
+		$this->trapDBType=$dbParam['db'];
45
+		$this->logging->log('DSN : '.$this->trapDSN. ';user '.$this->trapUsername,INFO);
46
+		$this->db_connect_trap();
47 47
         
48
-    }
48
+	}
49 49
     
50
-    /**
51
-     * Setup and connect to IDO database
52
-     * @param array $dbParam : array of named params
53
-     */
54
-    public function setupIDO($dbParam)
55
-    {
56
-        $this->idoDSN=$this->setupDSN($dbParam);
57
-        $this->idoUsername = $dbParam['username'];
58
-        $this->idoPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
59
-        $this->logging->log('DSN : '.$this->idoDSN. ';user '.$this->idoUsername,INFO);
60
-        $this->idoDBType=$dbParam['db'];
61
-        $this->db_connect_ido();
62
-    }
50
+	/**
51
+	 * Setup and connect to IDO database
52
+	 * @param array $dbParam : array of named params
53
+	 */
54
+	public function setupIDO($dbParam)
55
+	{
56
+		$this->idoDSN=$this->setupDSN($dbParam);
57
+		$this->idoUsername = $dbParam['username'];
58
+		$this->idoPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
59
+		$this->logging->log('DSN : '.$this->idoDSN. ';user '.$this->idoUsername,INFO);
60
+		$this->idoDBType=$dbParam['db'];
61
+		$this->db_connect_ido();
62
+	}
63 63
     
64
-    /**
65
-     * Connect to IDO database
66
-     * @return \PDO
67
-     */
68
-    public function db_connect_ido()
69
-    {
70
-        if ($this->idoDB != null) {
71
-            // Check if connection is still alive
72
-            try {
73
-                $this->idoDB->query('select 1')->fetchColumn();
74
-                return $this->idoDB;
75
-            } catch (Exception $e) {
76
-                // select 1 failed, try to reconnect.
77
-                $this->logging->log('Database IDO connection lost, reconnecting',WARN);
78
-            }
79
-        }
80
-        try {
81
-            $this->idoDB = new PDO($this->idoDSN,$this->idoUsername,$this->idoPass);
82
-        } catch (PDOException $e) {
83
-            $this->logging->log('Connection failed to IDO : ' . $e->getMessage(),ERROR,'');
84
-        }
85
-        return $this->idoDB;
86
-    }
64
+	/**
65
+	 * Connect to IDO database
66
+	 * @return \PDO
67
+	 */
68
+	public function db_connect_ido()
69
+	{
70
+		if ($this->idoDB != null) {
71
+			// Check if connection is still alive
72
+			try {
73
+				$this->idoDB->query('select 1')->fetchColumn();
74
+				return $this->idoDB;
75
+			} catch (Exception $e) {
76
+				// select 1 failed, try to reconnect.
77
+				$this->logging->log('Database IDO connection lost, reconnecting',WARN);
78
+			}
79
+		}
80
+		try {
81
+			$this->idoDB = new PDO($this->idoDSN,$this->idoUsername,$this->idoPass);
82
+		} catch (PDOException $e) {
83
+			$this->logging->log('Connection failed to IDO : ' . $e->getMessage(),ERROR,'');
84
+		}
85
+		return $this->idoDB;
86
+	}
87 87
     
88
-    /**
89
-     * Connect to Trap database
90
-     * @return \PDO
91
-     */
92
-    public function db_connect_trap()
93
-    {
88
+	/**
89
+	 * Connect to Trap database
90
+	 * @return \PDO
91
+	 */
92
+	public function db_connect_trap()
93
+	{
94 94
         
95
-        if ($this->trapDB != null) {
96
-            // Check if connection is still alive
97
-            try {
98
-                $this->trapDB->query('select 1')->fetchColumn();
99
-                return $this->trapDB;
100
-            } catch (Exception $e) {
101
-                // select 1 failed, try to reconnect.
102
-                $this->logging->log('Database connection lost, reconnecting',WARN);
103
-            }           
104
-        }       
105
-        try {
106
-            $this->trapDB = new PDO($this->trapDSN,$this->trapUsername,$this->trapPass);
107
-        } catch (PDOException $e) {
108
-            $this->logging->log('Connection failed : ' . $e->getMessage(),ERROR,'');
109
-        }
110
-        return $this->trapDB;
111
-    }
95
+		if ($this->trapDB != null) {
96
+			// Check if connection is still alive
97
+			try {
98
+				$this->trapDB->query('select 1')->fetchColumn();
99
+				return $this->trapDB;
100
+			} catch (Exception $e) {
101
+				// select 1 failed, try to reconnect.
102
+				$this->logging->log('Database connection lost, reconnecting',WARN);
103
+			}           
104
+		}       
105
+		try {
106
+			$this->trapDB = new PDO($this->trapDSN,$this->trapUsername,$this->trapPass);
107
+		} catch (PDOException $e) {
108
+			$this->logging->log('Connection failed : ' . $e->getMessage(),ERROR,'');
109
+		}
110
+		return $this->trapDB;
111
+	}
112 112
     
113
-    /**
114
-     * Setup dsn and check parameters
115
-     * @param array $configElmt
116
-     * @return string
117
-     */
118
-    protected function setupDSN($configElmt)  
119
-    {
120
-        if (!array_key_exists('db',$configElmt) ||
121
-            !array_key_exists('host',$configElmt) ||
122
-            !array_key_exists('dbname',$configElmt) ||
123
-            !array_key_exists('username',$configElmt))
124
-        {
125
-            $this->logging->log('Missing DB params',ERROR);
126
-            return ''; 
127
-        }
113
+	/**
114
+	 * Setup dsn and check parameters
115
+	 * @param array $configElmt
116
+	 * @return string
117
+	 */
118
+	protected function setupDSN($configElmt)  
119
+	{
120
+		if (!array_key_exists('db',$configElmt) ||
121
+			!array_key_exists('host',$configElmt) ||
122
+			!array_key_exists('dbname',$configElmt) ||
123
+			!array_key_exists('username',$configElmt))
124
+		{
125
+			$this->logging->log('Missing DB params',ERROR);
126
+			return ''; 
127
+		}
128 128
         
129
-        //	$dsn = 'mysql:dbname=traps;host=127.0.0.1';
130
-        $dsn= $configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
129
+		//	$dsn = 'mysql:dbname=traps;host=127.0.0.1';
130
+		$dsn= $configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
131 131
         
132
-        if (array_key_exists('port', $configElmt))
133
-        {
134
-            $dsn .= ';port='.$configElmt['port'];
135
-        }
136
-        return $dsn;
137
-    }
132
+		if (array_key_exists('port', $configElmt))
133
+		{
134
+			$dsn .= ';port='.$configElmt['port'];
135
+		}
136
+		return $dsn;
137
+	}
138 138
 }
139 139
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -34,15 +34,15 @@  discard block
 block discarded – undo
34 34
      * @param Logging $logClass : where to log
35 35
      * @param array $dbParam : array of named params  type,host,dbname,username,[port],[password]
36 36
      */
37
-    function __construct($logClass,$dbParam)
37
+    function __construct($logClass, $dbParam)
38 38
     {
39 39
         $this->logging=$logClass;
40 40
         
41 41
         $this->trapDSN=$this->setupDSN($dbParam);
42
-        $this->trapUsername = $dbParam['username'];
43
-        $this->trapPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
42
+        $this->trapUsername=$dbParam['username'];
43
+        $this->trapPass=(array_key_exists('password', $dbParam)) ? $dbParam['password'] : '';
44 44
         $this->trapDBType=$dbParam['db'];
45
-        $this->logging->log('DSN : '.$this->trapDSN. ';user '.$this->trapUsername,INFO);
45
+        $this->logging->log('DSN : '.$this->trapDSN.';user '.$this->trapUsername, INFO);
46 46
         $this->db_connect_trap();
47 47
         
48 48
     }
@@ -54,9 +54,9 @@  discard block
 block discarded – undo
54 54
     public function setupIDO($dbParam)
55 55
     {
56 56
         $this->idoDSN=$this->setupDSN($dbParam);
57
-        $this->idoUsername = $dbParam['username'];
58
-        $this->idoPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
59
-        $this->logging->log('DSN : '.$this->idoDSN. ';user '.$this->idoUsername,INFO);
57
+        $this->idoUsername=$dbParam['username'];
58
+        $this->idoPass=(array_key_exists('password', $dbParam)) ? $dbParam['password'] : '';
59
+        $this->logging->log('DSN : '.$this->idoDSN.';user '.$this->idoUsername, INFO);
60 60
         $this->idoDBType=$dbParam['db'];
61 61
         $this->db_connect_ido();
62 62
     }
@@ -74,13 +74,13 @@  discard block
 block discarded – undo
74 74
                 return $this->idoDB;
75 75
             } catch (Exception $e) {
76 76
                 // select 1 failed, try to reconnect.
77
-                $this->logging->log('Database IDO connection lost, reconnecting',WARN);
77
+                $this->logging->log('Database IDO connection lost, reconnecting', WARN);
78 78
             }
79 79
         }
80 80
         try {
81
-            $this->idoDB = new PDO($this->idoDSN,$this->idoUsername,$this->idoPass);
81
+            $this->idoDB=new PDO($this->idoDSN, $this->idoUsername, $this->idoPass);
82 82
         } catch (PDOException $e) {
83
-            $this->logging->log('Connection failed to IDO : ' . $e->getMessage(),ERROR,'');
83
+            $this->logging->log('Connection failed to IDO : '.$e->getMessage(), ERROR, '');
84 84
         }
85 85
         return $this->idoDB;
86 86
     }
@@ -99,13 +99,13 @@  discard block
 block discarded – undo
99 99
                 return $this->trapDB;
100 100
             } catch (Exception $e) {
101 101
                 // select 1 failed, try to reconnect.
102
-                $this->logging->log('Database connection lost, reconnecting',WARN);
102
+                $this->logging->log('Database connection lost, reconnecting', WARN);
103 103
             }           
104 104
         }       
105 105
         try {
106
-            $this->trapDB = new PDO($this->trapDSN,$this->trapUsername,$this->trapPass);
106
+            $this->trapDB=new PDO($this->trapDSN, $this->trapUsername, $this->trapPass);
107 107
         } catch (PDOException $e) {
108
-            $this->logging->log('Connection failed : ' . $e->getMessage(),ERROR,'');
108
+            $this->logging->log('Connection failed : '.$e->getMessage(), ERROR, '');
109 109
         }
110 110
         return $this->trapDB;
111 111
     }
@@ -117,21 +117,21 @@  discard block
 block discarded – undo
117 117
      */
118 118
     protected function setupDSN($configElmt)  
119 119
     {
120
-        if (!array_key_exists('db',$configElmt) ||
121
-            !array_key_exists('host',$configElmt) ||
122
-            !array_key_exists('dbname',$configElmt) ||
123
-            !array_key_exists('username',$configElmt))
120
+        if (!array_key_exists('db', $configElmt) ||
121
+            !array_key_exists('host', $configElmt) ||
122
+            !array_key_exists('dbname', $configElmt) ||
123
+            !array_key_exists('username', $configElmt))
124 124
         {
125
-            $this->logging->log('Missing DB params',ERROR);
125
+            $this->logging->log('Missing DB params', ERROR);
126 126
             return ''; 
127 127
         }
128 128
         
129 129
         //	$dsn = 'mysql:dbname=traps;host=127.0.0.1';
130
-        $dsn= $configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
130
+        $dsn=$configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
131 131
         
132 132
         if (array_key_exists('port', $configElmt))
133 133
         {
134
-            $dsn .= ';port='.$configElmt['port'];
134
+            $dsn.=';port='.$configElmt['port'];
135 135
         }
136 136
         return $dsn;
137 137
     }
Please login to merge, or discard this patch.
application/controllers/ReceivedController.php 2 patches
Spacing   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -20,19 +20,19 @@  discard block
 block discarded – undo
20 20
 		$this->checkReadPermission();
21 21
 		$this->prepareTabs()->activate('traps');
22 22
 
23
-		$db = $this->getDb();
23
+		$db=$this->getDb();
24 24
 		$this->getTrapListTable()->setConnection($db);
25 25
 		
26 26
 		// Apply pagination limits
27
-		$this->view->table=$this->applyPaginationLimits($this->getTrapListTable(),$this->getModuleConfig()->itemListDisplay());		
27
+		$this->view->table=$this->applyPaginationLimits($this->getTrapListTable(), $this->getModuleConfig()->itemListDisplay());		
28 28
 		
29 29
 		// Set Filter
30 30
 		//$postData=$this->getRequest()->getPost();
31 31
 		$filter=array();
32
-		$filter['q']=$this->params->get('q');//(isset($postData['q']))?$postData['q']:'';
32
+		$filter['q']=$this->params->get('q'); //(isset($postData['q']))?$postData['q']:'';
33 33
 		$filter['done']=$this->params->get('done');
34 34
 		$this->view->filter=$filter;
35
-		$this->view->table->updateFilter(Url::fromRequest(),$filter);
35
+		$this->view->table->updateFilter(Url::fromRequest(), $filter);
36 36
 		
37 37
 		//$this->view->filterEditor = $this->getTrapListTable()->getFilterEditor($this->getRequest());
38 38
 
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
 		
47 47
 		$this->checkReadPermission();
48 48
 		// set up tab
49
-		$this->getTabs()->add('get',array(
49
+		$this->getTabs()->add('get', array(
50 50
 			'active'	=> true,
51 51
 			'label'		=> $this->translate('Detailed status'),
52 52
 			'url'		=> Url::fromRequest()
@@ -56,11 +56,11 @@  discard block
 block discarded – undo
56 56
 		$this->view->trapid=$trapid;
57 57
 		$queryArray=$this->getModuleConfig()->trapDetailQuery();
58 58
 		
59
-		$db = $this->getDb()->getConnection();
59
+		$db=$this->getDb()->getConnection();
60 60
 		
61 61
 		// URL to add a handler
62 62
 		$this->view->addHandlerUrl=Url::fromPath(
63
-			$this->getModuleConfig()->urlPath() . '/handler/add',
63
+			$this->getModuleConfig()->urlPath().'/handler/add',
64 64
 			array('fromid' => $trapid));
65 65
 		// ***************  Get main data
66 66
 		// extract columns and titles;
@@ -72,28 +72,28 @@  discard block
 block discarded – undo
72 72
 		// Do DB query for trap. 
73 73
 		try
74 74
 		{
75
-			$query = $db->select()
76
-				->from($this->moduleConfig->getTrapTableName(),$elmts)
77
-				->where('id=?',$trapid);
75
+			$query=$db->select()
76
+				->from($this->moduleConfig->getTrapTableName(), $elmts)
77
+				->where('id=?', $trapid);
78 78
 			$trapDetail=$db->fetchRow($query);
79
-			if ( $trapDetail == null) throw new Exception('No traps was found with id = '.$trapid);
79
+			if ($trapDetail == null) throw new Exception('No traps was found with id = '.$trapid);
80 80
 		}
81 81
 		catch (Exception $e)
82 82
 		{
83
-			$this->displayExitError('Trap detail',$e->getMessage());
83
+			$this->displayExitError('Trap detail', $e->getMessage());
84 84
 			return;
85 85
 		}
86 86
 
87 87
 		// Store result in array (with Titles).
88 88
 		foreach ($queryArray as $key => $val) {
89 89
 			if ($key == 'timestamp') {
90
-				$cval=strftime('%c',$trapDetail->$key);
90
+				$cval=strftime('%c', $trapDetail->$key);
91 91
 			} else {
92 92
 				$cval=$trapDetail->$key;
93 93
 			}
94
-			array_push($queryArray[$key],$cval);
94
+			array_push($queryArray[$key], $cval);
95 95
 		}
96
-		$this->view->rowset = $queryArray;
96
+		$this->view->rowset=$queryArray;
97 97
 
98 98
 		// **************   Check for additionnal data
99 99
 		
@@ -105,17 +105,17 @@  discard block
 block discarded – undo
105 105
 		}
106 106
 		try
107 107
 		{		
108
-			$query = $db->select()
109
-				->from($this->moduleConfig->getTrapDataTableName(),$data_elmts)
110
-				->where('trap_id=?',$trapid);
108
+			$query=$db->select()
109
+				->from($this->moduleConfig->getTrapDataTableName(), $data_elmts)
110
+				->where('trap_id=?', $trapid);
111 111
 			$trapDetail=$db->fetchAll($query);
112 112
 		}
113 113
 		catch (Exception $e)
114 114
 		{
115
-			$this->displayExitError('Trap detail',$e->getMessage());
115
+			$this->displayExitError('Trap detail', $e->getMessage());
116 116
 		}
117 117
 		// TODO : code this in a better & simpler way
118
-		if ($trapDetail == null ) 
118
+		if ($trapDetail == null) 
119 119
 		{
120 120
 			$this->view->data=false;
121 121
 		}
@@ -127,9 +127,9 @@  discard block
 block discarded – undo
127 127
 			foreach ($trapDetail as $key => $val) 
128 128
 			{	
129 129
 				$trapval[$key]=array();
130
-				foreach (array_keys($queryArrayData) as $vkey ) 
130
+				foreach (array_keys($queryArrayData) as $vkey) 
131 131
 				{
132
-					array_push($trapval[$key],$val->$vkey);
132
+					array_push($trapval[$key], $val->$vkey);
133 133
 				}
134 134
 			}
135 135
 			$this->view->data_val=$trapval;
@@ -145,19 +145,19 @@  discard block
 block discarded – undo
145 145
 	    $this->checkReadPermission();
146 146
 	    $this->prepareTabs()->activate('hosts');
147 147
 	    
148
-	    $db = $this->getDb();
148
+	    $db=$this->getDb();
149 149
 	    $this->getTrapHostListTable()->setConnection($db);
150 150
 	    
151 151
 	    // Apply pagination limits
152
-	    $this->view->table=$this->applyPaginationLimits($this->getTrapHostListTable(),$this->getModuleConfig()->itemListDisplay());
152
+	    $this->view->table=$this->applyPaginationLimits($this->getTrapHostListTable(), $this->getModuleConfig()->itemListDisplay());
153 153
 	    
154 154
 	    // Set Filter
155 155
 	    //$postData=$this->getRequest()->getPost();
156 156
 	    $filter=array();
157
-	    $filter['q']=$this->params->get('q');//(isset($postData['q']))?$postData['q']:'';
157
+	    $filter['q']=$this->params->get('q'); //(isset($postData['q']))?$postData['q']:'';
158 158
 	    $filter['done']=$this->params->get('done');
159 159
 	    $this->view->filter=$filter;
160
-	    $this->view->table->updateFilter(Url::fromRequest(),$filter);
160
+	    $this->view->table->updateFilter(Url::fromRequest(), $filter);
161 161
 	}
162 162
 	
163 163
 	public function deleteAction()
@@ -176,15 +176,15 @@  discard block
 block discarded – undo
176 176
 	{
177 177
 		return $this->getTabs()->add('traps', array(
178 178
 			'label'	=> $this->translate('Traps'),
179
-			'url'   => $this->getModuleConfig()->urlPath() . '/received')
179
+			'url'   => $this->getModuleConfig()->urlPath().'/received')
180 180
 		    )
181 181
 		    ->add('hosts', array(
182 182
 		        'label' => $this->translate('Hosts'),
183
-		        'url'   => $this->getModuleConfig()->urlPath() . '/received/hosts')
183
+		        'url'   => $this->getModuleConfig()->urlPath().'/received/hosts')
184 184
 		    )
185 185
 		    ->add('delete', array(
186 186
 			'label' => $this->translate('Delete'),
187
-			'url'   => $this->getModuleConfig()->urlPath() . '/received/delete')
187
+			'url'   => $this->getModuleConfig()->urlPath().'/received/delete')
188 188
 		  );
189 189
 	} 
190 190
 
@@ -211,14 +211,14 @@  discard block
 block discarded – undo
211 211
 			$this->_helper->json(array('status'=>'Missing variables'));
212 212
 			return;
213 213
 		}
214
-		if ($action =="count")
214
+		if ($action == "count")
215 215
 		{
216
-			$this->_helper->json(array('status'=>'OK','count'=>$this->countTrap($ip,$oid)));
216
+			$this->_helper->json(array('status'=>'OK', 'count'=>$this->countTrap($ip, $oid)));
217 217
 			return;
218 218
 		}
219
-		if ($action =="delete")
219
+		if ($action == "delete")
220 220
 		{
221
-			$this->_helper->json(array('status'=>'OK','count'=>$this->deleteTrap($ip,$oid)));
221
+			$this->_helper->json(array('status'=>'OK', 'count'=>$this->deleteTrap($ip, $oid)));
222 222
 			return;
223 223
 		}		
224 224
 		$this->_helper->json(array('status'=>'unknown action'));
Please login to merge, or discard this patch.
Braces   +7 added lines, -9 removed lines patch added patch discarded remove patch
@@ -76,9 +76,10 @@  discard block
 block discarded – undo
76 76
 				->from($this->moduleConfig->getTrapTableName(),$elmts)
77 77
 				->where('id=?',$trapid);
78 78
 			$trapDetail=$db->fetchRow($query);
79
-			if ( $trapDetail == null) throw new Exception('No traps was found with id = '.$trapid);
80
-		}
81
-		catch (Exception $e)
79
+			if ( $trapDetail == null) {
80
+				throw new Exception('No traps was found with id = '.$trapid);
81
+			}
82
+		} catch (Exception $e)
82 83
 		{
83 84
 			$this->displayExitError('Trap detail',$e->getMessage());
84 85
 			return;
@@ -109,8 +110,7 @@  discard block
 block discarded – undo
109 110
 				->from($this->moduleConfig->getTrapDataTableName(),$data_elmts)
110 111
 				->where('trap_id=?',$trapid);
111 112
 			$trapDetail=$db->fetchAll($query);
112
-		}
113
-		catch (Exception $e)
113
+		} catch (Exception $e)
114 114
 		{
115 115
 			$this->displayExitError('Trap detail',$e->getMessage());
116 116
 		}
@@ -118,8 +118,7 @@  discard block
 block discarded – undo
118 118
 		if ($trapDetail == null ) 
119 119
 		{
120 120
 			$this->view->data=false;
121
-		}
122
-		else
121
+		} else
123 122
 		{
124 123
 			$this->view->data=true;
125 124
 			// Store result in array.
@@ -205,8 +204,7 @@  discard block
 block discarded – undo
205 204
 			$ip=$postData['IP'];
206 205
 			$oid=$postData['OID'];
207 206
 			$action=$postData['action'];
208
-		}
209
-		else
207
+		} else
210 208
 		{
211 209
 			$this->_helper->json(array('status'=>'Missing variables'));
212 210
 			return;
Please login to merge, or discard this patch.