Passed
Push — master ( 6af608...f4805a )
by Patrick
03:21
created
bin/trap_class.php 3 patches
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.
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|boolean : PDO object or false
618
-	*/	
615
+	 *	@param $ip string ipv4 or ipv6
616
+	 *	@param $oid string oid in numeric
617
+	 *	@return mixed|boolean : 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|boolean : PDO object or false
618 618
 	*/	
619
-	protected function getRules($ip,$oid)
619
+	protected function getRules($ip, $oid)
620 620
 	{
621 621
 		$db_conn=$this->trapsDB->db_connect_trap();
622 622
 		// fetch rules based on IP in rule and OID
623 623
 		$sql='SELECT * from '.$this->db_prefix.'rules WHERE trap_oid=\''.$oid.'\' ';
624
-		$this->logging->log('SQL query : '.$sql,DEBUG );
624
+		$this->logging->log('SQL query : '.$sql, DEBUG);
625 625
 		if (($ret_code=$db_conn->query($sql)) === false) {
626
-			$this->logging->log('No result in query : ' . $sql,WARN,'');
626
+			$this->logging->log('No result in query : '.$sql, WARN, '');
627 627
 			return false;
628 628
 		}
629 629
 		$rules_all=$ret_code->fetchAll();
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
 		$rule_ret_key=0;
633 633
 		foreach ($rules_all as $key => $rule)
634 634
 		{
635
-			if ($rule['ip4']==$ip || $rule['ip6']==$ip)
635
+			if ($rule['ip4'] == $ip || $rule['ip6'] == $ip)
636 636
 			{
637 637
 				$rules_ret[$rule_ret_key]=$rules_all[$key];
638 638
 				//TODO : get host name by API (and check if correct in rule).
@@ -640,7 +640,7 @@  discard block
 block discarded – undo
640 640
 				continue;
641 641
 			}
642 642
 			// TODO : get hosts IP by API
643
-			if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
643
+			if (isset($rule['host_group_name']) && $rule['host_group_name'] != null)
644 644
 			{ // get ips of group members by oid
645 645
 				$db_conn2=$this->trapsDB->db_connect_ido();
646 646
 				$sql="SELECT m.host_object_id, a.address as ip4, a.address6 as ip6, b.name1 as host_name
@@ -651,15 +651,15 @@  discard block
 block discarded – undo
651 651
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
652 652
 						WHERE o.name1='".$rule['host_group_name']."';";
653 653
 				if (($ret_code2=$db_conn2->query($sql)) === false) {
654
-					$this->logging->log('No result in query : ' . $sql,WARN,'');
654
+					$this->logging->log('No result in query : '.$sql, WARN, '');
655 655
 					continue;
656 656
 				}
657 657
 				$grouphosts=$ret_code2->fetchAll();
658 658
 				//echo "rule grp :\n";print_r($grouphosts);echo "\n";
659
-				foreach ( $grouphosts as $host)
659
+				foreach ($grouphosts as $host)
660 660
 				{
661 661
 					//echo $host['ip4']."\n";
662
-					if ($host['ip4']==$ip || $host['ip6']==$ip)
662
+					if ($host['ip4'] == $ip || $host['ip6'] == $ip)
663 663
 					{
664 664
 						//echo "Rule added \n";
665 665
 						$rules_ret[$rule_ret_key]=$rules_all[$key];
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
 		$db_conn=$this->trapsDB->db_connect_trap();
683 683
 		$sql="UPDATE ".$this->db_prefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
684 684
 		if ($db_conn->query($sql) === false) {
685
-			$this->logging->log('Error in update query : ' . $sql,WARN,'');
685
+			$this->logging->log('Error in update query : '.$sql, WARN, '');
686 686
 		}
687 687
 	}
688 688
 	
@@ -694,31 +694,31 @@  discard block
 block discarded – undo
694 694
 	 * @param string $display
695 695
 	 * @returnn bool true is service check was sent without error
696 696
 	*/
697
-	public function serviceCheckResult($host,$service,$state,$display)
697
+	public function serviceCheckResult($host, $service, $state, $display)
698 698
 	{
699 699
 	    if ($this->api_use === false)
700 700
 	    {
701
-    		$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
702
-    			$host.';' .$service .';' . $state . ';'.$display;
703
-    		$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
701
+    		$send='['.date('U').'] PROCESS_SERVICE_CHECK_RESULT;'.
702
+    			$host.';'.$service.';'.$state.';'.$display;
703
+    		$this->logging->log($send." : to : ".$this->icinga2cmd, INFO);
704 704
     		
705 705
     		// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
706
-    		exec('echo "'.$send.'" > ' .$this->icinga2cmd);
706
+    		exec('echo "'.$send.'" > '.$this->icinga2cmd);
707 707
     		return true;
708 708
 	    }
709 709
 	    else
710 710
 	    {
711
-	        $api = $this->getAPI();
711
+	        $api=$this->getAPI();
712 712
 	        $api->setCredentials($this->api_username, $this->api_password);
713
-	        list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display);
713
+	        list($retcode, $retmessage)=$api->serviceCheckResult($host, $service, $state, $display);
714 714
 	        if ($retcode == false)
715 715
 	        {
716
-	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
716
+	            $this->logging->log("Error sending result : ".$retmessage, WARN, '');
717 717
 	            return false;
718 718
 	        }
719 719
 	        else 
720 720
 	        {
721
-	            $this->logging->log( "Sent result : " .$retmessage,INFO );
721
+	            $this->logging->log("Sent result : ".$retmessage, INFO);
722 722
 	            return true;
723 723
 	        }
724 724
 	    }
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
 	
727 727
 	public function getHostByIP($ip)
728 728
 	{
729
-	    $api = $this->getAPI();
729
+	    $api=$this->getAPI();
730 730
 	    $api->setCredentials($this->api_username, $this->api_password);
731 731
 	    return $api->getHostByIP($ip);
732 732
 	}
@@ -739,32 +739,32 @@  discard block
 block discarded – undo
739 739
 	protected function applyDisplay($display)
740 740
 	{
741 741
 	    $matches=array();
742
-	    while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
742
+	    while (preg_match('/_OID\(([0-9\.]+)\)/', $display, $matches) == 1)
743 743
 		{
744 744
 			$oid=$matches[1];
745 745
 			$found=0;
746
-			foreach($this->trap_data_ext as $val)
746
+			foreach ($this->trap_data_ext as $val)
747 747
 			{
748 748
 				if ($oid == $val->oid)
749 749
 				{
750
-					$val->value=preg_replace('/"/','',$val->value);
750
+					$val->value=preg_replace('/"/', '', $val->value);
751 751
 					$rep=0;
752
-					$display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
753
-					if ($rep==0)
752
+					$display=preg_replace('/_OID\('.$oid.'\)/', $val->value, $display, -1, $rep);
753
+					if ($rep == 0)
754 754
 					{
755
-						$this->logging->log("Error in display",WARN,'');
755
+						$this->logging->log("Error in display", WARN, '');
756 756
 						return $display;
757 757
 					}
758 758
 					$found=1;
759 759
 					break;
760 760
 				}
761 761
 			}
762
-			if ($found==0)
762
+			if ($found == 0)
763 763
 			{
764
-				$display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
765
-				if ($rep==0)
764
+				$display=preg_replace('/_OID\('.$oid.'\)/', '<not in trap>', $display, -1, $rep);
765
+				if ($rep == 0)
766 766
 				{
767
-					$this->logging->log("Error in display",WARN,'');
767
+					$this->logging->log("Error in display", WARN, '');
768 768
 					return $display;
769 769
 				}				
770 770
 			}
@@ -776,11 +776,11 @@  discard block
 block discarded – undo
776 776
 	*/
777 777
 	public function applyRules()
778 778
 	{
779
-		$rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
779
+		$rules=$this->getRules($this->trap_data['source_ip'], $this->trap_data['trap_oid']);
780 780
 		
781
-		if ($rules===false || count($rules)==0)
781
+		if ($rules === false || count($rules) == 0)
782 782
 		{
783
-			$this->logging->log('No rules found for this trap',INFO );
783
+			$this->logging->log('No rules found for this trap', INFO);
784 784
 			$this->trap_data['status']='unknown';
785 785
 			$this->trap_to_db=true;
786 786
 			return;
@@ -795,59 +795,59 @@  discard block
 block discarded – undo
795 795
 			$service_name=$rule['service_name'];
796 796
 			
797 797
 			$display=$this->applyDisplay($rule['display']);
798
-			$this->trap_action = ($this->trap_action==null)? '' : $this->trap_action . ', ';
798
+			$this->trap_action=($this->trap_action == null) ? '' : $this->trap_action.', ';
799 799
 			try
800 800
 			{
801
-				$this->logging->log('Rule to eval : '.$rule['rule'],INFO );
802
-				$evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trap_data_ext) ;
801
+				$this->logging->log('Rule to eval : '.$rule['rule'], INFO);
802
+				$evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trap_data_ext);
803 803
 				//->eval_rule($rule['rule']);
804 804
 				
805 805
 				if ($evalr == true)
806 806
 				{
807 807
 					//$this->logging->log('rules OOK: '.print_r($rule),INFO );
808 808
 					$action=$rule['action_match'];
809
-					$this->logging->log('action OK : '.$action,INFO );
809
+					$this->logging->log('action OK : '.$action, INFO);
810 810
 					if ($action >= 0)
811 811
 					{
812
-						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
812
+						if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
813 813
 						{
814 814
 						    $this->trap_action.='Error sending status : check cmd/API';
815 815
 						}
816 816
 						else
817 817
 						{
818
-						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
818
+						    $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
819 819
 						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
820 820
 						}
821 821
 					}
822 822
 					else
823 823
 					{
824
-						$this->add_rule_match($rule['id'],$rule['num_match']+1);
824
+						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
825 825
 					}
826
-					$this->trap_to_db=($action==-2)?false:true;
826
+					$this->trap_to_db=($action == -2) ?false:true;
827 827
 				}
828 828
 				else
829 829
 				{
830 830
 					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
831 831
 					
832 832
 					$action=$rule['action_nomatch'];
833
-					$this->logging->log('action NOK : '.$action,INFO );
833
+					$this->logging->log('action NOK : '.$action, INFO);
834 834
 					if ($action >= 0)
835 835
 					{
836
-					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
836
+					    if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
837 837
 					    {
838 838
 					        $this->trap_action.='Error sending status : check cmd/API';
839 839
 					    }
840 840
 					    else
841 841
 					    {
842
-    						$this->add_rule_match($rule['id'],$rule['num_match']+1);
842
+    						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
843 843
     						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
844 844
 					    }
845 845
 					}
846 846
 					else
847 847
 					{
848
-						$this->add_rule_match($rule['id'],$rule['num_match']+1);
848
+						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
849 849
 					}
850
-					$this->trap_to_db=($action==-2)?false:true;					
850
+					$this->trap_to_db=($action == -2) ?false:true;					
851 851
 				}
852 852
 				// Put name in source_name
853 853
 				if (!isset($this->trap_data['source_name']))
@@ -856,7 +856,7 @@  discard block
 block discarded – undo
856 856
 				}
857 857
 				else
858 858
 				{
859
-					if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
859
+					if (!preg_match('/'.$rule['host_name'].'/', $this->trap_data['source_name']))
860 860
 					{ // only add if not present
861 861
 						$this->trap_data['source_name'].=','.$rule['host_name'];
862 862
 					}
@@ -864,13 +864,13 @@  discard block
 block discarded – undo
864 864
 			}
865 865
 			catch (Exception $e) 
866 866
 			{ 
867
-			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
867
+			    $this->logging->log('Error in rule eval : '.$e->getMessage(), WARN, '');
868 868
 			    $this->trap_action.=' ERR : '.$e->getMessage();
869 869
 			    $this->trap_data['status']='error';
870 870
 			}
871 871
 			
872 872
 		}
873
-		if ($this->trap_data['status']=='error')
873
+		if ($this->trap_data['status'] == 'error')
874 874
 		{
875 875
 		  $this->trap_to_db=true; // Always put errors in DB for the use can see
876 876
 		}
@@ -886,13 +886,13 @@  discard block
 block discarded – undo
886 886
 	public function add_rule_final($time)
887 887
 	{
888 888
 		$db_conn=$this->trapsDB->db_connect_trap();
889
-		if ($this->trap_action==null) 
889
+		if ($this->trap_action == null) 
890 890
 		{
891 891
 			$this->trap_action='No action';
892 892
 		}
893 893
 		$sql="UPDATE ".$this->db_prefix."received SET process_time = '".$time."' , status_detail='".$this->trap_action."'  WHERE (id = '".$this->trap_id."');";
894 894
 		if ($db_conn->query($sql) === false) {
895
-			$this->logging->log('Error in update query : ' . $sql,WARN,'');
895
+			$this->logging->log('Error in update query : '.$sql, WARN, '');
896 896
 		}
897 897
 	}
898 898
 	
@@ -915,7 +915,7 @@  discard block
 block discarded – undo
915 915
     WHERE s.current_state != 0;";
916 916
 		$db_conn=$this->trapsDB->db_connect_ido();
917 917
 		if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
918
-			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
918
+			$this->logging->log('No result in query : '.$sql_query, ERROR, '');
919 919
 			return 0;
920 920
 		}
921 921
 		$services=$services_db->fetchAll();
@@ -924,7 +924,7 @@  discard block
 block discarded – undo
924 924
 		$sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->db_prefix."rules where revert_ok != 0;";
925 925
 		$db_conn2=$this->trapsDB->db_connect_trap();
926 926
 		if (($rules_db=$db_conn2->query($sql_query)) === false) {
927
-			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
927
+			$this->logging->log('No result in query : '.$sql_query, ERROR, '');
928 928
 			return 0;
929 929
 		}
930 930
 		$rules=$rules_db->fetchAll();
@@ -940,13 +940,13 @@  discard block
 block discarded – undo
940 940
 					$service['host_name'] == $rule['host_name'] &&
941 941
 					($service['last_check'] + $rule['revert_ok']) < $now)
942 942
 				{
943
-					$this->serviceCheckResult($service['host_name'],$service['service_name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
943
+					$this->serviceCheckResult($service['host_name'], $service['service_name'], 0, 'Reset service to OK after '.$rule['revert_ok'].' seconds');
944 944
 					$numreset++;
945 945
 				}
946 946
 			}
947 947
 		}
948 948
 		echo "\n";
949
-		echo $numreset . " service(s) reset to OK\n";
949
+		echo $numreset." service(s) reset to OK\n";
950 950
 		return 0;
951 951
 		
952 952
 	}
Please login to merge, or discard this patch.
tests/expr_test.php 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.
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.
library/Trapdirector/TrapsProcess/Rule.php 3 patches
Indentation   +289 added lines, -289 removed lines patch added patch discarded remove patch
@@ -11,331 +11,331 @@
 block discarded – undo
11 11
 class Rule
12 12
 {
13 13
     
14
-    protected $logging; //< logging class
14
+	protected $logging; //< logging class
15 15
     
16
-    /**
17
-     * Setup Rule Class
18
-     * @param Logging $logClass : where to log
19
-     */
20
-    function __construct($logClass)
21
-    {
22
-        $this->logging=$logClass;
16
+	/**
17
+	 * Setup Rule Class
18
+	 * @param Logging $logClass : where to log
19
+	 */
20
+	function __construct($logClass)
21
+	{
22
+		$this->logging=$logClass;
23 23
 
24
-    }
24
+	}
25 25
 
26 26
 /**
27 27
  * Get full number 
28 28
  * @return array<number,string>
29 29
  */
30
-    private function get_number($rule,&$item)
31
-    {
32
-        $item2=$item+1;
33
-        while (
34
-            ($item2!=strlen($rule)) 
35
-            && (preg_match('/[0-9\.]/',$rule[$item2]))) 
36
-        { 
37
-            $item2++ ;
38
-        }
39
-        $val=substr($rule,$item,$item2-$item);
40
-        $item=$item2;
41
-        //echo "number ".$val."\n";
30
+	private function get_number($rule,&$item)
31
+	{
32
+		$item2=$item+1;
33
+		while (
34
+			($item2!=strlen($rule)) 
35
+			&& (preg_match('/[0-9\.]/',$rule[$item2]))) 
36
+		{ 
37
+			$item2++ ;
38
+		}
39
+		$val=substr($rule,$item,$item2-$item);
40
+		$item=$item2;
41
+		//echo "number ".$val."\n";
42 42
         
43
-        return array(0,$val);
44
-    }
43
+		return array(0,$val);
44
+	}
45 45
 
46
-    private function get_string($rule,&$item)
47
-    {
48
-        $item++;
49
-        $item2=$this->eval_getNext($rule,$item,'"');
50
-        $val=substr($rule,$item,$item2-$item-1);
51
-        $item=$item2;
52
-        //echo "string : ".$val."\n";
53
-        return array(1,$val);
46
+	private function get_string($rule,&$item)
47
+	{
48
+		$item++;
49
+		$item2=$this->eval_getNext($rule,$item,'"');
50
+		$val=substr($rule,$item,$item2-$item-1);
51
+		$item=$item2;
52
+		//echo "string : ".$val."\n";
53
+		return array(1,$val);
54 54
         
55
-    }
55
+	}
56 56
     
57
-    private function get_group($rule,&$item)
58
-    {
59
-        $item++;
60
-        $start=$item;
61
-        $parenthesis_count=0;
62
-        while (($item < strlen($rule)) // Not end of string AND
63
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
64
-        {
65
-            if ($rule[$item] == '"' )
66
-            { // pass through string
67
-                $item++;
68
-                $item=$this->eval_getNext($rule,$item,'"');
69
-            }
70
-            else{
71
-                if ($rule[$item] == '(')
72
-                {
73
-                    $parenthesis_count++;
74
-                }
75
-                if ($rule[$item] == ')')
76
-                {
77
-                    $parenthesis_count--;
78
-                }
79
-                $item++;
80
-            }
81
-        }
57
+	private function get_group($rule,&$item)
58
+	{
59
+		$item++;
60
+		$start=$item;
61
+		$parenthesis_count=0;
62
+		while (($item < strlen($rule)) // Not end of string AND
63
+			&& ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
64
+		{
65
+			if ($rule[$item] == '"' )
66
+			{ // pass through string
67
+				$item++;
68
+				$item=$this->eval_getNext($rule,$item,'"');
69
+			}
70
+			else{
71
+				if ($rule[$item] == '(')
72
+				{
73
+					$parenthesis_count++;
74
+				}
75
+				if ($rule[$item] == ')')
76
+				{
77
+					$parenthesis_count--;
78
+				}
79
+				$item++;
80
+			}
81
+		}
82 82
         
83
-        if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
84
-        $val=substr($rule,$start,$item-$start);
85
-        $item++;
86
-        $start=0;
87
-        //echo "group : ".$val."\n";
88
-        // returns evaluation of group as type 2 (boolean)
89
-        return array(2,$this->evaluation($val,$start));
90
-    }
83
+		if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
84
+		$val=substr($rule,$start,$item-$start);
85
+		$item++;
86
+		$start=0;
87
+		//echo "group : ".$val."\n";
88
+		// returns evaluation of group as type 2 (boolean)
89
+		return array(2,$this->evaluation($val,$start));
90
+	}
91 91
     
92
-    protected function eval_getElement($rule,&$item)
93
-    {
94
-        if ($item >= strlen($rule))
95
-        {
96
-            throw new Exception("Early end of string ".$rule ." at " .$item );
97
-        }
98
-        while ($rule[$item]==' ') $item++;
99
-        if (preg_match('/[0-9\.]/',$rule[$item]))
100
-        { // number
101
-            return $this->get_number($rule, $item);
102
-        }
103
-        if ($rule[$item] == '"')
104
-        { // string
105
-            return $this->get_string($rule, $item);
106
-        }
92
+	protected function eval_getElement($rule,&$item)
93
+	{
94
+		if ($item >= strlen($rule))
95
+		{
96
+			throw new Exception("Early end of string ".$rule ." at " .$item );
97
+		}
98
+		while ($rule[$item]==' ') $item++;
99
+		if (preg_match('/[0-9\.]/',$rule[$item]))
100
+		{ // number
101
+			return $this->get_number($rule, $item);
102
+		}
103
+		if ($rule[$item] == '"')
104
+		{ // string
105
+			return $this->get_string($rule, $item);
106
+		}
107 107
         
108
-        if ($rule[$item] == '(')
109
-        { // grouping
110
-            return $this->get_group($rule, $item);
111
-        }
112
-        throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
108
+		if ($rule[$item] == '(')
109
+		{ // grouping
110
+			return $this->get_group($rule, $item);
111
+		}
112
+		throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
113 113
         
114
-    }
114
+	}
115 115
     
116
-    protected function eval_getNext($rule,$item,$tok)
117
-    {
118
-        while (
119
-            ($rule[$item] != $tok ) 
120
-            && ($item < strlen($rule))) 
121
-        { 
122
-            $item++;
123
-        }
124
-        if ($item==strlen($rule)) {
125
-            throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
126
-        }
127
-        return $item+1;
128
-    }
116
+	protected function eval_getNext($rule,$item,$tok)
117
+	{
118
+		while (
119
+			($rule[$item] != $tok ) 
120
+			&& ($item < strlen($rule))) 
121
+		{ 
122
+			$item++;
123
+		}
124
+		if ($item==strlen($rule)) {
125
+			throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
126
+		}
127
+		return $item+1;
128
+	}
129 129
     
130
-    protected function eval_getOper($rule,&$item)
131
-    {
132
-        while ($rule[$item]==' ') $item++;
133
-        switch ($rule[$item])
134
-        {
135
-            case '<':
136
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
137
-                $item++; return array(0,"<");
138
-            case '>':
139
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
140
-                $item++; return array(0,">");
141
-            case '=':
142
-                $item++; return array(0,"=");
143
-            case '!':
144
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
145
-                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
146
-            case '~':
147
-                $item++; return array(0,"~");
148
-            case '|':
149
-                $item++; return array(1,"|");
150
-            case '&':
151
-                $item++; return array(1,"&");
152
-            default	:
153
-                throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
154
-        }
155
-    }
130
+	protected function eval_getOper($rule,&$item)
131
+	{
132
+		while ($rule[$item]==' ') $item++;
133
+		switch ($rule[$item])
134
+		{
135
+			case '<':
136
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
137
+				$item++; return array(0,"<");
138
+			case '>':
139
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
140
+				$item++; return array(0,">");
141
+			case '=':
142
+				$item++; return array(0,"=");
143
+			case '!':
144
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
145
+				throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
146
+			case '~':
147
+				$item++; return array(0,"~");
148
+			case '|':
149
+				$item++; return array(1,"|");
150
+			case '&':
151
+				$item++; return array(1,"&");
152
+			default	:
153
+				throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
154
+		}
155
+	}
156 156
     
157
-    private function check_negate_first($rule,&$item)
158
-    {
159
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
160
-        {
161
-            $item++;
162
-            return true;
163
-        }
164
-        else
165
-        {
166
-            return false;
167
-        }
168
-    }
157
+	private function check_negate_first($rule,&$item)
158
+	{
159
+		if ( $rule[$item] == '!') // If '!' found, negate next expression.
160
+		{
161
+			$item++;
162
+			return true;
163
+		}
164
+		else
165
+		{
166
+			return false;
167
+		}
168
+	}
169 169
 
170
-    private function do_compare($val1,$val2,$comp,$negate)
171
-    {
172
-        switch ($comp){
173
-            case '<':	$retVal= ($val1 < $val2); break;
174
-            case '<=':	$retVal= ($val1 <= $val2); break;
175
-            case '>':	$retVal= ($val1 > $val2); break;
176
-            case '>=':	$retVal= ($val1 >= $val2); break;
177
-            case '=':	$retVal= ($val1 == $val2); break;
178
-            case '!=':	$retVal= ($val1 != $val2); break;
179
-            case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
180
-            case '|':	$retVal= ($val1 || $val2); break;
181
-            case '&':	$retVal= ($val1 && $val2); break;
182
-            default:  throw new Exception("Error in expression - unknown comp : ".$comp);
183
-        }
184
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
170
+	private function do_compare($val1,$val2,$comp,$negate)
171
+	{
172
+		switch ($comp){
173
+			case '<':	$retVal= ($val1 < $val2); break;
174
+			case '<=':	$retVal= ($val1 <= $val2); break;
175
+			case '>':	$retVal= ($val1 > $val2); break;
176
+			case '>=':	$retVal= ($val1 >= $val2); break;
177
+			case '=':	$retVal= ($val1 == $val2); break;
178
+			case '!=':	$retVal= ($val1 != $val2); break;
179
+			case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
180
+			case '|':	$retVal= ($val1 || $val2); break;
181
+			case '&':	$retVal= ($val1 && $val2); break;
182
+			default:  throw new Exception("Error in expression - unknown comp : ".$comp);
183
+		}
184
+		if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
185 185
         
186
-        return $retVal;
187
-    }
186
+		return $retVal;
187
+	}
188 188
     
189
-    /** Evaluation : makes token and evaluate.
190
-     *	Public function for expressions testing
191
-     *	accepts : < > = <= >= !=  (typec = 0)
192
-     *	operators : & | (typec=1)
193
-     *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
194
-     *   comparison int vs strings will return null (error)
195
-     *	return : bool or null on error
196
-     */
197
-    public function evaluation($rule,&$item)
198
-    {
199
-        //echo "Evaluation of ".substr($rule,$item)."\n";
200
-        $negate=$this->check_negate_first($rule, $item);
201
-        // First element : number, string or ()
202
-        list($type1,$val1) = $this->eval_getElement($rule,$item);
203
-        //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
189
+	/** Evaluation : makes token and evaluate.
190
+	 *	Public function for expressions testing
191
+	 *	accepts : < > = <= >= !=  (typec = 0)
192
+	 *	operators : & | (typec=1)
193
+	 *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
194
+	 *   comparison int vs strings will return null (error)
195
+	 *	return : bool or null on error
196
+	 */
197
+	public function evaluation($rule,&$item)
198
+	{
199
+		//echo "Evaluation of ".substr($rule,$item)."\n";
200
+		$negate=$this->check_negate_first($rule, $item);
201
+		// First element : number, string or ()
202
+		list($type1,$val1) = $this->eval_getElement($rule,$item);
203
+		//echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
204 204
         
205
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
206
-        {
207
-            if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
208
-            if ($negate === true) $val1= ! $val1;
209
-            return $val1;
210
-        }
205
+		if ($item==strlen($rule)) // If only element, return value, but only boolean
206
+		{
207
+			if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
208
+			if ($negate === true) $val1= ! $val1;
209
+			return $val1;
210
+		}
211 211
         
212
-        // Second element : operator
213
-        list($typec,$comp) = $this->eval_getOper($rule,$item);
214
-        //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
212
+		// Second element : operator
213
+		list($typec,$comp) = $this->eval_getOper($rule,$item);
214
+		//echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
215 215
         
216
-        // Third element : number, string or ()
217
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
218
-        {
219
-            $item++;
220
-            if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
221
-            $val2= ! $this->evaluation($rule,$item);
222
-            $type2=2; // result is a boolean
223
-        }
224
-        else
225
-        {
226
-            list($type2,$val2) = $this->eval_getElement($rule,$item);
227
-        }
228
-        //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
216
+		// Third element : number, string or ()
217
+		if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
218
+		{
219
+			$item++;
220
+			if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
221
+			$val2= ! $this->evaluation($rule,$item);
222
+			$type2=2; // result is a boolean
223
+		}
224
+		else
225
+		{
226
+			list($type2,$val2) = $this->eval_getElement($rule,$item);
227
+		}
228
+		//echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
229 229
         
230
-        if ($type1!=$type2)  // cannot compare different types
231
-        {
232
-            throw new Exception("Cannot compare string & number : ".$rule);
233
-        }
234
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
235
-        {
236
-            throw new Exception("Cannot use boolean operators with string & number : ".$rule);
237
-        }
230
+		if ($type1!=$type2)  // cannot compare different types
231
+		{
232
+			throw new Exception("Cannot compare string & number : ".$rule);
233
+		}
234
+		if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
235
+		{
236
+			throw new Exception("Cannot use boolean operators with string & number : ".$rule);
237
+		}
238 238
         
239
-        $retVal = $this->do_compare($val1, $val2, $comp, $negate);
239
+		$retVal = $this->do_compare($val1, $val2, $comp, $negate);
240 240
         
241
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
242
-        // check for logical operator :
243
-        switch ($rule[$item])
244
-        {
245
-            case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
246
-            case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
241
+		if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
242
+		// check for logical operator :
243
+		switch ($rule[$item])
244
+		{
245
+			case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
246
+			case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
247 247
             
248
-            default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
249
-        }
250
-    }
248
+			default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
249
+		}
250
+	}
251 251
     
252
-    // Remove all whitespaces (when not quoted)
253
-    public function eval_cleanup($rule)
254
-    {
255
-        $item=0;
256
-        $rule2='';
257
-        while ($item < strlen($rule))
258
-        {
259
-            if ($rule[$item]==' ') { $item++; continue; }
260
-            if ($rule[$item]=='"')
261
-            {
262
-                $rule2.=$rule[$item];
263
-                $item++;
264
-                while (($item < strlen($rule)) && ($rule[$item]!='"') )
265
-                {
266
-                    $rule2.=$rule[$item];
267
-                    $item++;
268
-                }
269
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
270
-                $rule2.=$rule[$item];
271
-                $item++;
272
-                continue;
273
-            }
252
+	// Remove all whitespaces (when not quoted)
253
+	public function eval_cleanup($rule)
254
+	{
255
+		$item=0;
256
+		$rule2='';
257
+		while ($item < strlen($rule))
258
+		{
259
+			if ($rule[$item]==' ') { $item++; continue; }
260
+			if ($rule[$item]=='"')
261
+			{
262
+				$rule2.=$rule[$item];
263
+				$item++;
264
+				while (($item < strlen($rule)) && ($rule[$item]!='"') )
265
+				{
266
+					$rule2.=$rule[$item];
267
+					$item++;
268
+				}
269
+				if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
270
+				$rule2.=$rule[$item];
271
+				$item++;
272
+				continue;
273
+			}
274 274
             
275
-            $rule2.=$rule[$item];
276
-            $item++;
277
-        }
275
+			$rule2.=$rule[$item];
276
+			$item++;
277
+		}
278 278
         
279
-        return $rule2;
280
-    }
279
+		return $rule2;
280
+	}
281 281
     
282
-    /** Evaluation rule (uses eval_* functions recursively)
283
-     *	@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) )
284
-     *  @param array $oidList : OIDs values to sustitute.
285
-     *	@return bool : true : rule match, false : rule don't match , throw exception on error.
286
-     */
282
+	/** Evaluation rule (uses eval_* functions recursively)
283
+	 *	@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) )
284
+	 *  @param array $oidList : OIDs values to sustitute.
285
+	 *	@return bool : true : rule match, false : rule don't match , throw exception on error.
286
+	 */
287 287
     
288
-    public function eval_rule($rule,$oidList)
289
-    {
290
-        if ($rule==null || $rule == '') // Empty rule is always true
291
-        {
292
-            return true;
293
-        }
294
-        $matches=array();
295
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
296
-        {
297
-            $oid=$matches[1];
298
-            $found=0;
299
-            // ** replaced by .*
300
-            $oidR=preg_replace('/\*\*/', '.*', $oid);
301
-            // * replaced by [^.]*
302
-            $oidR=preg_replace('/\*/', '[0-9]+', $oidR);
288
+	public function eval_rule($rule,$oidList)
289
+	{
290
+		if ($rule==null || $rule == '') // Empty rule is always true
291
+		{
292
+			return true;
293
+		}
294
+		$matches=array();
295
+		while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
296
+		{
297
+			$oid=$matches[1];
298
+			$found=0;
299
+			// ** replaced by .*
300
+			$oidR=preg_replace('/\*\*/', '.*', $oid);
301
+			// * replaced by [^.]*
302
+			$oidR=preg_replace('/\*/', '[0-9]+', $oidR);
303 303
             
304
-            // replace * with \* in oid for preg_replace
305
-            $oid=preg_replace('/\*/', '\*', $oid);
304
+			// replace * with \* in oid for preg_replace
305
+			$oid=preg_replace('/\*/', '\*', $oid);
306 306
             
307
-            $this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
307
+			$this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
308 308
             
309
-            foreach($oidList as $val)
310
-            {
311
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
312
-                {
313
-                    if (!preg_match('/^[0-9]*\.?[0-9]+$/',$val->value))
314
-                    { // If not a number, change " to ' and put " around it
315
-                        $val->value=preg_replace('/"/',"'",$val->value);
316
-                        $val->value='"'.$val->value.'"';
317
-                    }
318
-                    $rep=0;
319
-                    $rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
320
-                    if ($rep==0)
321
-                    {
322
-                        $this->logging->log("Error in rule_eval",WARN,'');
323
-                        return false;
324
-                    }
325
-                    $found=1;
326
-                    break;
327
-                }
328
-            }
329
-            if ($found==0)
330
-            {	// OID not found : throw error
331
-                throw new Exception('OID '.$oid.' not found in trap');
332
-            }
333
-        }
334
-        $item=0;
335
-        $rule=$this->eval_cleanup($rule);
336
-        $this->logging->log('Rule after clenup: '.$rule,INFO );
309
+			foreach($oidList as $val)
310
+			{
311
+				if (preg_match("/^$oidR$/",$val->oid) == 1)
312
+				{
313
+					if (!preg_match('/^[0-9]*\.?[0-9]+$/',$val->value))
314
+					{ // If not a number, change " to ' and put " around it
315
+						$val->value=preg_replace('/"/',"'",$val->value);
316
+						$val->value='"'.$val->value.'"';
317
+					}
318
+					$rep=0;
319
+					$rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
320
+					if ($rep==0)
321
+					{
322
+						$this->logging->log("Error in rule_eval",WARN,'');
323
+						return false;
324
+					}
325
+					$found=1;
326
+					break;
327
+				}
328
+			}
329
+			if ($found==0)
330
+			{	// OID not found : throw error
331
+				throw new Exception('OID '.$oid.' not found in trap');
332
+			}
333
+		}
334
+		$item=0;
335
+		$rule=$this->eval_cleanup($rule);
336
+		$this->logging->log('Rule after clenup: '.$rule,INFO );
337 337
         
338
-        return  $this->evaluation($rule,$item);
339
-    }
338
+		return  $this->evaluation($rule,$item);
339
+	}
340 340
     
341 341
 }
342 342
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -27,47 +27,47 @@  discard block
 block discarded – undo
27 27
  * Get full number 
28 28
  * @return array<number,string>
29 29
  */
30
-    private function get_number($rule,&$item)
30
+    private function get_number($rule, &$item)
31 31
     {
32
-        $item2=$item+1;
32
+        $item2=$item + 1;
33 33
         while (
34
-            ($item2!=strlen($rule)) 
35
-            && (preg_match('/[0-9\.]/',$rule[$item2]))) 
34
+            ($item2 != strlen($rule)) 
35
+            && (preg_match('/[0-9\.]/', $rule[$item2]))) 
36 36
         { 
37
-            $item2++ ;
37
+            $item2++;
38 38
         }
39
-        $val=substr($rule,$item,$item2-$item);
39
+        $val=substr($rule, $item, $item2 - $item);
40 40
         $item=$item2;
41 41
         //echo "number ".$val."\n";
42 42
         
43
-        return array(0,$val);
43
+        return array(0, $val);
44 44
     }
45 45
 
46
-    private function get_string($rule,&$item)
46
+    private function get_string($rule, &$item)
47 47
     {
48 48
         $item++;
49
-        $item2=$this->eval_getNext($rule,$item,'"');
50
-        $val=substr($rule,$item,$item2-$item-1);
49
+        $item2=$this->eval_getNext($rule, $item, '"');
50
+        $val=substr($rule, $item, $item2 - $item - 1);
51 51
         $item=$item2;
52 52
         //echo "string : ".$val."\n";
53
-        return array(1,$val);
53
+        return array(1, $val);
54 54
         
55 55
     }
56 56
     
57
-    private function get_group($rule,&$item)
57
+    private function get_group($rule, &$item)
58 58
     {
59 59
         $item++;
60 60
         $start=$item;
61 61
         $parenthesis_count=0;
62 62
         while (($item < strlen($rule)) // Not end of string AND
63
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
63
+            && (($rule[$item] != ')') || $parenthesis_count > 0)) // Closing ')' or embeded ()
64 64
         {
65
-            if ($rule[$item] == '"' )
65
+            if ($rule[$item] == '"')
66 66
             { // pass through string
67 67
                 $item++;
68
-                $item=$this->eval_getNext($rule,$item,'"');
68
+                $item=$this->eval_getNext($rule, $item, '"');
69 69
             }
70
-            else{
70
+            else {
71 71
                 if ($rule[$item] == '(')
72 72
                 {
73 73
                     $parenthesis_count++;
@@ -80,23 +80,23 @@  discard block
 block discarded – undo
80 80
             }
81 81
         }
82 82
         
83
-        if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
84
-        $val=substr($rule,$start,$item-$start);
83
+        if ($item == strlen($rule)) {throw new Exception("no closing () in ".$rule." at ".$item); }
84
+        $val=substr($rule, $start, $item - $start);
85 85
         $item++;
86 86
         $start=0;
87 87
         //echo "group : ".$val."\n";
88 88
         // returns evaluation of group as type 2 (boolean)
89
-        return array(2,$this->evaluation($val,$start));
89
+        return array(2, $this->evaluation($val, $start));
90 90
     }
91 91
     
92
-    protected function eval_getElement($rule,&$item)
92
+    protected function eval_getElement($rule, &$item)
93 93
     {
94 94
         if ($item >= strlen($rule))
95 95
         {
96
-            throw new Exception("Early end of string ".$rule ." at " .$item );
96
+            throw new Exception("Early end of string ".$rule." at ".$item);
97 97
         }
98
-        while ($rule[$item]==' ') $item++;
99
-        if (preg_match('/[0-9\.]/',$rule[$item]))
98
+        while ($rule[$item] == ' ') $item++;
99
+        if (preg_match('/[0-9\.]/', $rule[$item]))
100 100
         { // number
101 101
             return $this->get_number($rule, $item);
102 102
         }
@@ -109,54 +109,54 @@  discard block
 block discarded – undo
109 109
         { // grouping
110 110
             return $this->get_group($rule, $item);
111 111
         }
112
-        throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
112
+        throw new Exception("number/string not found in ".$rule." at ".$item.' : '.$rule[$item]);
113 113
         
114 114
     }
115 115
     
116
-    protected function eval_getNext($rule,$item,$tok)
116
+    protected function eval_getNext($rule, $item, $tok)
117 117
     {
118 118
         while (
119
-            ($rule[$item] != $tok ) 
119
+            ($rule[$item] != $tok) 
120 120
             && ($item < strlen($rule))) 
121 121
         { 
122 122
             $item++;
123 123
         }
124
-        if ($item==strlen($rule)) {
125
-            throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
124
+        if ($item == strlen($rule)) {
125
+            throw new Exception("closing '".$tok."' not found in ".$rule." at ".$item);
126 126
         }
127
-        return $item+1;
127
+        return $item + 1;
128 128
     }
129 129
     
130
-    protected function eval_getOper($rule,&$item)
130
+    protected function eval_getOper($rule, &$item)
131 131
     {
132
-        while ($rule[$item]==' ') $item++;
132
+        while ($rule[$item] == ' ') $item++;
133 133
         switch ($rule[$item])
134 134
         {
135 135
             case '<':
136
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
137
-                $item++; return array(0,"<");
136
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, "<="); }
137
+                $item++; return array(0, "<");
138 138
             case '>':
139
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
140
-                $item++; return array(0,">");
139
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, ">="); }
140
+                $item++; return array(0, ">");
141 141
             case '=':
142
-                $item++; return array(0,"=");
142
+                $item++; return array(0, "=");
143 143
             case '!':
144
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
145
-                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
144
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, "!="); }
145
+                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule." at ".$item);
146 146
             case '~':
147
-                $item++; return array(0,"~");
147
+                $item++; return array(0, "~");
148 148
             case '|':
149
-                $item++; return array(1,"|");
149
+                $item++; return array(1, "|");
150 150
             case '&':
151
-                $item++; return array(1,"&");
151
+                $item++; return array(1, "&");
152 152
             default	:
153
-                throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
153
+                throw new Exception("Erreur in expr - operator not found in ".$rule." at ".$item);
154 154
         }
155 155
     }
156 156
     
157
-    private function check_negate_first($rule,&$item)
157
+    private function check_negate_first($rule, &$item)
158 158
     {
159
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
159
+        if ($rule[$item] == '!') // If '!' found, negate next expression.
160 160
         {
161 161
             $item++;
162 162
             return true;
@@ -167,21 +167,21 @@  discard block
 block discarded – undo
167 167
         }
168 168
     }
169 169
 
170
-    private function do_compare($val1,$val2,$comp,$negate)
170
+    private function do_compare($val1, $val2, $comp, $negate)
171 171
     {
172
-        switch ($comp){
173
-            case '<':	$retVal= ($val1 < $val2); break;
174
-            case '<=':	$retVal= ($val1 <= $val2); break;
175
-            case '>':	$retVal= ($val1 > $val2); break;
176
-            case '>=':	$retVal= ($val1 >= $val2); break;
177
-            case '=':	$retVal= ($val1 == $val2); break;
178
-            case '!=':	$retVal= ($val1 != $val2); break;
179
-            case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
180
-            case '|':	$retVal= ($val1 || $val2); break;
181
-            case '&':	$retVal= ($val1 && $val2); break;
172
+        switch ($comp) {
173
+            case '<':	$retVal=($val1 < $val2); break;
174
+            case '<=':	$retVal=($val1 <= $val2); break;
175
+            case '>':	$retVal=($val1 > $val2); break;
176
+            case '>=':	$retVal=($val1 >= $val2); break;
177
+            case '=':	$retVal=($val1 == $val2); break;
178
+            case '!=':	$retVal=($val1 != $val2); break;
179
+            case '~':	$retVal=(preg_match('/'.preg_replace('/"/', '', $val2).'/', $val1)); break;
180
+            case '|':	$retVal=($val1 || $val2); break;
181
+            case '&':	$retVal=($val1 && $val2); break;
182 182
             default:  throw new Exception("Error in expression - unknown comp : ".$comp);
183 183
         }
184
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
184
+        if ($negate === true) $retVal=!$retVal; // Inverse result if negate before expression
185 185
         
186 186
         return $retVal;
187 187
     }
@@ -194,56 +194,56 @@  discard block
 block discarded – undo
194 194
      *   comparison int vs strings will return null (error)
195 195
      *	return : bool or null on error
196 196
      */
197
-    public function evaluation($rule,&$item)
197
+    public function evaluation($rule, &$item)
198 198
     {
199 199
         //echo "Evaluation of ".substr($rule,$item)."\n";
200 200
         $negate=$this->check_negate_first($rule, $item);
201 201
         // First element : number, string or ()
202
-        list($type1,$val1) = $this->eval_getElement($rule,$item);
202
+        list($type1, $val1)=$this->eval_getElement($rule, $item);
203 203
         //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
204 204
         
205
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
205
+        if ($item == strlen($rule)) // If only element, return value, but only boolean
206 206
         {
207 207
             if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
208
-            if ($negate === true) $val1= ! $val1;
208
+            if ($negate === true) $val1=!$val1;
209 209
             return $val1;
210 210
         }
211 211
         
212 212
         // Second element : operator
213
-        list($typec,$comp) = $this->eval_getOper($rule,$item);
213
+        list($typec, $comp)=$this->eval_getOper($rule, $item);
214 214
         //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
215 215
         
216 216
         // Third element : number, string or ()
217
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
217
+        if ($rule[$item] == '!') // starts with a ! so evaluate whats next
218 218
         {
219 219
             $item++;
220 220
             if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
221
-            $val2= ! $this->evaluation($rule,$item);
221
+            $val2=!$this->evaluation($rule, $item);
222 222
             $type2=2; // result is a boolean
223 223
         }
224 224
         else
225 225
         {
226
-            list($type2,$val2) = $this->eval_getElement($rule,$item);
226
+            list($type2, $val2)=$this->eval_getElement($rule, $item);
227 227
         }
228 228
         //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
229 229
         
230
-        if ($type1!=$type2)  // cannot compare different types
230
+        if ($type1 != $type2)  // cannot compare different types
231 231
         {
232 232
             throw new Exception("Cannot compare string & number : ".$rule);
233 233
         }
234
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
234
+        if ($typec == 1 && $type1 != 2) // cannot use & or | with string/number
235 235
         {
236 236
             throw new Exception("Cannot use boolean operators with string & number : ".$rule);
237 237
         }
238 238
         
239
-        $retVal = $this->do_compare($val1, $val2, $comp, $negate);
239
+        $retVal=$this->do_compare($val1, $val2, $comp, $negate);
240 240
         
241
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
241
+        if ($item == strlen($rule)) return $retVal; // End of string : return evaluation
242 242
         // check for logical operator :
243 243
         switch ($rule[$item])
244 244
         {
245
-            case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
246
-            case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
245
+            case '|':	$item++; return ($retVal || $this->evaluation($rule, $item));
246
+            case '&':	$item++; return ($retVal && $this->evaluation($rule, $item));
247 247
             
248 248
             default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
249 249
         }
@@ -256,17 +256,17 @@  discard block
 block discarded – undo
256 256
         $rule2='';
257 257
         while ($item < strlen($rule))
258 258
         {
259
-            if ($rule[$item]==' ') { $item++; continue; }
260
-            if ($rule[$item]=='"')
259
+            if ($rule[$item] == ' ') { $item++; continue; }
260
+            if ($rule[$item] == '"')
261 261
             {
262 262
                 $rule2.=$rule[$item];
263 263
                 $item++;
264
-                while (($item < strlen($rule)) && ($rule[$item]!='"') )
264
+                while (($item < strlen($rule)) && ($rule[$item] != '"'))
265 265
                 {
266 266
                     $rule2.=$rule[$item];
267 267
                     $item++;
268 268
                 }
269
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
269
+                if ($item == strlen($rule)) throw new Exception("closing '\"' not found in ".$rule." at ".$item);
270 270
                 $rule2.=$rule[$item];
271 271
                 $item++;
272 272
                 continue;
@@ -285,14 +285,14 @@  discard block
 block discarded – undo
285 285
      *	@return bool : true : rule match, false : rule don't match , throw exception on error.
286 286
      */
287 287
     
288
-    public function eval_rule($rule,$oidList)
288
+    public function eval_rule($rule, $oidList)
289 289
     {
290
-        if ($rule==null || $rule == '') // Empty rule is always true
290
+        if ($rule == null || $rule == '') // Empty rule is always true
291 291
         {
292 292
             return true;
293 293
         }
294 294
         $matches=array();
295
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
295
+        while (preg_match('/_OID\(([0-9\.\*]+)\)/', $rule, $matches) == 1)
296 296
         {
297 297
             $oid=$matches[1];
298 298
             $found=0;
@@ -304,38 +304,38 @@  discard block
 block discarded – undo
304 304
             // replace * with \* in oid for preg_replace
305 305
             $oid=preg_replace('/\*/', '\*', $oid);
306 306
             
307
-            $this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
307
+            $this->logging->log('OID in rule : '.$oid.' / '.$oidR, DEBUG);
308 308
             
309
-            foreach($oidList as $val)
309
+            foreach ($oidList as $val)
310 310
             {
311
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
311
+                if (preg_match("/^$oidR$/", $val->oid) == 1)
312 312
                 {
313
-                    if (!preg_match('/^[0-9]*\.?[0-9]+$/',$val->value))
313
+                    if (!preg_match('/^[0-9]*\.?[0-9]+$/', $val->value))
314 314
                     { // If not a number, change " to ' and put " around it
315
-                        $val->value=preg_replace('/"/',"'",$val->value);
315
+                        $val->value=preg_replace('/"/', "'", $val->value);
316 316
                         $val->value='"'.$val->value.'"';
317 317
                     }
318 318
                     $rep=0;
319
-                    $rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
320
-                    if ($rep==0)
319
+                    $rule=preg_replace('/_OID\('.$oid.'\)/', $val->value, $rule, -1, $rep);
320
+                    if ($rep == 0)
321 321
                     {
322
-                        $this->logging->log("Error in rule_eval",WARN,'');
322
+                        $this->logging->log("Error in rule_eval", WARN, '');
323 323
                         return false;
324 324
                     }
325 325
                     $found=1;
326 326
                     break;
327 327
                 }
328 328
             }
329
-            if ($found==0)
329
+            if ($found == 0)
330 330
             {	// OID not found : throw error
331 331
                 throw new Exception('OID '.$oid.' not found in trap');
332 332
             }
333 333
         }
334 334
         $item=0;
335 335
         $rule=$this->eval_cleanup($rule);
336
-        $this->logging->log('Rule after clenup: '.$rule,INFO );
336
+        $this->logging->log('Rule after clenup: '.$rule, INFO);
337 337
         
338
-        return  $this->evaluation($rule,$item);
338
+        return  $this->evaluation($rule, $item);
339 339
     }
340 340
     
341 341
 }
342 342
\ 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
@@ -60,14 +60,15 @@  discard block
 block discarded – undo
60 60
         $start=$item;
61 61
         $parenthesis_count=0;
62 62
         while (($item < strlen($rule)) // Not end of string AND
63
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
63
+            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) {
64
+        	// Closing ')' or embeded ()
64 65
         {
65 66
             if ($rule[$item] == '"' )
66 67
             { // pass through string
67 68
                 $item++;
69
+        }
68 70
                 $item=$this->eval_getNext($rule,$item,'"');
69
-            }
70
-            else{
71
+            } else{
71 72
                 if ($rule[$item] == '(')
72 73
                 {
73 74
                     $parenthesis_count++;
@@ -95,7 +96,9 @@  discard block
 block discarded – undo
95 96
         {
96 97
             throw new Exception("Early end of string ".$rule ." at " .$item );
97 98
         }
98
-        while ($rule[$item]==' ') $item++;
99
+        while ($rule[$item]==' ') {
100
+        	$item++;
101
+        }
99 102
         if (preg_match('/[0-9\.]/',$rule[$item]))
100 103
         { // number
101 104
             return $this->get_number($rule, $item);
@@ -129,7 +132,9 @@  discard block
 block discarded – undo
129 132
     
130 133
     protected function eval_getOper($rule,&$item)
131 134
     {
132
-        while ($rule[$item]==' ') $item++;
135
+        while ($rule[$item]==' ') {
136
+        	$item++;
137
+        }
133 138
         switch ($rule[$item])
134 139
         {
135 140
             case '<':
@@ -156,12 +161,13 @@  discard block
 block discarded – undo
156 161
     
157 162
     private function check_negate_first($rule,&$item)
158 163
     {
159
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
164
+        if ( $rule[$item] == '!') {
165
+        	// If '!' found, negate next expression.
160 166
         {
161 167
             $item++;
162
-            return true;
163 168
         }
164
-        else
169
+            return true;
170
+        } else
165 171
         {
166 172
             return false;
167 173
         }
@@ -181,7 +187,10 @@  discard block
 block discarded – undo
181 187
             case '&':	$retVal= ($val1 && $val2); break;
182 188
             default:  throw new Exception("Error in expression - unknown comp : ".$comp);
183 189
         }
184
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
190
+        if ($negate === true) {
191
+        	$retVal = ! $retVal;
192
+        }
193
+        // Inverse result if negate before expression
185 194
         
186 195
         return $retVal;
187 196
     }
@@ -202,10 +211,14 @@  discard block
 block discarded – undo
202 211
         list($type1,$val1) = $this->eval_getElement($rule,$item);
203 212
         //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
204 213
         
205
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
214
+        if ($item==strlen($rule)) {
215
+        	// If only element, return value, but only boolean
206 216
         {
207 217
             if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
208
-            if ($negate === true) $val1= ! $val1;
218
+        }
219
+            if ($negate === true) {
220
+            	$val1= ! $val1;
221
+            }
209 222
             return $val1;
210 223
         }
211 224
         
@@ -214,31 +227,41 @@  discard block
 block discarded – undo
214 227
         //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
215 228
         
216 229
         // Third element : number, string or ()
217
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
230
+        if ( $rule[$item] == '!') {
231
+        	// starts with a ! so evaluate whats next
218 232
         {
219 233
             $item++;
220
-            if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
234
+        }
235
+            if ($typec != 1) {
236
+            	throw new Exception("Mixing boolean and comparison : ".$rule);
237
+            }
221 238
             $val2= ! $this->evaluation($rule,$item);
222 239
             $type2=2; // result is a boolean
223
-        }
224
-        else
240
+        } else
225 241
         {
226 242
             list($type2,$val2) = $this->eval_getElement($rule,$item);
227 243
         }
228 244
         //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
229 245
         
230
-        if ($type1!=$type2)  // cannot compare different types
246
+        if ($type1!=$type2) {
247
+        	// cannot compare different types
231 248
         {
232 249
             throw new Exception("Cannot compare string & number : ".$rule);
233 250
         }
234
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
251
+        }
252
+        if ($typec==1 && $type1 !=2) {
253
+        	// cannot use & or | with string/number
235 254
         {
236 255
             throw new Exception("Cannot use boolean operators with string & number : ".$rule);
237 256
         }
257
+        }
238 258
         
239 259
         $retVal = $this->do_compare($val1, $val2, $comp, $negate);
240 260
         
241
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
261
+        if ($item==strlen($rule)) {
262
+        	return $retVal;
263
+        }
264
+        // End of string : return evaluation
242 265
         // check for logical operator :
243 266
         switch ($rule[$item])
244 267
         {
@@ -266,7 +289,9 @@  discard block
 block discarded – undo
266 289
                     $rule2.=$rule[$item];
267 290
                     $item++;
268 291
                 }
269
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
292
+                if ($item == strlen ($rule)) {
293
+                	throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
294
+                }
270 295
                 $rule2.=$rule[$item];
271 296
                 $item++;
272 297
                 continue;
@@ -287,10 +312,12 @@  discard block
 block discarded – undo
287 312
     
288 313
     public function eval_rule($rule,$oidList)
289 314
     {
290
-        if ($rule==null || $rule == '') // Empty rule is always true
315
+        if ($rule==null || $rule == '') {
316
+        	// Empty rule is always true
291 317
         {
292 318
             return true;
293 319
         }
320
+        }
294 321
         $matches=array();
295 322
         while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
296 323
         {
Please login to merge, or discard this patch.
application/controllers/HandlerController.php 3 patches
Indentation   +235 added lines, -236 removed lines patch added patch discarded remove patch
@@ -11,13 +11,12 @@  discard block
 block discarded – undo
11 11
 
12 12
 //use Icinga\Web\Form as Form;
13 13
 /** Rules management
14
-
15
-*/
14
+ */
16 15
 class HandlerController extends TrapsController
17 16
 {
18 17
 
19 18
 	/** index : list existing rules 
20
-	*/
19
+	 */
21 20
 	public function indexAction()
22 21
 	{	
23 22
 		$this->checkReadPermission();
@@ -39,23 +38,23 @@  discard block
 block discarded – undo
39 38
 	 */
40 39
 	public function testruleAction()
41 40
 	{
42
-	    $this->checkReadPermission();
43
-	    $this->getTabs()->add('get',array(
44
-	        'active'	=> true,
45
-	        'label'		=> $this->translate('Test Rule'),
46
-	        'url'		=> Url::fromRequest()
47
-	    ));
41
+		$this->checkReadPermission();
42
+		$this->getTabs()->add('get',array(
43
+			'active'	=> true,
44
+			'label'		=> $this->translate('Test Rule'),
45
+			'url'		=> Url::fromRequest()
46
+		));
48 47
 	    
49
-	    //$db = $this->getDb();
48
+		//$db = $this->getDb();
50 49
 
51
-	    if ($this->params->get('rule') !== null) 
52
-	    {
53
-	        $this->view->rule= $this->params->get('rule');
54
-	    }
55
-	    else
56
-	    {
57
-	        $this->view->rule='';
58
-	    }
50
+		if ($this->params->get('rule') !== null) 
51
+		{
52
+			$this->view->rule= $this->params->get('rule');
53
+		}
54
+		else
55
+		{
56
+			$this->view->rule='';
57
+		}
59 58
 	}
60 59
 	
61 60
 	/**
@@ -63,31 +62,31 @@  discard block
 block discarded – undo
63 62
 	 */
64 63
 	private function add_setup_vars()
65 64
 	{
66
-	    // variables to send to view
67
-	    $this->view->hostlist=array(); // host list to input datalist
68
-	    $this->view->hostname=''; // Host name in input text
69
-	    $this->view->serviceGet=false; // Set to true to get list of service if only one host set
70
-	    $this->view->serviceSet=null; // Select service in services select (must have serviceGet=true).
71
-	    $this->view->mainoid=''; // Trap OID
72
-	    $this->view->mib=''; // Trap mib
73
-	    $this->view->name=''; // Trap name
74
-	    $this->view->trapListForMIB=array(); // Trap list if mib exists for trap
75
-	    $this->view->objectList=array(); // objects sent with trap
76
-	    $this->view->display=''; // Initial display
77
-	    $this->view->rule=''; // rule display
78
-	    $this->view->revertOK=''; // revert OK in seconds
79
-	    $this->view->hostid=-1; // normally set by javascript serviceGet()
80
-	    $this->view->ruleid=-1; // Rule id in DB for update & delete
81
-	    $this->view->setToUpdate=false; // set form as update form
82
-	    $this->view->setRuleMatch=-1; // set action on rule match (default nothing)
83
-	    $this->view->setRuleNoMatch=-1; // set action on rule no match (default nothing)
65
+		// variables to send to view
66
+		$this->view->hostlist=array(); // host list to input datalist
67
+		$this->view->hostname=''; // Host name in input text
68
+		$this->view->serviceGet=false; // Set to true to get list of service if only one host set
69
+		$this->view->serviceSet=null; // Select service in services select (must have serviceGet=true).
70
+		$this->view->mainoid=''; // Trap OID
71
+		$this->view->mib=''; // Trap mib
72
+		$this->view->name=''; // Trap name
73
+		$this->view->trapListForMIB=array(); // Trap list if mib exists for trap
74
+		$this->view->objectList=array(); // objects sent with trap
75
+		$this->view->display=''; // Initial display
76
+		$this->view->rule=''; // rule display
77
+		$this->view->revertOK=''; // revert OK in seconds
78
+		$this->view->hostid=-1; // normally set by javascript serviceGet()
79
+		$this->view->ruleid=-1; // Rule id in DB for update & delete
80
+		$this->view->setToUpdate=false; // set form as update form
81
+		$this->view->setRuleMatch=-1; // set action on rule match (default nothing)
82
+		$this->view->setRuleNoMatch=-1; // set action on rule no match (default nothing)
84 83
 	    
85
-	    $this->view->selectGroup=false; // Select by group if true
86
-	    $this->view->hostgroupid=-1; // host group id
87
-	    $this->view->serviceGroupGet=false; // Get list of service for group (set serviceSet to select one)
84
+		$this->view->selectGroup=false; // Select by group if true
85
+		$this->view->hostgroupid=-1; // host group id
86
+		$this->view->serviceGroupGet=false; // Get list of service for group (set serviceSet to select one)
88 87
 	    
89
-	    $this->view->modifier=null;
90
-	    $this->view->modified=null;
88
+		$this->view->modifier=null;
89
+		$this->view->modified=null;
91 90
 	}
92 91
 	
93 92
 	/**
@@ -96,102 +95,102 @@  discard block
 block discarded – undo
96 95
 	 */
97 96
 	private function add_from_existing($trapid)
98 97
 	{
99
-	    /********** Setup from existing trap ***************/
100
-	    // Get the full trap info
101
-	    $trapDetail=$this->getTrapDetail($trapid);
98
+		/********** Setup from existing trap ***************/
99
+		// Get the full trap info
100
+		$trapDetail=$this->getTrapDetail($trapid);
102 101
 	    
103
-	    $hostfilter=$trapDetail->source_ip;
102
+		$hostfilter=$trapDetail->source_ip;
104 103
 	    
105
-	    // Get host
106
-	    try
107
-	    {
108
-	        $hosts=$this->getHostByIP($hostfilter);
109
-	    }
110
-	    catch (Exception $e)
111
-	    {
112
-	        $this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
113
-	    }
104
+		// Get host
105
+		try
106
+		{
107
+			$hosts=$this->getHostByIP($hostfilter);
108
+		}
109
+		catch (Exception $e)
110
+		{
111
+			$this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
112
+		}
114 113
 	    
115 114
 	    
116
-	    // if one unique host found -> put id text input
117
-	    if (count($hosts)==1) {
118
-	        $this->view->hostname=$hosts[0]->name;
119
-	        //$hostid=$hosts[0]->id;
120
-	        // Tell JS to get services when page is loaded
121
-	        $this->view->serviceGet=true;
115
+		// if one unique host found -> put id text input
116
+		if (count($hosts)==1) {
117
+			$this->view->hostname=$hosts[0]->name;
118
+			//$hostid=$hosts[0]->id;
119
+			// Tell JS to get services when page is loaded
120
+			$this->view->serviceGet=true;
122 121
 	        
123
-	    }
124
-	    else
125
-	    {
126
-	        foreach($hosts as $key=>$val)
127
-	        {
128
-	            array_push($this->view->hostlist,$hosts[$key]->name);
129
-	        }
130
-	    }
122
+		}
123
+		else
124
+		{
125
+			foreach($hosts as $key=>$val)
126
+			{
127
+				array_push($this->view->hostlist,$hosts[$key]->name);
128
+			}
129
+		}
131 130
 	    
132
-	    // set up trap oid and objects received by the trap
131
+		// set up trap oid and objects received by the trap
133 132
 	    
134
-	    $this->view->mainoid=$trapDetail->trap_oid;
135
-	    if ($trapDetail->trap_name_mib != null)
136
-	    {
137
-	        $this->view->mib=$trapDetail->trap_name_mib;
138
-	        $this->view->name=$trapDetail->trap_name;
139
-	        $this->view->trapListForMIB=$this->getMIB()
140
-	        ->getTrapList($trapDetail->trap_name_mib);
141
-	    }
133
+		$this->view->mainoid=$trapDetail->trap_oid;
134
+		if ($trapDetail->trap_name_mib != null)
135
+		{
136
+			$this->view->mib=$trapDetail->trap_name_mib;
137
+			$this->view->name=$trapDetail->trap_name;
138
+			$this->view->trapListForMIB=$this->getMIB()
139
+			->getTrapList($trapDetail->trap_name_mib);
140
+		}
142 141
 	    
143
-	    // Get all objects that can be in trap from MIB
144
-	    $allObjects=$this->getMIB()->getObjectList($trapDetail->trap_oid);
145
-	    // Get all objects in current Trap
146
-	    $currentTrapObjects=$this->getTrapobjects($trapid);
147
-	    $oid_index=1;
148
-	    foreach ($currentTrapObjects as $key => $val)
149
-	    {
150
-	        $currentObjectType='Unknown';
151
-	        $currentObjectTypeEnum='Unknown';
152
-	        if (isset($allObjects[$val->oid]['type']))
153
-	        {
154
-	            $currentObjectType=$allObjects[$val->oid]['type'];
155
-	            $currentObjectTypeEnum=$allObjects[$val->oid]['type_enum'];
156
-	        }
157
-	        $currentObject=array(
158
-	            $oid_index,
159
-	            $val->oid,
160
-	            $val->oid_name_mib,
161
-	            $val->oid_name,
162
-	            $val->value,
163
-	            $currentObjectType,
164
-	            $currentObjectTypeEnum
165
-	        );
166
-	        $oid_index++;
167
-	        array_push($this->view->objectList,$currentObject);
168
-	        // set currrent object to null in allObjects
169
-	        if (isset($allObjects[$val->oid]))
170
-	        {
171
-	            $allObjects[$val->oid]=null;
172
-	        }
173
-	    }
174
-	    if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
175
-	    {
176
-	        foreach ($allObjects as $key => $val)
177
-	        {
178
-	            if ($val==null) { continue; }
179
-	            array_push($this->view->objectList, array(
180
-	                $oid_index,
181
-	                $key,
182
-	                $allObjects[$key]['mib'],
183
-	                $allObjects[$key]['name'],
184
-	                '',
185
-	                $allObjects[$key]['type'],
186
-	                $allObjects[$key]['type_enum']
187
-	            ));
188
-	            $oid_index++;
189
-	        }
190
-	    }
142
+		// Get all objects that can be in trap from MIB
143
+		$allObjects=$this->getMIB()->getObjectList($trapDetail->trap_oid);
144
+		// Get all objects in current Trap
145
+		$currentTrapObjects=$this->getTrapobjects($trapid);
146
+		$oid_index=1;
147
+		foreach ($currentTrapObjects as $key => $val)
148
+		{
149
+			$currentObjectType='Unknown';
150
+			$currentObjectTypeEnum='Unknown';
151
+			if (isset($allObjects[$val->oid]['type']))
152
+			{
153
+				$currentObjectType=$allObjects[$val->oid]['type'];
154
+				$currentObjectTypeEnum=$allObjects[$val->oid]['type_enum'];
155
+			}
156
+			$currentObject=array(
157
+				$oid_index,
158
+				$val->oid,
159
+				$val->oid_name_mib,
160
+				$val->oid_name,
161
+				$val->value,
162
+				$currentObjectType,
163
+				$currentObjectTypeEnum
164
+			);
165
+			$oid_index++;
166
+			array_push($this->view->objectList,$currentObject);
167
+			// set currrent object to null in allObjects
168
+			if (isset($allObjects[$val->oid]))
169
+			{
170
+				$allObjects[$val->oid]=null;
171
+			}
172
+		}
173
+		if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
174
+		{
175
+			foreach ($allObjects as $key => $val)
176
+			{
177
+				if ($val==null) { continue; }
178
+				array_push($this->view->objectList, array(
179
+					$oid_index,
180
+					$key,
181
+					$allObjects[$key]['mib'],
182
+					$allObjects[$key]['name'],
183
+					'',
184
+					$allObjects[$key]['type'],
185
+					$allObjects[$key]['type_enum']
186
+				));
187
+				$oid_index++;
188
+			}
189
+		}
191 190
 	    
192
-	    // Add a simple display
193
-	    $this->view->display='Trap '.$trapDetail->trap_name.' received';
194
-	    $this->view->create_basic_rule=true;
191
+		// Add a simple display
192
+		$this->view->display='Trap '.$trapDetail->trap_name.' received';
193
+		$this->view->create_basic_rule=true;
195 194
 	}
196 195
 
197 196
 	/**
@@ -200,29 +199,29 @@  discard block
 block discarded – undo
200 199
 	 */
201 200
 	private function add_check_host_exists($ruleDetail)
202 201
 	{
203
-	    // Check if hostname still exists
204
-	    $host_get=$this->getHostByName($this->view->hostname);
202
+		// Check if hostname still exists
203
+		$host_get=$this->getHostByName($this->view->hostname);
205 204
 	    
206
-	    if (count($host_get)==0)
207
-	    {
208
-	        $this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
209
-	        $this->view->serviceGet=false;
210
-	    }
211
-	    else
212
-	    {
213
-	        // Tell JS to get services when page is loaded
214
-	        $this->view->serviceGet=true;
215
-	        // get service id for form to set :
216
-	        $serviceID=$this->getServiceIDByName($this->view->hostname,$ruleDetail->service_name);
217
-	        if (count($serviceID) ==0)
218
-	        {
219
-	            $this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
220
-	        }
221
-	        else
222
-	        {
223
-	            $this->view->serviceSet=$serviceID[0]->id;
224
-	        }
225
-	    }
205
+		if (count($host_get)==0)
206
+		{
207
+			$this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
208
+			$this->view->serviceGet=false;
209
+		}
210
+		else
211
+		{
212
+			// Tell JS to get services when page is loaded
213
+			$this->view->serviceGet=true;
214
+			// get service id for form to set :
215
+			$serviceID=$this->getServiceIDByName($this->view->hostname,$ruleDetail->service_name);
216
+			if (count($serviceID) ==0)
217
+			{
218
+				$this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
219
+			}
220
+			else
221
+			{
222
+				$this->view->serviceSet=$serviceID[0]->id;
223
+			}
224
+		}
226 225
 	}
227 226
 
228 227
 	/**
@@ -231,33 +230,33 @@  discard block
 block discarded – undo
231 230
 	 */
232 231
 	private function add_check_hostgroup_exists($ruleDetail)
233 232
 	{
234
-	    // Check if groupe exists
235
-	    $group_get=$this->getHostGroupByName($this->view->hostgroupname);
236
-	    if (count($group_get)==0)
237
-	    {
238
-	        $this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
239
-	        $this->view->serviceGroupGet=false;
240
-	    }
241
-	    else
242
-	    {
243
-	        $grpServices=$this->getServicesByHostGroupid($group_get[0]->id);
244
-	        $foundGrpService=0;
245
-	        foreach ($grpServices as $grpService)
246
-	        {
247
-	            if ($grpService[0] == $ruleDetail->service_name)
248
-	            {
249
-	                $foundGrpService=1;
250
-	                $this->view->serviceSet=$ruleDetail->service_name;
251
-	            }
252
-	        }
233
+		// Check if groupe exists
234
+		$group_get=$this->getHostGroupByName($this->view->hostgroupname);
235
+		if (count($group_get)==0)
236
+		{
237
+			$this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
238
+			$this->view->serviceGroupGet=false;
239
+		}
240
+		else
241
+		{
242
+			$grpServices=$this->getServicesByHostGroupid($group_get[0]->id);
243
+			$foundGrpService=0;
244
+			foreach ($grpServices as $grpService)
245
+			{
246
+				if ($grpService[0] == $ruleDetail->service_name)
247
+				{
248
+					$foundGrpService=1;
249
+					$this->view->serviceSet=$ruleDetail->service_name;
250
+				}
251
+			}
253 252
 	        
254
-	        // Tell JS to get services when page is loaded
255
-	        $this->view->serviceGroupGet=true;
256
-	        if ($foundGrpService==0)
257
-	        {
258
-	            $this->view->warning_message.=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
259
-	        }
260
-	    }
253
+			// Tell JS to get services when page is loaded
254
+			$this->view->serviceGroupGet=true;
255
+			if ($foundGrpService==0)
256
+			{
257
+				$this->view->warning_message.=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
258
+			}
259
+		}
261 260
 	}
262 261
 	
263 262
 	/**
@@ -269,48 +268,48 @@  discard block
 block discarded – undo
269 268
 	 */
270 269
 	private function add_create_trap_object_list(&$display, &$rule)
271 270
 	{
272
-	    $curObjectList=array();
273
-	    $index=1;
274
-	    // check in display & rule for : OID(<oid>)
275
-	    $matches=array();
276
-	    while ( preg_match('/_OID\(([\.0-9]+)\)/',$display,$matches) ||
277
-	        preg_match('/_OID\(([\.0-9]+)\)/',$rule,$matches))
278
-	    {
279
-	        $curOid=$matches[1];
280
-	        if (($object=$this->getMIB()->translateOID($curOid)) != null)
281
-	        {
282
-	            array_push($curObjectList, array(
283
-	                $index,
284
-	                $curOid,
285
-	                $object['mib'],
286
-	                $object['name'],
287
-	                '',
288
-	                $object['type'],
289
-	                $object['type_enum']
290
-	            ));
291
-	        }
292
-	        else
293
-	        {
294
-	            array_push($curObjectList, array(
295
-	                $index,
296
-	                $curOid,
297
-	                'not found',
298
-	                'not found',
299
-	                '',
300
-	                'not found'
301
-	            ));
302
-	        }
303
-	        $display=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$display);
304
-	        $rule=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$rule);
305
-	        $index++;
306
-	    }
307
-	    return $curObjectList;
271
+		$curObjectList=array();
272
+		$index=1;
273
+		// check in display & rule for : OID(<oid>)
274
+		$matches=array();
275
+		while ( preg_match('/_OID\(([\.0-9]+)\)/',$display,$matches) ||
276
+			preg_match('/_OID\(([\.0-9]+)\)/',$rule,$matches))
277
+		{
278
+			$curOid=$matches[1];
279
+			if (($object=$this->getMIB()->translateOID($curOid)) != null)
280
+			{
281
+				array_push($curObjectList, array(
282
+					$index,
283
+					$curOid,
284
+					$object['mib'],
285
+					$object['name'],
286
+					'',
287
+					$object['type'],
288
+					$object['type_enum']
289
+				));
290
+			}
291
+			else
292
+			{
293
+				array_push($curObjectList, array(
294
+					$index,
295
+					$curOid,
296
+					'not found',
297
+					'not found',
298
+					'',
299
+					'not found'
300
+				));
301
+			}
302
+			$display=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$display);
303
+			$rule=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$rule);
304
+			$index++;
305
+		}
306
+		return $curObjectList;
308 307
 	}
309 308
 	
310 309
 	/** Add a handler  
311
-	*	Get params fromid : setup from existing trap (id of trap table)
312
-	*	Get param ruleid : edit from existing handler (id of rule table)
313
-	*/
310
+	 *	Get params fromid : setup from existing trap (id of trap table)
311
+	 *	Get param ruleid : edit from existing handler (id of rule table)
312
+	 */
314 313
 	public function addAction()
315 314
 	{
316 315
 		$this->checkConfigPermission();
@@ -329,8 +328,8 @@  discard block
 block discarded – undo
329 328
 		//$this->view->trapvalues=false; // Set to true to display 'value' colum in objects
330 329
 		
331 330
 		if (($trapid = $this->params->get('fromid')) !== null) {
332
-		    /********** Setup from existing trap ***************/
333
-            $this->add_from_existing($trapid);
331
+			/********** Setup from existing trap ***************/
332
+			$this->add_from_existing($trapid);
334 333
 			return;
335 334
 		}
336 335
 		
@@ -355,14 +354,14 @@  discard block
 block discarded – undo
355 354
 			$this->view->warning_message='';
356 355
 			if ($this->view->hostname != null)
357 356
 			{
358
-			    $this->view->selectGroup=false;
359
-			    // Check if hostname still exists
360
-			    $this->add_check_host_exists($ruleDetail);
357
+				$this->view->selectGroup=false;
358
+				// Check if hostname still exists
359
+				$this->add_check_host_exists($ruleDetail);
361 360
 			}
362 361
 			else
363 362
 			{
364
-			    $this->view->selectGroup=true;
365
-			    $this->add_check_hostgroup_exists($ruleDetail); //  Check if groupe exists				
363
+				$this->view->selectGroup=true;
364
+				$this->add_check_hostgroup_exists($ruleDetail); //  Check if groupe exists				
366 365
 			}
367 366
 			
368 367
 			$this->view->mainoid=$ruleDetail->trap_oid;
@@ -390,9 +389,9 @@  discard block
 block discarded – undo
390 389
 	}
391 390
 	
392 391
 	/** Validate form and output message to user  
393
-	*	@param in postdata 
394
-	* 	@return string status : OK / <Message>
395
-	**/
392
+	 *	@param in postdata 
393
+	 * 	@return string status : OK / <Message>
394
+	 **/
396 395
 	protected function handlerformAction()
397 396
 	{
398 397
 		$postData=$this->getRequest()->getPost();
@@ -433,7 +432,7 @@  discard block
 block discarded – undo
433 432
 			//$this->Module()->
434 433
 			$this->_helper->json(array(
435 434
 				'status'=>'OK',
436
-			    'redirect'=>'trapdirector/handler'
435
+				'redirect'=>'trapdirector/handler'
437 436
 			      
438 437
 			));
439 438
 		}		
@@ -517,9 +516,9 @@  discard block
 block discarded – undo
517 516
 	}
518 517
 
519 518
 	/** Get trap detail by trapid. 
520
-	*	@param integer $trapid : id of trap in received table
521
-	*	@return array (objects)
522
-	*/
519
+	 *	@param integer $trapid : id of trap in received table
520
+	 *	@return array (objects)
521
+	 */
523 522
 	protected function getTrapDetail($trapid) 
524 523
 	{
525 524
 		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
@@ -551,9 +550,9 @@  discard block
 block discarded – undo
551 550
 	}
552 551
 
553 552
 	/** Get trap objects
554
-	*	@param integer $trapid : trap id
555
-	* 	@return array : full column in db of trap id
556
-	*/
553
+	 *	@param integer $trapid : trap id
554
+	 * 	@return array : full column in db of trap id
555
+	 */
557 556
 	protected function getTrapobjects($trapid)
558 557
 	{	
559 558
 		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
@@ -584,9 +583,9 @@  discard block
 block discarded – undo
584 583
 	}
585 584
 
586 585
 	/** Get rule detail by ruleid.
587
-	*	@param integer $ruleid int id of rule in rule table
588
-	*	@return array : column objects in db
589
-	*/
586
+	 *	@param integer $ruleid int id of rule in rule table
587
+	 *	@return array : column objects in db
588
+	 */
590 589
 	protected function getRuleDetail($ruleid) 
591 590
 	{
592 591
 		if (!preg_match('/^[0-9]+$/',$ruleid)) { throw new Exception('Invalid id');  }
@@ -613,7 +612,7 @@  discard block
 block discarded – undo
613 612
 	}
614 613
 
615 614
 	/** Setup tabs for rules 
616
-	*/
615
+	 */
617 616
 	protected function prepareTabs()
618 617
 	{
619 618
 		return $this->getTabs()->add('status', array(
Please login to merge, or discard this patch.
Spacing   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -23,14 +23,14 @@  discard block
 block discarded – undo
23 23
 		$this->checkReadPermission();
24 24
 		$this->prepareTabs()->activate('status');
25 25
 
26
-		$db = $this->getDb();
26
+		$db=$this->getDb();
27 27
 		$this->getHandlerListTable()->setConnection($db);
28 28
 		$this->getHandlerListTable()->setMibloader($this->getMIB());
29 29
 		// Apply pagination limits 
30
-		$this->view->table=$this->applyPaginationLimits($this->getHandlerListTable(),$this->getModuleConfig()->itemListDisplay());		
30
+		$this->view->table=$this->applyPaginationLimits($this->getHandlerListTable(), $this->getModuleConfig()->itemListDisplay());		
31 31
 		
32 32
 		// Set Filter
33
-		$this->view->filterEditor = $this->getHandlerListTable()->getFilterEditor($this->getRequest());		
33
+		$this->view->filterEditor=$this->getHandlerListTable()->getFilterEditor($this->getRequest());		
34 34
 	
35 35
 		//$this->displayExitError('Handler/indexAction','Not implemented');
36 36
 	}
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
 	public function testruleAction()
41 41
 	{
42 42
 	    $this->checkReadPermission();
43
-	    $this->getTabs()->add('get',array(
43
+	    $this->getTabs()->add('get', array(
44 44
 	        'active'	=> true,
45 45
 	        'label'		=> $this->translate('Test Rule'),
46 46
 	        'url'		=> Url::fromRequest()
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
 
51 51
 	    if ($this->params->get('rule') !== null) 
52 52
 	    {
53
-	        $this->view->rule= $this->params->get('rule');
53
+	        $this->view->rule=$this->params->get('rule');
54 54
 	    }
55 55
 	    else
56 56
 	    {
@@ -109,12 +109,12 @@  discard block
 block discarded – undo
109 109
 	    }
110 110
 	    catch (Exception $e)
111 111
 	    {
112
-	        $this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
112
+	        $this->displayExitError('Add handler : get host by IP/Name ', $e->getMessage());
113 113
 	    }
114 114
 	    
115 115
 	    
116 116
 	    // if one unique host found -> put id text input
117
-	    if (count($hosts)==1) {
117
+	    if (count($hosts) == 1) {
118 118
 	        $this->view->hostname=$hosts[0]->name;
119 119
 	        //$hostid=$hosts[0]->id;
120 120
 	        // Tell JS to get services when page is loaded
@@ -123,9 +123,9 @@  discard block
 block discarded – undo
123 123
 	    }
124 124
 	    else
125 125
 	    {
126
-	        foreach($hosts as $key=>$val)
126
+	        foreach ($hosts as $key=>$val)
127 127
 	        {
128
-	            array_push($this->view->hostlist,$hosts[$key]->name);
128
+	            array_push($this->view->hostlist, $hosts[$key]->name);
129 129
 	        }
130 130
 	    }
131 131
 	    
@@ -164,18 +164,18 @@  discard block
 block discarded – undo
164 164
 	            $currentObjectTypeEnum
165 165
 	        );
166 166
 	        $oid_index++;
167
-	        array_push($this->view->objectList,$currentObject);
167
+	        array_push($this->view->objectList, $currentObject);
168 168
 	        // set currrent object to null in allObjects
169 169
 	        if (isset($allObjects[$val->oid]))
170 170
 	        {
171 171
 	            $allObjects[$val->oid]=null;
172 172
 	        }
173 173
 	    }
174
-	    if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
174
+	    if ($allObjects != null) // in case trap doesn't have objects or is not resolved
175 175
 	    {
176 176
 	        foreach ($allObjects as $key => $val)
177 177
 	        {
178
-	            if ($val==null) { continue; }
178
+	            if ($val == null) { continue; }
179 179
 	            array_push($this->view->objectList, array(
180 180
 	                $oid_index,
181 181
 	                $key,
@@ -203,9 +203,9 @@  discard block
 block discarded – undo
203 203
 	    // Check if hostname still exists
204 204
 	    $host_get=$this->getHostByName($this->view->hostname);
205 205
 	    
206
-	    if (count($host_get)==0)
206
+	    if (count($host_get) == 0)
207 207
 	    {
208
-	        $this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
208
+	        $this->view->warning_message='Host '.$this->view->hostname.' doesn\'t exists anymore';
209 209
 	        $this->view->serviceGet=false;
210 210
 	    }
211 211
 	    else
@@ -213,10 +213,10 @@  discard block
 block discarded – undo
213 213
 	        // Tell JS to get services when page is loaded
214 214
 	        $this->view->serviceGet=true;
215 215
 	        // get service id for form to set :
216
-	        $serviceID=$this->getServiceIDByName($this->view->hostname,$ruleDetail->service_name);
217
-	        if (count($serviceID) ==0)
216
+	        $serviceID=$this->getServiceIDByName($this->view->hostname, $ruleDetail->service_name);
217
+	        if (count($serviceID) == 0)
218 218
 	        {
219
-	            $this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
219
+	            $this->view->warning_message=' Service '.$ruleDetail->service_name.' doesn\'t exists anymore';
220 220
 	        }
221 221
 	        else
222 222
 	        {
@@ -233,9 +233,9 @@  discard block
 block discarded – undo
233 233
 	{
234 234
 	    // Check if groupe exists
235 235
 	    $group_get=$this->getHostGroupByName($this->view->hostgroupname);
236
-	    if (count($group_get)==0)
236
+	    if (count($group_get) == 0)
237 237
 	    {
238
-	        $this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
238
+	        $this->view->warning_message='HostGroup '.$this->view->hostgroupname.' doesn\'t exists anymore';
239 239
 	        $this->view->serviceGroupGet=false;
240 240
 	    }
241 241
 	    else
@@ -253,9 +253,9 @@  discard block
 block discarded – undo
253 253
 	        
254 254
 	        // Tell JS to get services when page is loaded
255 255
 	        $this->view->serviceGroupGet=true;
256
-	        if ($foundGrpService==0)
256
+	        if ($foundGrpService == 0)
257 257
 	        {
258
-	            $this->view->warning_message.=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
258
+	            $this->view->warning_message.=' Service '.$ruleDetail->service_name.' doesn\'t exists anymore';
259 259
 	        }
260 260
 	    }
261 261
 	}
@@ -273,8 +273,8 @@  discard block
 block discarded – undo
273 273
 	    $index=1;
274 274
 	    // check in display & rule for : OID(<oid>)
275 275
 	    $matches=array();
276
-	    while ( preg_match('/_OID\(([\.0-9]+)\)/',$display,$matches) ||
277
-	        preg_match('/_OID\(([\.0-9]+)\)/',$rule,$matches))
276
+	    while (preg_match('/_OID\(([\.0-9]+)\)/', $display, $matches) ||
277
+	        preg_match('/_OID\(([\.0-9]+)\)/', $rule, $matches))
278 278
 	    {
279 279
 	        $curOid=$matches[1];
280 280
 	        if (($object=$this->getMIB()->translateOID($curOid)) != null)
@@ -300,8 +300,8 @@  discard block
 block discarded – undo
300 300
 	                'not found'
301 301
 	            ));
302 302
 	        }
303
-	        $display=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$display);
304
-	        $rule=preg_replace('/_OID\('.$curOid.'\)/','\$'.$index.'\$',$rule);
303
+	        $display=preg_replace('/_OID\('.$curOid.'\)/', '\$'.$index.'\$', $display);
304
+	        $rule=preg_replace('/_OID\('.$curOid.'\)/', '\$'.$index.'\$', $rule);
305 305
 	        $index++;
306 306
 	    }
307 307
 	    return $curObjectList;
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
 	{
316 316
 		$this->checkConfigPermission();
317 317
 		// set up tab
318
-		$this->getTabs()->add('get',array(
318
+		$this->getTabs()->add('get', array(
319 319
 			'active'	=> true,
320 320
 			'label'		=> $this->translate('Add handler'),
321 321
 			'url'		=> Url::fromRequest()
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
 		
329 329
 		//$this->view->trapvalues=false; // Set to true to display 'value' colum in objects
330 330
 		
331
-		if (($trapid = $this->params->get('fromid')) !== null) {
331
+		if (($trapid=$this->params->get('fromid')) !== null) {
332 332
 		    /********** Setup from existing trap ***************/
333 333
             $this->add_from_existing($trapid);
334 334
 			return;
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
 			$this->view->setRuleMatch=$ruleDetail->action_match;
349 349
 			$this->view->setRuleNoMatch=$ruleDetail->action_nomatch;
350 350
 			$this->view->hostgroupname=$ruleDetail->host_group_name;
351
-			$this->view->modified=gmdate("Y-m-d\TH:i:s\Z",$ruleDetail->modified);
351
+			$this->view->modified=gmdate("Y-m-d\TH:i:s\Z", $ruleDetail->modified);
352 352
 			$this->view->modifier=$ruleDetail->modifier;
353 353
 			
354 354
 			// Warning message if host/service don't exists anymore
@@ -400,26 +400,26 @@  discard block
 block discarded – undo
400 400
 	
401 401
 		$params=array(
402 402
 			// id (also db) => 	array('post' => post id, 'val' => default val, 'db' => send to table)
403
-			'hostgroup'		=>	array('post' => 'hostgroup','db'=>false),
404
-			'db_rule'		=>	array('post' => 'db_rule','db'=>false),
405
-			'hostid'		=>	array('post' => 'hostid','db'=>false),
406
-			'host_name'		=>	array('post' => 'hostname','val' => null,'db'=>true),
407
-			'host_group_name'=>	array('post' => null,'val' => null,'db'=>true),
408
-			'serviceid'		=>	array('post' => 'serviceid','db'=>false),
409
-			'service_name'	=>	array('post' => 'serviceName','db'=>true),
410
-			'trap_oid'		=>	array('post' => 'oid','db'=>true),
411
-			'revert_ok'		=>	array('post' => 'revertOK','val' => 0,'db'=>true),
412
-			'display'		=>	array('post' => 'display','val' => '','db'=>true),
413
-			'rule'			=>	array('post' => 'rule','val' => '','db'=>true),			
414
-			'action_match'	=>	array('post' => 'ruleMatch','val' => -1,'db'=>true),
415
-			'action_nomatch'=>	array('post' => 'ruleNoMatch','val' => -1,'db'=>true),					
416
-			'ip4'			=>	array('post' => null,'val' => null,'db'=>true),
417
-			'ip6'			=>	array('post' => null,'val' => null,'db'=>true),
418
-			'action_form'	=>	array('post' => 'action_form','db'=>false)
403
+			'hostgroup'		=>	array('post' => 'hostgroup', 'db'=>false),
404
+			'db_rule'		=>	array('post' => 'db_rule', 'db'=>false),
405
+			'hostid'		=>	array('post' => 'hostid', 'db'=>false),
406
+			'host_name'		=>	array('post' => 'hostname', 'val' => null, 'db'=>true),
407
+			'host_group_name'=>	array('post' => null, 'val' => null, 'db'=>true),
408
+			'serviceid'		=>	array('post' => 'serviceid', 'db'=>false),
409
+			'service_name'	=>	array('post' => 'serviceName', 'db'=>true),
410
+			'trap_oid'		=>	array('post' => 'oid', 'db'=>true),
411
+			'revert_ok'		=>	array('post' => 'revertOK', 'val' => 0, 'db'=>true),
412
+			'display'		=>	array('post' => 'display', 'val' => '', 'db'=>true),
413
+			'rule'			=>	array('post' => 'rule', 'val' => '', 'db'=>true),			
414
+			'action_match'	=>	array('post' => 'ruleMatch', 'val' => -1, 'db'=>true),
415
+			'action_nomatch'=>	array('post' => 'ruleNoMatch', 'val' => -1, 'db'=>true),					
416
+			'ip4'			=>	array('post' => null, 'val' => null, 'db'=>true),
417
+			'ip6'			=>	array('post' => null, 'val' => null, 'db'=>true),
418
+			'action_form'	=>	array('post' => 'action_form', 'db'=>false)
419 419
 		);
420 420
 		
421 421
 		if (isset($postData[$params['action_form']['post']]) 
422
-			&& $postData[$params['action_form']['post']] == 'delete' )
422
+			&& $postData[$params['action_form']['post']] == 'delete')
423 423
 		{
424 424
 			try
425 425
 			{
@@ -439,16 +439,16 @@  discard block
 block discarded – undo
439 439
 		}		
440 440
 		foreach (array_keys($params) as $key)
441 441
 		{
442
-			if ($params[$key]['post']==null) continue; // data not sent in post vars
443
-			if (! isset($postData[$params[$key]['post']]))
442
+			if ($params[$key]['post'] == null) continue; // data not sent in post vars
443
+			if (!isset($postData[$params[$key]['post']]))
444 444
 			{
445 445
 				// should not happen as the js checks data
446
-				$this->_helper->json(array('status'=>'No ' . $key));
446
+				$this->_helper->json(array('status'=>'No '.$key));
447 447
 			}
448 448
 			else
449 449
 			{
450 450
 				$data=$postData[$params[$key]['post']];
451
-				if ($data!=null && $data !="")
451
+				if ($data != null && $data != "")
452 452
 				{
453 453
 					$params[$key]['val']=$postData[$params[$key]['post']];
454 454
 				}
@@ -457,8 +457,8 @@  discard block
 block discarded – undo
457 457
 
458 458
 		try 
459 459
 		{
460
-			$isHostGroup=($params['hostgroup']['val'] == 1)?true:false;
461
-			if (! $isHostGroup ) 
460
+			$isHostGroup=($params['hostgroup']['val'] == 1) ?true:false;
461
+			if (!$isHostGroup) 
462 462
 			{  // checks if selection by host 
463 463
 				$hostAddr=$this->getHostInfoByID($params['hostid']['val']);
464 464
 				$params['ip4']['val']=$hostAddr->ip4;
@@ -485,25 +485,25 @@  discard block
 block discarded – undo
485 485
 					return;					
486 486
 				}
487 487
 				// Put param in correct column (group_name)
488
-				$params['host_group_name']['val'] = $params['host_name']['val'];
488
+				$params['host_group_name']['val']=$params['host_name']['val'];
489 489
 				$params['host_name']['val']=null;
490 490
 			}
491 491
 			$dbparams=array();
492 492
 			foreach ($params as $key=>$val)
493 493
 			{
494
-				if ($val['db']==true )
494
+				if ($val['db'] == true)
495 495
 				{
496
-					$dbparams[$key] = $val['val'];
496
+					$dbparams[$key]=$val['val'];
497 497
 				}
498 498
 			}
499 499
 			// echo '<br>';	print_r($dbparams);echo '<br>';
500
-			if ($params['db_rule']['val'] == -1 ) 
500
+			if ($params['db_rule']['val'] == -1) 
501 501
 			{
502 502
 				$ruleID=$this->addHandlerRule($dbparams);
503 503
 			}
504 504
 			else
505 505
 			{
506
-				$this->updateHandlerRule($dbparams,$params['db_rule']['val']);
506
+				$this->updateHandlerRule($dbparams, $params['db_rule']['val']);
507 507
 				$ruleID=$params['db_rule']['val'];
508 508
 			}
509 509
 		}
@@ -522,10 +522,10 @@  discard block
 block discarded – undo
522 522
 	*/
523 523
 	protected function getTrapDetail($trapid) 
524 524
 	{
525
-		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
525
+		if (!preg_match('/^[0-9]+$/', $trapid)) { throw new Exception('Invalid id'); }
526 526
 		$queryArray=$this->getModuleConfig()->trapDetailQuery();
527 527
 		
528
-		$db = $this->getDb()->getConnection();
528
+		$db=$this->getDb()->getConnection();
529 529
 		// ***************  Get main data
530 530
 		// extract columns and titles;
531 531
 		$elmts=NULL;
@@ -534,15 +534,15 @@  discard block
 block discarded – undo
534 534
 		}
535 535
 		try
536 536
 		{		
537
-			$query = $db->select()
538
-				->from($this->getModuleConfig()->getTrapTableName(),$elmts)
539
-				->where('id=?',$trapid);
537
+			$query=$db->select()
538
+				->from($this->getModuleConfig()->getTrapTableName(), $elmts)
539
+				->where('id=?', $trapid);
540 540
 			$trapDetail=$db->fetchRow($query);
541
-			if ( $trapDetail == null ) throw new Exception('No traps was found with id = '.$trapid);
541
+			if ($trapDetail == null) throw new Exception('No traps was found with id = '.$trapid);
542 542
 		}
543 543
 		catch (Exception $e)
544 544
 		{
545
-			$this->displayExitError('Add handler : get trap detail returning : '.print_r($trapDetail,true),$e->getMessage());
545
+			$this->displayExitError('Add handler : get trap detail returning : '.print_r($trapDetail, true), $e->getMessage());
546 546
 			return;
547 547
 		}
548 548
 
@@ -556,10 +556,10 @@  discard block
 block discarded – undo
556 556
 	*/
557 557
 	protected function getTrapobjects($trapid)
558 558
 	{	
559
-		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
559
+		if (!preg_match('/^[0-9]+$/', $trapid)) { throw new Exception('Invalid id'); }
560 560
 		$queryArrayData=$this->getModuleConfig()->trapDataDetailQuery();
561 561
 		
562
-		$db = $this->getDb()->getConnection();
562
+		$db=$this->getDb()->getConnection();
563 563
 		// ***************  Get object data
564 564
 		// extract columns and titles;
565 565
 		$data_elmts=NULL;
@@ -568,15 +568,15 @@  discard block
 block discarded – undo
568 568
 		}
569 569
 		try
570 570
 		{		
571
-			$query = $db->select()
572
-				->from($this->moduleConfig->getTrapDataTableName(),$data_elmts)
573
-				->where('trap_id=?',$trapid);
571
+			$query=$db->select()
572
+				->from($this->moduleConfig->getTrapDataTableName(), $data_elmts)
573
+				->where('trap_id=?', $trapid);
574 574
 			$trapDetail=$db->fetchAll($query);
575 575
 			// if ( $trapDetail == null ) throw new Exception('No traps was found with id = '.$trapid);
576 576
 		}
577 577
 		catch (Exception $e)
578 578
 		{
579
-			$this->displayExitError('Add handler : get trap data detail : ',$e->getMessage());
579
+			$this->displayExitError('Add handler : get trap data detail : ', $e->getMessage());
580 580
 			return array();
581 581
 		}
582 582
 
@@ -589,22 +589,22 @@  discard block
 block discarded – undo
589 589
 	*/
590 590
 	protected function getRuleDetail($ruleid) 
591 591
 	{
592
-		if (!preg_match('/^[0-9]+$/',$ruleid)) { throw new Exception('Invalid id');  }
592
+		if (!preg_match('/^[0-9]+$/', $ruleid)) { throw new Exception('Invalid id'); }
593 593
 		$queryArray=$this->getModuleConfig()->ruleDetailQuery();
594 594
 		
595
-		$db = $this->getDb()->getConnection();
595
+		$db=$this->getDb()->getConnection();
596 596
 		// ***************  Get main data
597 597
 		try
598 598
 		{		
599
-			$query = $db->select()
600
-				->from($this->getModuleConfig()->getTrapRuleName(),$queryArray)
601
-				->where('id=?',$ruleid);
599
+			$query=$db->select()
600
+				->from($this->getModuleConfig()->getTrapRuleName(), $queryArray)
601
+				->where('id=?', $ruleid);
602 602
 			$ruleDetail=$db->fetchRow($query);
603
-			if ( $ruleDetail == null ) throw new Exception('No rule was found with id = '.$ruleid);
603
+			if ($ruleDetail == null) throw new Exception('No rule was found with id = '.$ruleid);
604 604
 		}
605 605
 		catch (Exception $e)
606 606
 		{
607
-			$this->displayExitError('Update handler : get rule detail',$e->getMessage());
607
+			$this->displayExitError('Update handler : get rule detail', $e->getMessage());
608 608
 			return array();
609 609
 		}
610 610
 
@@ -618,7 +618,7 @@  discard block
 block discarded – undo
618 618
 	{
619 619
 		return $this->getTabs()->add('status', array(
620 620
 			'label' => $this->translate('Traps'),
621
-			'url'   => $this->getModuleConfig()->urlPath() . '/handler')
621
+			'url'   => $this->getModuleConfig()->urlPath().'/handler')
622 622
 		);
623 623
 	} 
624 624
 	
Please login to merge, or discard this patch.
Braces   +35 added lines, -39 removed lines patch added patch discarded remove patch
@@ -51,8 +51,7 @@  discard block
 block discarded – undo
51 51
 	    if ($this->params->get('rule') !== null) 
52 52
 	    {
53 53
 	        $this->view->rule= $this->params->get('rule');
54
-	    }
55
-	    else
54
+	    } else
56 55
 	    {
57 56
 	        $this->view->rule='';
58 57
 	    }
@@ -106,8 +105,7 @@  discard block
 block discarded – undo
106 105
 	    try
107 106
 	    {
108 107
 	        $hosts=$this->getHostByIP($hostfilter);
109
-	    }
110
-	    catch (Exception $e)
108
+	    } catch (Exception $e)
111 109
 	    {
112 110
 	        $this->displayExitError('Add handler : get host by IP/Name ',$e->getMessage());
113 111
 	    }
@@ -120,8 +118,7 @@  discard block
 block discarded – undo
120 118
 	        // Tell JS to get services when page is loaded
121 119
 	        $this->view->serviceGet=true;
122 120
 	        
123
-	    }
124
-	    else
121
+	    } else
125 122
 	    {
126 123
 	        foreach($hosts as $key=>$val)
127 124
 	        {
@@ -171,11 +168,14 @@  discard block
 block discarded – undo
171 168
 	            $allObjects[$val->oid]=null;
172 169
 	        }
173 170
 	    }
174
-	    if ($allObjects!=null) // in case trap doesn't have objects or is not resolved
171
+	    if ($allObjects!=null) {
172
+	    	// in case trap doesn't have objects or is not resolved
175 173
 	    {
176 174
 	        foreach ($allObjects as $key => $val)
177 175
 	        {
178
-	            if ($val==null) { continue; }
176
+	            if ($val==null) { continue;
177
+	    }
178
+	    }
179 179
 	            array_push($this->view->objectList, array(
180 180
 	                $oid_index,
181 181
 	                $key,
@@ -207,8 +207,7 @@  discard block
 block discarded – undo
207 207
 	    {
208 208
 	        $this->view->warning_message='Host '.$this->view->hostname. ' doesn\'t exists anymore';
209 209
 	        $this->view->serviceGet=false;
210
-	    }
211
-	    else
210
+	    } else
212 211
 	    {
213 212
 	        // Tell JS to get services when page is loaded
214 213
 	        $this->view->serviceGet=true;
@@ -217,8 +216,7 @@  discard block
 block discarded – undo
217 216
 	        if (count($serviceID) ==0)
218 217
 	        {
219 218
 	            $this->view->warning_message=' Service '.$ruleDetail->service_name. ' doesn\'t exists anymore';
220
-	        }
221
-	        else
219
+	        } else
222 220
 	        {
223 221
 	            $this->view->serviceSet=$serviceID[0]->id;
224 222
 	        }
@@ -237,8 +235,7 @@  discard block
 block discarded – undo
237 235
 	    {
238 236
 	        $this->view->warning_message='HostGroup '.$this->view->hostgroupname. ' doesn\'t exists anymore';
239 237
 	        $this->view->serviceGroupGet=false;
240
-	    }
241
-	    else
238
+	    } else
242 239
 	    {
243 240
 	        $grpServices=$this->getServicesByHostGroupid($group_get[0]->id);
244 241
 	        $foundGrpService=0;
@@ -288,8 +285,7 @@  discard block
 block discarded – undo
288 285
 	                $object['type'],
289 286
 	                $object['type_enum']
290 287
 	            ));
291
-	        }
292
-	        else
288
+	        } else
293 289
 	        {
294 290
 	            array_push($curObjectList, array(
295 291
 	                $index,
@@ -358,8 +354,7 @@  discard block
 block discarded – undo
358 354
 			    $this->view->selectGroup=false;
359 355
 			    // Check if hostname still exists
360 356
 			    $this->add_check_host_exists($ruleDetail);
361
-			}
362
-			else
357
+			} else
363 358
 			{
364 359
 			    $this->view->selectGroup=true;
365 360
 			    $this->add_check_hostgroup_exists($ruleDetail); //  Check if groupe exists				
@@ -367,9 +362,11 @@  discard block
 block discarded – undo
367 362
 			
368 363
 			$this->view->mainoid=$ruleDetail->trap_oid;
369 364
 			$oidName=$this->getMIB()->translateOID($ruleDetail->trap_oid);
370
-			if ($oidName != null)  // oid is found in mibs
365
+			if ($oidName != null) {
366
+				// oid is found in mibs
371 367
 			{
372
-				$this->view->mib=$oidName['mib']; 
368
+				$this->view->mib=$oidName['mib'];
369
+			}
373 370
 				$this->view->name=$oidName['name'];
374 371
 				$this->view->trapListForMIB=$this->getMIB()
375 372
 					->getTrapList($oidName['mib']);				
@@ -424,8 +421,7 @@  discard block
 block discarded – undo
424 421
 			try
425 422
 			{
426 423
 				$this->deleteRule($postData[$params['db_rule']['post']]);
427
-			}
428
-			catch (Exception $e)
424
+			} catch (Exception $e)
429 425
 			{
430 426
 				$this->_helper->json(array('status'=>$e->getMessage()));
431 427
 				return;
@@ -439,13 +435,15 @@  discard block
 block discarded – undo
439 435
 		}		
440 436
 		foreach (array_keys($params) as $key)
441 437
 		{
442
-			if ($params[$key]['post']==null) continue; // data not sent in post vars
438
+			if ($params[$key]['post']==null) {
439
+				continue;
440
+			}
441
+			// data not sent in post vars
443 442
 			if (! isset($postData[$params[$key]['post']]))
444 443
 			{
445 444
 				// should not happen as the js checks data
446 445
 				$this->_helper->json(array('status'=>'No ' . $key));
447
-			}
448
-			else
446
+			} else
449 447
 			{
450 448
 				$data=$postData[$params[$key]['post']];
451 449
 				if ($data!=null && $data !="")
@@ -475,8 +473,7 @@  discard block
 block discarded – undo
475 473
 					$this->_helper->json(array('status'=>"Invalid service id : Please re enter service"));
476 474
 					return;
477 475
 				}
478
-			}
479
-			else
476
+			} else
480 477
 			{
481 478
 				$object=$this->getObjectNameByid($params['hostid']['val']);
482 479
 				if ($params['host_name']['val'] != $object->name1)
@@ -500,14 +497,12 @@  discard block
 block discarded – undo
500 497
 			if ($params['db_rule']['val'] == -1 ) 
501 498
 			{
502 499
 				$ruleID=$this->addHandlerRule($dbparams);
503
-			}
504
-			else
500
+			} else
505 501
 			{
506 502
 				$this->updateHandlerRule($dbparams,$params['db_rule']['val']);
507 503
 				$ruleID=$params['db_rule']['val'];
508 504
 			}
509
-		}
510
-		catch (Exception $e)
505
+		} catch (Exception $e)
511 506
 		{
512 507
 			$this->_helper->json(array('status'=>$e->getMessage()));
513 508
 			return;
@@ -538,9 +533,10 @@  discard block
 block discarded – undo
538 533
 				->from($this->getModuleConfig()->getTrapTableName(),$elmts)
539 534
 				->where('id=?',$trapid);
540 535
 			$trapDetail=$db->fetchRow($query);
541
-			if ( $trapDetail == null ) throw new Exception('No traps was found with id = '.$trapid);
542
-		}
543
-		catch (Exception $e)
536
+			if ( $trapDetail == null ) {
537
+				throw new Exception('No traps was found with id = '.$trapid);
538
+			}
539
+		} catch (Exception $e)
544 540
 		{
545 541
 			$this->displayExitError('Add handler : get trap detail returning : '.print_r($trapDetail,true),$e->getMessage());
546 542
 			return;
@@ -573,8 +569,7 @@  discard block
 block discarded – undo
573 569
 				->where('trap_id=?',$trapid);
574 570
 			$trapDetail=$db->fetchAll($query);
575 571
 			// if ( $trapDetail == null ) throw new Exception('No traps was found with id = '.$trapid);
576
-		}
577
-		catch (Exception $e)
572
+		} catch (Exception $e)
578 573
 		{
579 574
 			$this->displayExitError('Add handler : get trap data detail : ',$e->getMessage());
580 575
 			return array();
@@ -600,9 +595,10 @@  discard block
 block discarded – undo
600 595
 				->from($this->getModuleConfig()->getTrapRuleName(),$queryArray)
601 596
 				->where('id=?',$ruleid);
602 597
 			$ruleDetail=$db->fetchRow($query);
603
-			if ( $ruleDetail == null ) throw new Exception('No rule was found with id = '.$ruleid);
604
-		}
605
-		catch (Exception $e)
598
+			if ( $ruleDetail == null ) {
599
+				throw new Exception('No rule was found with id = '.$ruleid);
600
+			}
601
+		} catch (Exception $e)
606 602
 		{
607 603
 			$this->displayExitError('Update handler : get rule detail',$e->getMessage());
608 604
 			return array();
Please login to merge, or discard this patch.
application/controllers/StatusController.php 3 patches
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -65,10 +65,10 @@  discard block
 block discarded – undo
65 65
 	} 
66 66
   
67 67
 	/** Mib management
68
-	*	Post param : action=update_mib_db : update mib database
69
-	*	Post param : ation=check_update : check if mib update is finished
70
-	*	File post : mibfile -> save mib file
71
-	*/
68
+	 *	Post param : action=update_mib_db : update mib database
69
+	 *	Post param : ation=check_update : check if mib update is finished
70
+	 *	File post : mibfile -> save mib file
71
+	 */
72 72
 	public function mibAction()
73 73
 	{
74 74
 		$this->prepareTabs()->activate('mib');
@@ -87,22 +87,22 @@  discard block
 block discarded – undo
87 87
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
88 88
 					if (preg_match('/OK/',$return))
89 89
 					{
90
-					    $this->_helper->json(array('status'=>'OK'));
90
+						$this->_helper->json(array('status'=>'OK'));
91 91
 					}
92 92
 					// Error
93 93
 					$this->_helper->json(array('status'=>$return));
94 94
 				}
95 95
 				if ($action == 'check_update')
96 96
 				{
97
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
98
-				    if ($file == false)
99
-				    {   // process is dead
100
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
101
-				        return;
102
-				    }
103
-				    $pid=fgets($file);
104
-				    $output=array();
105
-				    $retVal=0;
97
+					$file=@fopen('/tmp/trapdirector_update.pid','r');
98
+					if ($file == false)
99
+					{   // process is dead
100
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
101
+						return;
102
+					}
103
+					$pid=fgets($file);
104
+					$output=array();
105
+					$retVal=0;
106 106
 					exec('ps '.$pid,$output,$retVal);
107 107
 					if ($retVal == 0)
108 108
 					{ // process is alive
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 					}
111 111
 					else
112 112
 					{ // process is dead
113
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
113
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
114 114
 					}
115 115
 				}
116 116
 				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
@@ -123,26 +123,26 @@  discard block
 block discarded – undo
123 123
 				$destDir=array_shift($DirConf);
124 124
 				if (!is_dir($destDir))
125 125
 				{
126
-				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
126
+					$this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
127 127
 				}
128 128
 				else
129 129
 				{
130
-				    if (!is_writable($destDir))
131
-				    {
132
-				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
133
-				    }
134
-				    else
135
-				    {
136
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
137
-    				    if (move_uploaded_file($_FILES['mibfile']['tmp_name'],$destination)===false)
138
-    				    {
139
-    				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
140
-    				    }
141
-    				    else
142
-    				    {
143
-    				        $this->view->uploadStatus="File $name uploaded in $destDir";
144
-    				    }
145
-				    }
130
+					if (!is_writable($destDir))
131
+					{
132
+						$this->view->uploadStatus="ERROR : $destDir directory is not writable";
133
+					}
134
+					else
135
+					{
136
+						$destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
137
+						if (move_uploaded_file($_FILES['mibfile']['tmp_name'],$destination)===false)
138
+						{
139
+							$this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
140
+						}
141
+						else
142
+						{
143
+							$this->view->uploadStatus="File $name uploaded in $destDir";
144
+						}
145
+					}
146 146
 				}
147 147
 
148 148
 			}
@@ -275,20 +275,20 @@  discard block
 block discarded – undo
275 275
 // TODO : see if useless 
276 276
 class UploadForm extends Form
277 277
 { 
278
-    public function __construct($options = null) 
279
-    {
280
-        parent::__construct($options);
281
-        $this->addElements2();
282
-    }
278
+	public function __construct($options = null) 
279
+	{
280
+		parent::__construct($options);
281
+		$this->addElements2();
282
+	}
283 283
 
284
-    public function addElements2()
285
-    {
286
-        // File Input
287
-        $file = new File('mib-file');
288
-        $file->setLabel('Mib upload');
289
-             //->setAttrib('multiple', null);
290
-        $this->addElement($file);
284
+	public function addElements2()
285
+	{
286
+		// File Input
287
+		$file = new File('mib-file');
288
+		$file->setLabel('Mib upload');
289
+			 //->setAttrib('multiple', null);
290
+		$this->addElement($file);
291 291
 		$button = new Submit("upload",array('ignore'=>false));
292 292
 		$this->addElement($button);//->setIgnore(false);
293
-    }
293
+	}
294 294
 }
Please login to merge, or discard this patch.
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -22,18 +22,18 @@  discard block
 block discarded – undo
22 22
 		/************  Trapdb ***********/
23 23
 		try
24 24
 		{
25
-			$db = $this->getDb()->getConnection();
26
-			$query = $db->select()->from(
25
+			$db=$this->getDb()->getConnection();
26
+			$query=$db->select()->from(
27 27
 				$this->getModuleConfig()->getTrapTableName(),
28 28
 				array('COUNT(*)')
29 29
 			);			
30 30
 			$this->view->trap_count=$db->fetchOne($query);
31
-			$query = $db->select()->from(
31
+			$query=$db->select()->from(
32 32
 				$this->getModuleConfig()->getTrapDataTableName(),
33 33
 				array('COUNT(*)')
34 34
 			);			
35 35
 			$this->view->trap_object_count=$db->fetchOne($query);
36
-			$query = $db->select()->from(
36
+			$query=$db->select()->from(
37 37
 				$this->getModuleConfig()->getTrapRuleName(),
38 38
 				array('COUNT(*)')
39 39
 			);			
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 		}
45 45
 		catch (Exception $e)
46 46
 		{
47
-			$this->displayExitError('status',$e->getMessage());
47
+			$this->displayExitError('status', $e->getMessage());
48 48
 		}
49 49
 		
50 50
 		/*************** Log destination *******************/
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
 		}
60 60
 		catch (Exception $e)
61 61
 		{
62
-			$this->displayExitError('status',$e->getMessage());
62
+			$this->displayExitError('status', $e->getMessage());
63 63
 		}		
64 64
 		
65 65
 	} 
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 				if ($action == 'update_mib_db')
86 86
 				{ // Do the update in background
87 87
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
88
-					if (preg_match('/OK/',$return))
88
+					if (preg_match('/OK/', $return))
89 89
 					{
90 90
 					    $this->_helper->json(array('status'=>'OK'));
91 91
 					}
@@ -94,32 +94,32 @@  discard block
 block discarded – undo
94 94
 				}
95 95
 				if ($action == 'check_update')
96 96
 				{
97
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
97
+				    $file=@fopen('/tmp/trapdirector_update.pid', 'r');
98 98
 				    if ($file == false)
99 99
 				    {   // process is dead
100
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
100
+				        $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'Cannot open file'));
101 101
 				        return;
102 102
 				    }
103 103
 				    $pid=fgets($file);
104 104
 				    $output=array();
105 105
 				    $retVal=0;
106
-					exec('ps '.$pid,$output,$retVal);
106
+					exec('ps '.$pid, $output, $retVal);
107 107
 					if ($retVal == 0)
108 108
 					{ // process is alive
109 109
 						$this->_helper->json(array('status'=>'Alive and kicking'));
110 110
 					}
111 111
 					else
112 112
 					{ // process is dead
113
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
113
+					    $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'no proc'.$pid));
114 114
 					}
115 115
 				}
116
-				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
116
+				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible'));
117 117
 			}
118 118
 			/** Check for mib file UPLOAD */
119 119
 			if (isset($_FILES['mibfile']))
120 120
 			{
121 121
 				$name=$_FILES['mibfile']['name'];
122
-				$DirConf=explode(':',$this->Config()->get('config', 'snmptranslate_dirs'));
122
+				$DirConf=explode(':', $this->Config()->get('config', 'snmptranslate_dirs'));
123 123
 				$destDir=array_shift($DirConf);
124 124
 				if (!is_dir($destDir))
125 125
 				{
@@ -133,8 +133,8 @@  discard block
 block discarded – undo
133 133
 				    }
134 134
 				    else
135 135
 				    {
136
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
137
-    				    if (move_uploaded_file($_FILES['mibfile']['tmp_name'],$destination)===false)
136
+				        $destination=$destDir.'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
137
+    				    if (move_uploaded_file($_FILES['mibfile']['tmp_name'], $destination) === false)
138 138
     				    {
139 139
     				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
140 140
     				    }
@@ -150,13 +150,13 @@  discard block
 block discarded – undo
150 150
 		}
151 151
 		
152 152
 		// snmptranslate tests
153
-		$snmptranslate = $this->Config()->get('config', 'snmptranslate');
153
+		$snmptranslate=$this->Config()->get('config', 'snmptranslate');
154 154
 		$this->view->snmptranslate_bin=$snmptranslate;
155 155
 		$this->view->snmptranslate_state='warn';
156
-		if (is_executable ( $snmptranslate ))
156
+		if (is_executable($snmptranslate))
157 157
 		{
158
-			$translate=exec($snmptranslate . ' 1');
159
-			if (preg_match('/iso/',$translate))
158
+			$translate=exec($snmptranslate.' 1');
159
+			if (preg_match('/iso/', $translate))
160 160
 			{
161 161
 				$this->view->snmptranslate='works fine';
162 162
 				$this->view->snmptranslate_state='ok';
@@ -174,46 +174,46 @@  discard block
 block discarded – undo
174 174
 		// mib database
175 175
 		
176 176
 		$this->view->mibDbCount=$this->getMIB()->countObjects();
177
-		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null,21);
177
+		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null, 21);
178 178
 		
179 179
 		// mib dirs
180 180
 		$DirConf=$this->Config()->get('config', 'snmptranslate_dirs');
181
-		$dirArray=explode(':',$DirConf);
181
+		$dirArray=explode(':', $DirConf);
182 182
 
183 183
 		// Get base directories from net-snmp-config
184 184
 		$output=$matches=array();
185 185
 		$retVal=0;
186
-		$sysDirs=exec('net-snmp-config --default-mibdirs',$output,$retVal);
187
-		if ($retVal==0)
186
+		$sysDirs=exec('net-snmp-config --default-mibdirs', $output, $retVal);
187
+		if ($retVal == 0)
188 188
 		{
189
-			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
189
+			$dirArray=array_merge($dirArray, explode(':', $sysDirs));
190 190
 		}
191 191
 		else
192 192
 		{
193
-			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
194
-			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
193
+			$translateOut=exec($this->Config()->get('config', 'snmptranslate').' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
194
+			if (preg_match('/MIBDIRS.*\'([^\']+)\'/', $translateOut, $matches))
195 195
 			{
196
-				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
196
+				$dirArray=array_merge($dirArray, explode(':', $matches[1]));
197 197
 			}
198 198
 			else
199 199
 			{
200
-				array_push($dirArray,'Install net-snmp-config to see system directories');
200
+				array_push($dirArray, 'Install net-snmp-config to see system directories');
201 201
 			}
202 202
 		}
203 203
 		
204 204
 		$this->view->dirArray=$dirArray;
205 205
 		
206 206
 		$output=null;
207
-		foreach (explode(':',$DirConf) as $mibdir)
207
+		foreach (explode(':', $DirConf) as $mibdir)
208 208
 		{
209
-			exec('ls '.$mibdir.' | grep -v traplist.txt',$output);
209
+			exec('ls '.$mibdir.' | grep -v traplist.txt', $output);
210 210
 		}
211 211
 		//$i=0;$listFiles='';while (isset($output[$i])) $listFiles.=$output[$i++];
212 212
 		//$this->view->fileList=explode(' ',$listFiles);
213 213
 		$this->view->fileList=$output;
214 214
 		
215 215
 		// Zend form 
216
-		$this->view->form= new UploadForm();
216
+		$this->view->form=new UploadForm();
217 217
 		//$this->view->form= new Form('upload-form');
218 218
 		
219 219
 		
@@ -237,18 +237,18 @@  discard block
 block discarded – undo
237 237
 		$this->view->templateForm_output='';
238 238
 		if (isset($postData['template_name']) && isset($postData['template_revert_time']))
239 239
 		{
240
-			$template_create = 'icingacli director service create --json \'{ "check_command": "dummy", ';
241
-			$template_create .= '"check_interval": "' .$postData['template_revert_time']. '", "check_timeout": "20", "disabled": false, "enable_active_checks": true, "enable_event_handler": true, "enable_notifications": true, "enable_passive_checks": true, "enable_perfdata": true, "max_check_attempts": "1", ';
242
-			$template_create .= '"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
240
+			$template_create='icingacli director service create --json \'{ "check_command": "dummy", ';
241
+			$template_create.='"check_interval": "'.$postData['template_revert_time'].'", "check_timeout": "20", "disabled": false, "enable_active_checks": true, "enable_event_handler": true, "enable_notifications": true, "enable_passive_checks": true, "enable_perfdata": true, "max_check_attempts": "1", ';
242
+			$template_create.='"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
243 243
 			$output=array();
244 244
 			$ret_code=0;
245
-			exec($template_create,$output,$ret_code);
245
+			exec($template_create, $output, $ret_code);
246 246
 			if ($ret_code != 0)
247 247
 			{
248
-				$this->displayExitError("Status -> Services","Error creating template : ".$output[0].'<br>Command was : '.$template_create);
248
+				$this->displayExitError("Status -> Services", "Error creating template : ".$output[0].'<br>Command was : '.$template_create);
249 249
 			}
250
-			exec('icingacli director config deploy',$output,$ret_code);
251
-			$this->view->templateForm_output='Template '.$postData['template_name']. ' created';
250
+			exec('icingacli director config deploy', $output, $ret_code);
251
+			$this->view->templateForm_output='Template '.$postData['template_name'].' created';
252 252
 		}
253 253
 		
254 254
 		// template creation form
@@ -261,13 +261,13 @@  discard block
 block discarded – undo
261 261
 	{
262 262
 		return $this->getTabs()->add('status', array(
263 263
 			'label' => $this->translate('Status'),
264
-			'url'   => $this->getModuleConfig()->urlPath() . '/status')
264
+			'url'   => $this->getModuleConfig()->urlPath().'/status')
265 265
 		)->add('mib', array(
266 266
 			'label' => $this->translate('MIB Management'),
267
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
267
+			'url'   => $this->getModuleConfig()->urlPath().'/status/mib')
268 268
 		)->add('services', array(
269 269
 			'label' => $this->translate('Services management'),
270
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
270
+			'url'   => $this->getModuleConfig()->urlPath().'/status/services')
271 271
 		);
272 272
 	} 
273 273
 }
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 // TODO : see if useless 
276 276
 class UploadForm extends Form
277 277
 { 
278
-    public function __construct($options = null) 
278
+    public function __construct($options=null) 
279 279
     {
280 280
         parent::__construct($options);
281 281
         $this->addElements2();
@@ -284,11 +284,11 @@  discard block
 block discarded – undo
284 284
     public function addElements2()
285 285
     {
286 286
         // File Input
287
-        $file = new File('mib-file');
287
+        $file=new File('mib-file');
288 288
         $file->setLabel('Mib upload');
289 289
              //->setAttrib('multiple', null);
290 290
         $this->addElement($file);
291
-		$button = new Submit("upload",array('ignore'=>false));
292
-		$this->addElement($button);//->setIgnore(false);
291
+		$button=new Submit("upload", array('ignore'=>false));
292
+		$this->addElement($button); //->setIgnore(false);
293 293
     }
294 294
 }
Please login to merge, or discard this patch.
Braces   +10 added lines, -20 removed lines patch added patch discarded remove patch
@@ -41,8 +41,7 @@  discard block
 block discarded – undo
41 41
  			
42 42
 			$this->view->trap_days_delete=$this->getDBConfigValue('db_remove_days');
43 43
 			
44
-		}
45
-		catch (Exception $e)
44
+		} catch (Exception $e)
46 45
 		{
47 46
 			$this->displayExitError('status',$e->getMessage());
48 47
 		}
@@ -56,8 +55,7 @@  discard block
 block discarded – undo
56 55
 			$this->view->currentLogFile=$this->getDBConfigValue('log_file');
57 56
 			$this->view->logLevels=$this->getModuleConfig()->getlogLevels();
58 57
 			$this->view->currentLogLevel=$this->getDBConfigValue('log_level');
59
-		}
60
-		catch (Exception $e)
58
+		} catch (Exception $e)
61 59
 		{
62 60
 			$this->displayExitError('status',$e->getMessage());
63 61
 		}		
@@ -107,8 +105,7 @@  discard block
 block discarded – undo
107 105
 					if ($retVal == 0)
108 106
 					{ // process is alive
109 107
 						$this->_helper->json(array('status'=>'Alive and kicking'));
110
-					}
111
-					else
108
+					} else
112 109
 					{ // process is dead
113 110
 					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
114 111
 					}
@@ -124,21 +121,18 @@  discard block
 block discarded – undo
124 121
 				if (!is_dir($destDir))
125 122
 				{
126 123
 				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
127
-				}
128
-				else
124
+				} else
129 125
 				{
130 126
 				    if (!is_writable($destDir))
131 127
 				    {
132 128
 				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
133
-				    }
134
-				    else
129
+				    } else
135 130
 				    {
136 131
 				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
137 132
     				    if (move_uploaded_file($_FILES['mibfile']['tmp_name'],$destination)===false)
138 133
     				    {
139 134
     				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
140
-    				    }
141
-    				    else
135
+    				    } else
142 136
     				    {
143 137
     				        $this->view->uploadStatus="File $name uploaded in $destDir";
144 138
     				    }
@@ -160,13 +154,11 @@  discard block
 block discarded – undo
160 154
 			{
161 155
 				$this->view->snmptranslate='works fine';
162 156
 				$this->view->snmptranslate_state='ok';
163
-			}
164
-			else
157
+			} else
165 158
 			{
166 159
 				$this->view->snmptranslate='can execute but no resolution';
167 160
 			}
168
-		}
169
-		else
161
+		} else
170 162
 		{
171 163
 			$this->view->snmptranslate='cannot execute';
172 164
 		}
@@ -187,15 +179,13 @@  discard block
 block discarded – undo
187 179
 		if ($retVal==0)
188 180
 		{
189 181
 			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
190
-		}
191
-		else
182
+		} else
192 183
 		{
193 184
 			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
194 185
 			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
195 186
 			{
196 187
 				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
197
-			}
198
-			else
188
+			} else
199 189
 			{
200 190
 				array_push($dirArray,'Install net-snmp-config to see system directories');
201 191
 			}
Please login to merge, or discard this patch.