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