Passed
Push — master ( 300cc7...278791 )
by Patrick
01:59
created
bin/trap_class.php 1 patch
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.
library/Trapdirector/TrapsProcess/Rule.php 1 patch
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.
application/controllers/HelperController.php 1 patch
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.
application/controllers/SettingsController.php 1 patch
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.