Passed
Push — master ( 55e9ea...2fad3a )
by Patrick
02:06
created
application/controllers/StatusController.php 3 patches
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.
Indentation   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -64,10 +64,10 @@  discard block
 block discarded – undo
64 64
 	} 
65 65
   
66 66
 	/** Mib management
67
-	*	Post param : action=update_mib_db : update mib database
68
-	*	Post param : ation=check_update : check if mib update is finished
69
-	*	File post : mibfile -> save mib file
70
-	*/
67
+	 *	Post param : action=update_mib_db : update mib database
68
+	 *	Post param : ation=check_update : check if mib update is finished
69
+	 *	File post : mibfile -> save mib file
70
+	 */
71 71
 	public function mibAction()
72 72
 	{
73 73
 		$this->prepareTabs()->activate('mib');
@@ -86,22 +86,22 @@  discard block
 block discarded – undo
86 86
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
87 87
 					if (preg_match('/OK/',$return))
88 88
 					{
89
-					    $this->_helper->json(array('status'=>'OK'));
89
+						$this->_helper->json(array('status'=>'OK'));
90 90
 					}
91 91
 					// Error
92 92
 					$this->_helper->json(array('status'=>$return));
93 93
 				}
94 94
 				if ($action == 'check_update')
95 95
 				{
96
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
97
-				    if ($file == false)
98
-				    {   // process is dead
99
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
100
-				        return;
101
-				    }
102
-				    $pid=fgets($file);
103
-				    $output=array();
104
-				    $retVal=0;
96
+					$file=@fopen('/tmp/trapdirector_update.pid','r');
97
+					if ($file == false)
98
+					{   // process is dead
99
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
100
+						return;
101
+					}
102
+					$pid=fgets($file);
103
+					$output=array();
104
+					$retVal=0;
105 105
 					exec('ps '.$pid,$output,$retVal);
106 106
 					if ($retVal == 0)
107 107
 					{ // process is alive
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 					}
110 110
 					else
111 111
 					{ // process is dead
112
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
112
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
113 113
 					}
114 114
 				}
115 115
 				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
@@ -122,26 +122,26 @@  discard block
 block discarded – undo
122 122
 				$destDir=array_shift($DirConf);
123 123
 				if (!is_dir($destDir))
124 124
 				{
125
-				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
125
+					$this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
126 126
 				}
127 127
 				else
128 128
 				{
129
-				    if (!is_writable($destDir))
130
-				    {
131
-				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
132
-				    }
133
-				    else
134
-				    {
135
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
136
-    				    if (move_uploaded_file($_FILES['mibfile']['tmp_name'],$destination)===false)
137
-    				    {
138
-    				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
139
-    				    }
140
-    				    else
141
-    				    {
142
-    				        $this->view->uploadStatus="File $name uploaded in $destDir";
143
-    				    }
144
-				    }
129
+					if (!is_writable($destDir))
130
+					{
131
+						$this->view->uploadStatus="ERROR : $destDir directory is not writable";
132
+					}
133
+					else
134
+					{
135
+						$destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
136
+						if (move_uploaded_file($_FILES['mibfile']['tmp_name'],$destination)===false)
137
+						{
138
+							$this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
139
+						}
140
+						else
141
+						{
142
+							$this->view->uploadStatus="File $name uploaded in $destDir";
143
+						}
144
+					}
145 145
 				}
146 146
 
147 147
 			}
@@ -261,47 +261,47 @@  discard block
 block discarded – undo
261 261
 	 */
262 262
 	public function pluginsAction()
263 263
 	{
264
-	    $this->prepareTabs()->activate('plugins');
264
+		$this->prepareTabs()->activate('plugins');
265 265
 	    
266
-	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
267
-	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
268
-	    $Trap = new Trap($icingaweb2_etc,4);
266
+		require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
267
+		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
268
+		$Trap = new Trap($icingaweb2_etc,4);
269 269
 	    
270
-	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
270
+		$this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
271 271
 	    
272
-	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
272
+		$enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
273 273
 
274
-	    $pluginList = $Trap->pluginClass->pluginList();
274
+		$pluginList = $Trap->pluginClass->pluginList();
275 275
 	    
276
-	    // Plugin list and fill function name list
277
-	    $functionList=array();
278
-	    $this->view->pluginArray=array();
279
-	    foreach ($pluginList as $plugin)
280
-	    {
281
-	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
282
-	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
283
-	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
284
-	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
285
-	        $pluginDetails->description = htmlentities($pluginDetails->description);
286
-	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
287
-	        array_push($this->view->pluginArray, $pluginDetails);
288
-	        // Get functions for function details
289
-	        foreach ($pluginDetails->funcArray as $function)
290
-	        {
291
-	            array_push($functionList,$function);
292
-	        }
293
-	    }
276
+		// Plugin list and fill function name list
277
+		$functionList=array();
278
+		$this->view->pluginArray=array();
279
+		foreach ($pluginList as $plugin)
280
+		{
281
+			$pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
282
+			$pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
283
+			$pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
284
+			$pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
285
+			$pluginDetails->description = htmlentities($pluginDetails->description);
286
+			$pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
287
+			array_push($this->view->pluginArray, $pluginDetails);
288
+			// Get functions for function details
289
+			foreach ($pluginDetails->funcArray as $function)
290
+			{
291
+				array_push($functionList,$function);
292
+			}
293
+		}
294 294
 	    
295
-	    // Function list with details
296
-	    $this->view->functionList=array();
297
-	    foreach ($functionList as $function)
298
-	    {
299
-	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
300
-	        $functionDetail->params = htmlentities($functionDetail->params);
301
-	        $functionDetail->description = htmlentities($functionDetail->description);
302
-	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
303
-	        array_push($this->view->functionList, $functionDetail);
304
-	    }
295
+		// Function list with details
296
+		$this->view->functionList=array();
297
+		foreach ($functionList as $function)
298
+		{
299
+			$functionDetail = $Trap->pluginClass->getFunctionDetails($function);
300
+			$functionDetail->params = htmlentities($functionDetail->params);
301
+			$functionDetail->description = htmlentities($functionDetail->description);
302
+			$functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
303
+			array_push($this->view->functionList, $functionDetail);
304
+		}
305 305
 
306 306
 	}
307 307
 	
@@ -316,30 +316,30 @@  discard block
 block discarded – undo
316 316
 		)->add('services', array(
317 317
 			'label' => $this->translate('Services management'),
318 318
 			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
319
-	    )->add('plugins', array(
320
-	        'label' => $this->translate('Plugins management'),
321
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
322
-	    );
319
+		)->add('plugins', array(
320
+			'label' => $this->translate('Plugins management'),
321
+			'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
322
+		);
323 323
 	} 
324 324
 }
325 325
 
326 326
 // TODO : see if useless 
327 327
 class UploadForm extends Form
328 328
 { 
329
-    public function __construct($options = null) 
330
-    {
331
-        parent::__construct($options);
332
-        $this->addElements2();
333
-    }
329
+	public function __construct($options = null) 
330
+	{
331
+		parent::__construct($options);
332
+		$this->addElements2();
333
+	}
334 334
 
335
-    public function addElements2()
336
-    {
337
-        // File Input
338
-        $file = new File('mib-file');
339
-        $file->setLabel('Mib upload');
340
-             //->setAttrib('multiple', null);
341
-        $this->addElement($file);
335
+	public function addElements2()
336
+	{
337
+		// File Input
338
+		$file = new File('mib-file');
339
+		$file->setLabel('Mib upload');
340
+			 //->setAttrib('multiple', null);
341
+		$this->addElement($file);
342 342
 		$button = new Submit("upload",array('ignore'=>false));
343 343
 		$this->addElement($button);//->setIgnore(false);
344
-    }
344
+	}
345 345
 }
Please login to merge, or discard this patch.
Spacing   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -21,18 +21,18 @@  discard block
 block discarded – undo
21 21
 		/************  Trapdb ***********/
22 22
 		try
23 23
 		{
24
-			$db = $this->getDb()->getConnection();
25
-			$query = $db->select()->from(
24
+			$db=$this->getDb()->getConnection();
25
+			$query=$db->select()->from(
26 26
 				$this->getModuleConfig()->getTrapTableName(),
27 27
 				array('COUNT(*)')
28 28
 			);			
29 29
 			$this->view->trap_count=$db->fetchOne($query);
30
-			$query = $db->select()->from(
30
+			$query=$db->select()->from(
31 31
 				$this->getModuleConfig()->getTrapDataTableName(),
32 32
 				array('COUNT(*)')
33 33
 			);			
34 34
 			$this->view->trap_object_count=$db->fetchOne($query);
35
-			$query = $db->select()->from(
35
+			$query=$db->select()->from(
36 36
 				$this->getModuleConfig()->getTrapRuleName(),
37 37
 				array('COUNT(*)')
38 38
 			);			
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
 		}
44 44
 		catch (Exception $e)
45 45
 		{
46
-			$this->displayExitError('status',$e->getMessage());
46
+			$this->displayExitError('status', $e->getMessage());
47 47
 		}
48 48
 		
49 49
 		/*************** Log destination *******************/
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 		}
59 59
 		catch (Exception $e)
60 60
 		{
61
-			$this->displayExitError('status',$e->getMessage());
61
+			$this->displayExitError('status', $e->getMessage());
62 62
 		}		
63 63
 		
64 64
 	} 
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 				if ($action == 'update_mib_db')
85 85
 				{ // Do the update in background
86 86
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
87
-					if (preg_match('/OK/',$return))
87
+					if (preg_match('/OK/', $return))
88 88
 					{
89 89
 					    $this->_helper->json(array('status'=>'OK'));
90 90
 					}
@@ -93,32 +93,32 @@  discard block
 block discarded – undo
93 93
 				}
94 94
 				if ($action == 'check_update')
95 95
 				{
96
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
96
+				    $file=@fopen('/tmp/trapdirector_update.pid', 'r');
97 97
 				    if ($file == false)
98 98
 				    {   // process is dead
99
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
99
+				        $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'Cannot open file'));
100 100
 				        return;
101 101
 				    }
102 102
 				    $pid=fgets($file);
103 103
 				    $output=array();
104 104
 				    $retVal=0;
105
-					exec('ps '.$pid,$output,$retVal);
105
+					exec('ps '.$pid, $output, $retVal);
106 106
 					if ($retVal == 0)
107 107
 					{ // process is alive
108 108
 						$this->_helper->json(array('status'=>'Alive and kicking'));
109 109
 					}
110 110
 					else
111 111
 					{ // process is dead
112
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
112
+					    $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'no proc'.$pid));
113 113
 					}
114 114
 				}
115
-				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
115
+				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible'));
116 116
 			}
117 117
 			/** Check for mib file UPLOAD */
118 118
 			if (isset($_FILES['mibfile']))
119 119
 			{
120 120
 				$name=$_FILES['mibfile']['name'];
121
-				$DirConf=explode(':',$this->Config()->get('config', 'snmptranslate_dirs'));
121
+				$DirConf=explode(':', $this->Config()->get('config', 'snmptranslate_dirs'));
122 122
 				$destDir=array_shift($DirConf);
123 123
 				if (!is_dir($destDir))
124 124
 				{
@@ -132,8 +132,8 @@  discard block
 block discarded – undo
132 132
 				    }
133 133
 				    else
134 134
 				    {
135
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
136
-    				    if (move_uploaded_file($_FILES['mibfile']['tmp_name'],$destination)===false)
135
+				        $destination=$destDir.'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
136
+    				    if (move_uploaded_file($_FILES['mibfile']['tmp_name'], $destination) === false)
137 137
     				    {
138 138
     				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
139 139
     				    }
@@ -149,13 +149,13 @@  discard block
 block discarded – undo
149 149
 		}
150 150
 		
151 151
 		// snmptranslate tests
152
-		$snmptranslate = $this->Config()->get('config', 'snmptranslate');
152
+		$snmptranslate=$this->Config()->get('config', 'snmptranslate');
153 153
 		$this->view->snmptranslate_bin=$snmptranslate;
154 154
 		$this->view->snmptranslate_state='warn';
155
-		if (is_executable ( $snmptranslate ))
155
+		if (is_executable($snmptranslate))
156 156
 		{
157
-			$translate=exec($snmptranslate . ' 1');
158
-			if (preg_match('/iso/',$translate))
157
+			$translate=exec($snmptranslate.' 1');
158
+			if (preg_match('/iso/', $translate))
159 159
 			{
160 160
 				$this->view->snmptranslate='works fine';
161 161
 				$this->view->snmptranslate_state='ok';
@@ -173,46 +173,46 @@  discard block
 block discarded – undo
173 173
 		// mib database
174 174
 		
175 175
 		$this->view->mibDbCount=$this->getMIB()->countObjects();
176
-		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null,21);
176
+		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null, 21);
177 177
 		
178 178
 		// mib dirs
179 179
 		$DirConf=$this->Config()->get('config', 'snmptranslate_dirs');
180
-		$dirArray=explode(':',$DirConf);
180
+		$dirArray=explode(':', $DirConf);
181 181
 
182 182
 		// Get base directories from net-snmp-config
183 183
 		$output=$matches=array();
184 184
 		$retVal=0;
185
-		$sysDirs=exec('net-snmp-config --default-mibdirs',$output,$retVal);
186
-		if ($retVal==0)
185
+		$sysDirs=exec('net-snmp-config --default-mibdirs', $output, $retVal);
186
+		if ($retVal == 0)
187 187
 		{
188
-			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
188
+			$dirArray=array_merge($dirArray, explode(':', $sysDirs));
189 189
 		}
190 190
 		else
191 191
 		{
192
-			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
193
-			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
192
+			$translateOut=exec($this->Config()->get('config', 'snmptranslate').' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
193
+			if (preg_match('/MIBDIRS.*\'([^\']+)\'/', $translateOut, $matches))
194 194
 			{
195
-				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
195
+				$dirArray=array_merge($dirArray, explode(':', $matches[1]));
196 196
 			}
197 197
 			else
198 198
 			{
199
-				array_push($dirArray,'Install net-snmp-config to see system directories');
199
+				array_push($dirArray, 'Install net-snmp-config to see system directories');
200 200
 			}
201 201
 		}
202 202
 		
203 203
 		$this->view->dirArray=$dirArray;
204 204
 		
205 205
 		$output=null;
206
-		foreach (explode(':',$DirConf) as $mibdir)
206
+		foreach (explode(':', $DirConf) as $mibdir)
207 207
 		{
208
-			exec('ls '.$mibdir.' | grep -v traplist.txt',$output);
208
+			exec('ls '.$mibdir.' | grep -v traplist.txt', $output);
209 209
 		}
210 210
 		//$i=0;$listFiles='';while (isset($output[$i])) $listFiles.=$output[$i++];
211 211
 		//$this->view->fileList=explode(' ',$listFiles);
212 212
 		$this->view->fileList=$output;
213 213
 		
214 214
 		// Zend form 
215
-		$this->view->form= new UploadForm();
215
+		$this->view->form=new UploadForm();
216 216
 		//$this->view->form= new Form('upload-form');
217 217
 		
218 218
 		
@@ -236,18 +236,18 @@  discard block
 block discarded – undo
236 236
 		$this->view->templateForm_output='';
237 237
 		if (isset($postData['template_name']) && isset($postData['template_revert_time']))
238 238
 		{
239
-			$template_create = 'icingacli director service create --json \'{ "check_command": "dummy", ';
240
-			$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", ';
241
-			$template_create .= '"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
239
+			$template_create='icingacli director service create --json \'{ "check_command": "dummy", ';
240
+			$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", ';
241
+			$template_create.='"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
242 242
 			$output=array();
243 243
 			$ret_code=0;
244
-			exec($template_create,$output,$ret_code);
244
+			exec($template_create, $output, $ret_code);
245 245
 			if ($ret_code != 0)
246 246
 			{
247
-				$this->displayExitError("Status -> Services","Error creating template : ".$output[0].'<br>Command was : '.$template_create);
247
+				$this->displayExitError("Status -> Services", "Error creating template : ".$output[0].'<br>Command was : '.$template_create);
248 248
 			}
249
-			exec('icingacli director config deploy',$output,$ret_code);
250
-			$this->view->templateForm_output='Template '.$postData['template_name']. ' created';
249
+			exec('icingacli director config deploy', $output, $ret_code);
250
+			$this->view->templateForm_output='Template '.$postData['template_name'].' created';
251 251
 		}
252 252
 		
253 253
 		// template creation form
@@ -263,15 +263,15 @@  discard block
 block discarded – undo
263 263
 	{
264 264
 	    $this->prepareTabs()->activate('plugins');
265 265
 	    
266
-	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
266
+	    require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
267 267
 	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
268
-	    $Trap = new Trap($icingaweb2_etc,4);
268
+	    $Trap=new Trap($icingaweb2_etc, 4);
269 269
 	    
270
-	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
270
+	    $this->view->pluginLoaded=htmlentities($Trap->pluginClass->registerAllPlugins(false));
271 271
 	    
272
-	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
272
+	    $enabledPlugins=$Trap->pluginClass->getEnabledPlugins();
273 273
 
274
-	    $pluginList = $Trap->pluginClass->pluginList();
274
+	    $pluginList=$Trap->pluginClass->pluginList();
275 275
 	    
276 276
 	    // Plugin list and fill function name list
277 277
 	    $functionList=array();
@@ -279,16 +279,16 @@  discard block
 block discarded – undo
279 279
 	    foreach ($pluginList as $plugin)
280 280
 	    {
281 281
 	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
282
-	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
283
-	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
284
-	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
285
-	        $pluginDetails->description = htmlentities($pluginDetails->description);
286
-	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
282
+	        $pluginDetails->enabled=(in_array($plugin, $enabledPlugins)) ? true : false;
283
+	        $pluginDetails->catchAllTraps=($pluginDetails->catchAllTraps === true) ? 'Yes' : 'No';
284
+	        $pluginDetails->processTraps=($pluginDetails->processTraps === true) ? 'Yes' : 'No';
285
+	        $pluginDetails->description=htmlentities($pluginDetails->description);
286
+	        $pluginDetails->description=preg_replace('/\n/', '<br>', $pluginDetails->description);
287 287
 	        array_push($this->view->pluginArray, $pluginDetails);
288 288
 	        // Get functions for function details
289 289
 	        foreach ($pluginDetails->funcArray as $function)
290 290
 	        {
291
-	            array_push($functionList,$function);
291
+	            array_push($functionList, $function);
292 292
 	        }
293 293
 	    }
294 294
 	    
@@ -296,10 +296,10 @@  discard block
 block discarded – undo
296 296
 	    $this->view->functionList=array();
297 297
 	    foreach ($functionList as $function)
298 298
 	    {
299
-	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
300
-	        $functionDetail->params = htmlentities($functionDetail->params);
301
-	        $functionDetail->description = htmlentities($functionDetail->description);
302
-	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
299
+	        $functionDetail=$Trap->pluginClass->getFunctionDetails($function);
300
+	        $functionDetail->params=htmlentities($functionDetail->params);
301
+	        $functionDetail->description=htmlentities($functionDetail->description);
302
+	        $functionDetail->description=preg_replace('/\n/', '<br>', $functionDetail->description);
303 303
 	        array_push($this->view->functionList, $functionDetail);
304 304
 	    }
305 305
 
@@ -309,16 +309,16 @@  discard block
 block discarded – undo
309 309
 	{
310 310
 		return $this->getTabs()->add('status', array(
311 311
 			'label' => $this->translate('Status'),
312
-			'url'   => $this->getModuleConfig()->urlPath() . '/status')
312
+			'url'   => $this->getModuleConfig()->urlPath().'/status')
313 313
 		)->add('mib', array(
314 314
 			'label' => $this->translate('MIB Management'),
315
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
315
+			'url'   => $this->getModuleConfig()->urlPath().'/status/mib')
316 316
 		)->add('services', array(
317 317
 			'label' => $this->translate('Services management'),
318
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
318
+			'url'   => $this->getModuleConfig()->urlPath().'/status/services')
319 319
 	    )->add('plugins', array(
320 320
 	        'label' => $this->translate('Plugins management'),
321
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
321
+	        'url'   => $this->getModuleConfig()->urlPath().'/status/plugins')
322 322
 	    );
323 323
 	} 
324 324
 }
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 // TODO : see if useless 
327 327
 class UploadForm extends Form
328 328
 { 
329
-    public function __construct($options = null) 
329
+    public function __construct($options=null) 
330 330
     {
331 331
         parent::__construct($options);
332 332
         $this->addElements2();
@@ -335,11 +335,11 @@  discard block
 block discarded – undo
335 335
     public function addElements2()
336 336
     {
337 337
         // File Input
338
-        $file = new File('mib-file');
338
+        $file=new File('mib-file');
339 339
         $file->setLabel('Mib upload');
340 340
              //->setAttrib('multiple', null);
341 341
         $this->addElement($file);
342
-		$button = new Submit("upload",array('ignore'=>false));
343
-		$this->addElement($button);//->setIgnore(false);
342
+		$button=new Submit("upload", array('ignore'=>false));
343
+		$this->addElement($button); //->setIgnore(false);
344 344
     }
345 345
 }
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
@@ -7,331 +7,331 @@
 block discarded – undo
7 7
 class Rule
8 8
 {
9 9
     
10
-    protected $logging; //< logging class
10
+	protected $logging; //< logging class
11 11
     
12
-    /**
13
-     * Setup Rule Class
14
-     * @param Logging $logClass : where to log
15
-     */
16
-    function __construct($logClass)
17
-    {
18
-        $this->logging=$logClass;
12
+	/**
13
+	 * Setup Rule Class
14
+	 * @param Logging $logClass : where to log
15
+	 */
16
+	function __construct($logClass)
17
+	{
18
+		$this->logging=$logClass;
19 19
 
20
-    }
20
+	}
21 21
 
22 22
 /**
23 23
  * Get full number 
24 24
  * @return array<number,string>
25 25
  */
26
-    private function get_number($rule,&$item)
27
-    {
28
-        $item2=$item+1;
29
-        while (
30
-            ($item2!=strlen($rule)) 
31
-            && (preg_match('/[\-0-9\.]/',$rule[$item2]))) 
32
-        { 
33
-            $item2++ ;
34
-        }
35
-        $val=substr($rule,$item,$item2-$item);
36
-        $item=$item2;
37
-        //echo "number ".$val."\n";
26
+	private function get_number($rule,&$item)
27
+	{
28
+		$item2=$item+1;
29
+		while (
30
+			($item2!=strlen($rule)) 
31
+			&& (preg_match('/[\-0-9\.]/',$rule[$item2]))) 
32
+		{ 
33
+			$item2++ ;
34
+		}
35
+		$val=substr($rule,$item,$item2-$item);
36
+		$item=$item2;
37
+		//echo "number ".$val."\n";
38 38
         
39
-        return array(0,$val);
40
-    }
39
+		return array(0,$val);
40
+	}
41 41
 
42
-    private function get_string($rule,&$item)
43
-    {
44
-        $item++;
45
-        $item2=$this->eval_getNext($rule,$item,'"');
46
-        $val=substr($rule,$item,$item2-$item-1);
47
-        $item=$item2;
48
-        //echo "string : ".$val."\n";
49
-        return array(1,$val);
42
+	private function get_string($rule,&$item)
43
+	{
44
+		$item++;
45
+		$item2=$this->eval_getNext($rule,$item,'"');
46
+		$val=substr($rule,$item,$item2-$item-1);
47
+		$item=$item2;
48
+		//echo "string : ".$val."\n";
49
+		return array(1,$val);
50 50
         
51
-    }
51
+	}
52 52
     
53
-    private function get_group($rule,&$item)
54
-    {
55
-        $item++;
56
-        $start=$item;
57
-        $parenthesis_count=0;
58
-        while (($item < strlen($rule)) // Not end of string AND
59
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
60
-        {
61
-            if ($rule[$item] == '"' )
62
-            { // pass through string
63
-                $item++;
64
-                $item=$this->eval_getNext($rule,$item,'"');
65
-            }
66
-            else{
67
-                if ($rule[$item] == '(')
68
-                {
69
-                    $parenthesis_count++;
70
-                }
71
-                if ($rule[$item] == ')')
72
-                {
73
-                    $parenthesis_count--;
74
-                }
75
-                $item++;
76
-            }
77
-        }
53
+	private function get_group($rule,&$item)
54
+	{
55
+		$item++;
56
+		$start=$item;
57
+		$parenthesis_count=0;
58
+		while (($item < strlen($rule)) // Not end of string AND
59
+			&& ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
60
+		{
61
+			if ($rule[$item] == '"' )
62
+			{ // pass through string
63
+				$item++;
64
+				$item=$this->eval_getNext($rule,$item,'"');
65
+			}
66
+			else{
67
+				if ($rule[$item] == '(')
68
+				{
69
+					$parenthesis_count++;
70
+				}
71
+				if ($rule[$item] == ')')
72
+				{
73
+					$parenthesis_count--;
74
+				}
75
+				$item++;
76
+			}
77
+		}
78 78
         
79
-        if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
80
-        $val=substr($rule,$start,$item-$start);
81
-        $item++;
82
-        $start=0;
83
-        //echo "group : ".$val."\n";
84
-        // returns evaluation of group as type 2 (boolean)
85
-        return array(2,$this->evaluation($val,$start));
86
-    }
79
+		if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
80
+		$val=substr($rule,$start,$item-$start);
81
+		$item++;
82
+		$start=0;
83
+		//echo "group : ".$val."\n";
84
+		// returns evaluation of group as type 2 (boolean)
85
+		return array(2,$this->evaluation($val,$start));
86
+	}
87 87
     
88
-    protected function eval_getElement($rule,&$item)
89
-    {
90
-        if ($item >= strlen($rule))
91
-        {
92
-            throw new Exception("Early end of string ".$rule ." at " .$item );
93
-        }
94
-        while ($rule[$item]==' ') $item++;
95
-        if (preg_match('/[\-0-9\.]/',$rule[$item]))
96
-        { // number
97
-            return $this->get_number($rule, $item);
98
-        }
99
-        if ($rule[$item] == '"')
100
-        { // string
101
-            return $this->get_string($rule, $item);
102
-        }
88
+	protected function eval_getElement($rule,&$item)
89
+	{
90
+		if ($item >= strlen($rule))
91
+		{
92
+			throw new Exception("Early end of string ".$rule ." at " .$item );
93
+		}
94
+		while ($rule[$item]==' ') $item++;
95
+		if (preg_match('/[\-0-9\.]/',$rule[$item]))
96
+		{ // number
97
+			return $this->get_number($rule, $item);
98
+		}
99
+		if ($rule[$item] == '"')
100
+		{ // string
101
+			return $this->get_string($rule, $item);
102
+		}
103 103
         
104
-        if ($rule[$item] == '(')
105
-        { // grouping
106
-            return $this->get_group($rule, $item);
107
-        }
108
-        throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
104
+		if ($rule[$item] == '(')
105
+		{ // grouping
106
+			return $this->get_group($rule, $item);
107
+		}
108
+		throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
109 109
         
110
-    }
110
+	}
111 111
     
112
-    protected function eval_getNext($rule,$item,$tok)
113
-    {
114
-        while (
115
-            ($rule[$item] != $tok ) 
116
-            && ($item < strlen($rule))) 
117
-        { 
118
-            $item++;
119
-        }
120
-        if ($item==strlen($rule)) {
121
-            throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
122
-        }
123
-        return $item+1;
124
-    }
112
+	protected function eval_getNext($rule,$item,$tok)
113
+	{
114
+		while (
115
+			($rule[$item] != $tok ) 
116
+			&& ($item < strlen($rule))) 
117
+		{ 
118
+			$item++;
119
+		}
120
+		if ($item==strlen($rule)) {
121
+			throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
122
+		}
123
+		return $item+1;
124
+	}
125 125
     
126
-    protected function eval_getOper($rule,&$item)
127
-    {
128
-        while ($rule[$item]==' ') $item++;
129
-        switch ($rule[$item])
130
-        {
131
-            case '<':
132
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
133
-                $item++; return array(0,"<");
134
-            case '>':
135
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
136
-                $item++; return array(0,">");
137
-            case '=':
138
-                $item++; return array(0,"=");
139
-            case '!':
140
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
141
-                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
142
-            case '~':
143
-                $item++; return array(0,"~");
144
-            case '|':
145
-                $item++; return array(1,"|");
146
-            case '&':
147
-                $item++; return array(1,"&");
148
-            default	:
149
-                throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
150
-        }
151
-    }
126
+	protected function eval_getOper($rule,&$item)
127
+	{
128
+		while ($rule[$item]==' ') $item++;
129
+		switch ($rule[$item])
130
+		{
131
+			case '<':
132
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
133
+				$item++; return array(0,"<");
134
+			case '>':
135
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
136
+				$item++; return array(0,">");
137
+			case '=':
138
+				$item++; return array(0,"=");
139
+			case '!':
140
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
141
+				throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
142
+			case '~':
143
+				$item++; return array(0,"~");
144
+			case '|':
145
+				$item++; return array(1,"|");
146
+			case '&':
147
+				$item++; return array(1,"&");
148
+			default	:
149
+				throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
150
+		}
151
+	}
152 152
     
153
-    private function check_negate_first($rule,&$item)
154
-    {
155
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
156
-        {
157
-            $item++;
158
-            return true;
159
-        }
160
-        else
161
-        {
162
-            return false;
163
-        }
164
-    }
153
+	private function check_negate_first($rule,&$item)
154
+	{
155
+		if ( $rule[$item] == '!') // If '!' found, negate next expression.
156
+		{
157
+			$item++;
158
+			return true;
159
+		}
160
+		else
161
+		{
162
+			return false;
163
+		}
164
+	}
165 165
 
166
-    private function do_compare($val1,$val2,$comp,$negate)
167
-    {
168
-        switch ($comp){
169
-            case '<':	$retVal= ($val1 < $val2); break;
170
-            case '<=':	$retVal= ($val1 <= $val2); break;
171
-            case '>':	$retVal= ($val1 > $val2); break;
172
-            case '>=':	$retVal= ($val1 >= $val2); break;
173
-            case '=':	$retVal= ($val1 == $val2); break;
174
-            case '!=':	$retVal= ($val1 != $val2); break;
175
-            case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
176
-            case '|':	$retVal= ($val1 || $val2); break;
177
-            case '&':	$retVal= ($val1 && $val2); break;
178
-            default:  throw new Exception("Error in expression - unknown comp : ".$comp);
179
-        }
180
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
166
+	private function do_compare($val1,$val2,$comp,$negate)
167
+	{
168
+		switch ($comp){
169
+			case '<':	$retVal= ($val1 < $val2); break;
170
+			case '<=':	$retVal= ($val1 <= $val2); break;
171
+			case '>':	$retVal= ($val1 > $val2); break;
172
+			case '>=':	$retVal= ($val1 >= $val2); break;
173
+			case '=':	$retVal= ($val1 == $val2); break;
174
+			case '!=':	$retVal= ($val1 != $val2); break;
175
+			case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
176
+			case '|':	$retVal= ($val1 || $val2); break;
177
+			case '&':	$retVal= ($val1 && $val2); break;
178
+			default:  throw new Exception("Error in expression - unknown comp : ".$comp);
179
+		}
180
+		if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
181 181
         
182
-        return $retVal;
183
-    }
182
+		return $retVal;
183
+	}
184 184
     
185
-    /** Evaluation : makes token and evaluate.
186
-     *	Public function for expressions testing
187
-     *	accepts : < > = <= >= !=  (typec = 0)
188
-     *	operators : & | (typec=1)
189
-     *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
190
-     *   comparison int vs strings will return null (error)
191
-     *	return : bool or null on error
192
-     */
193
-    public function evaluation($rule,&$item)
194
-    {
195
-        //echo "Evaluation of ".substr($rule,$item)."\n";
196
-        $negate=$this->check_negate_first($rule, $item);
197
-        // First element : number, string or ()
198
-        list($type1,$val1) = $this->eval_getElement($rule,$item);
199
-        //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
185
+	/** Evaluation : makes token and evaluate.
186
+	 *	Public function for expressions testing
187
+	 *	accepts : < > = <= >= !=  (typec = 0)
188
+	 *	operators : & | (typec=1)
189
+	 *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
190
+	 *   comparison int vs strings will return null (error)
191
+	 *	return : bool or null on error
192
+	 */
193
+	public function evaluation($rule,&$item)
194
+	{
195
+		//echo "Evaluation of ".substr($rule,$item)."\n";
196
+		$negate=$this->check_negate_first($rule, $item);
197
+		// First element : number, string or ()
198
+		list($type1,$val1) = $this->eval_getElement($rule,$item);
199
+		//echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
200 200
         
201
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
202
-        {
203
-            if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
204
-            if ($negate === true) $val1= ! $val1;
205
-            return $val1;
206
-        }
201
+		if ($item==strlen($rule)) // If only element, return value, but only boolean
202
+		{
203
+			if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
204
+			if ($negate === true) $val1= ! $val1;
205
+			return $val1;
206
+		}
207 207
         
208
-        // Second element : operator
209
-        list($typec,$comp) = $this->eval_getOper($rule,$item);
210
-        //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
208
+		// Second element : operator
209
+		list($typec,$comp) = $this->eval_getOper($rule,$item);
210
+		//echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
211 211
         
212
-        // Third element : number, string or ()
213
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
214
-        {
215
-            $item++;
216
-            if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
217
-            $val2= ! $this->evaluation($rule,$item);
218
-            $type2=2; // result is a boolean
219
-        }
220
-        else
221
-        {
222
-            list($type2,$val2) = $this->eval_getElement($rule,$item);
223
-        }
224
-        //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
212
+		// Third element : number, string or ()
213
+		if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
214
+		{
215
+			$item++;
216
+			if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
217
+			$val2= ! $this->evaluation($rule,$item);
218
+			$type2=2; // result is a boolean
219
+		}
220
+		else
221
+		{
222
+			list($type2,$val2) = $this->eval_getElement($rule,$item);
223
+		}
224
+		//echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
225 225
         
226
-        if ($type1!=$type2)  // cannot compare different types
227
-        {
228
-            throw new Exception("Cannot compare string & number : ".$rule);
229
-        }
230
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
231
-        {
232
-            throw new Exception("Cannot use boolean operators with string & number : ".$rule);
233
-        }
226
+		if ($type1!=$type2)  // cannot compare different types
227
+		{
228
+			throw new Exception("Cannot compare string & number : ".$rule);
229
+		}
230
+		if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
231
+		{
232
+			throw new Exception("Cannot use boolean operators with string & number : ".$rule);
233
+		}
234 234
         
235
-        $retVal = $this->do_compare($val1, $val2, $comp, $negate);
235
+		$retVal = $this->do_compare($val1, $val2, $comp, $negate);
236 236
         
237
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
238
-        // check for logical operator :
239
-        switch ($rule[$item])
240
-        {
241
-            case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
242
-            case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
237
+		if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
238
+		// check for logical operator :
239
+		switch ($rule[$item])
240
+		{
241
+			case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
242
+			case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
243 243
             
244
-            default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
245
-        }
246
-    }
244
+			default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
245
+		}
246
+	}
247 247
     
248
-    // Remove all whitespaces (when not quoted)
249
-    public function eval_cleanup($rule)
250
-    {
251
-        $item=0;
252
-        $rule2='';
253
-        while ($item < strlen($rule))
254
-        {
255
-            if ($rule[$item]==' ') { $item++; continue; }
256
-            if ($rule[$item]=='"')
257
-            {
258
-                $rule2.=$rule[$item];
259
-                $item++;
260
-                while (($item < strlen($rule)) && ($rule[$item]!='"') )
261
-                {
262
-                    $rule2.=$rule[$item];
263
-                    $item++;
264
-                }
265
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
266
-                $rule2.=$rule[$item];
267
-                $item++;
268
-                continue;
269
-            }
248
+	// Remove all whitespaces (when not quoted)
249
+	public function eval_cleanup($rule)
250
+	{
251
+		$item=0;
252
+		$rule2='';
253
+		while ($item < strlen($rule))
254
+		{
255
+			if ($rule[$item]==' ') { $item++; continue; }
256
+			if ($rule[$item]=='"')
257
+			{
258
+				$rule2.=$rule[$item];
259
+				$item++;
260
+				while (($item < strlen($rule)) && ($rule[$item]!='"') )
261
+				{
262
+					$rule2.=$rule[$item];
263
+					$item++;
264
+				}
265
+				if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
266
+				$rule2.=$rule[$item];
267
+				$item++;
268
+				continue;
269
+			}
270 270
             
271
-            $rule2.=$rule[$item];
272
-            $item++;
273
-        }
271
+			$rule2.=$rule[$item];
272
+			$item++;
273
+		}
274 274
         
275
-        return $rule2;
276
-    }
275
+		return $rule2;
276
+	}
277 277
     
278
-    /** Evaluation rule (uses eval_* functions recursively)
279
-     *	@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) )
280
-     *  @param array $oidList : OIDs values to sustitute.
281
-     *	@return bool : true : rule match, false : rule don't match , throw exception on error.
282
-     */
278
+	/** Evaluation rule (uses eval_* functions recursively)
279
+	 *	@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) )
280
+	 *  @param array $oidList : OIDs values to sustitute.
281
+	 *	@return bool : true : rule match, false : rule don't match , throw exception on error.
282
+	 */
283 283
     
284
-    public function eval_rule($rule,$oidList)
285
-    {
286
-        if ($rule==null || $rule == '') // Empty rule is always true
287
-        {
288
-            return true;
289
-        }
290
-        $matches=array();
291
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
292
-        {
293
-            $oid=$matches[1];
294
-            $found=0;
295
-            // ** replaced by .*
296
-            $oidR=preg_replace('/\*\*/', '.*', $oid);
297
-            // * replaced by [0-9]+ 
298
-            $oidR=preg_replace('/\*/', '[0-9]+', $oidR);
284
+	public function eval_rule($rule,$oidList)
285
+	{
286
+		if ($rule==null || $rule == '') // Empty rule is always true
287
+		{
288
+			return true;
289
+		}
290
+		$matches=array();
291
+		while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
292
+		{
293
+			$oid=$matches[1];
294
+			$found=0;
295
+			// ** replaced by .*
296
+			$oidR=preg_replace('/\*\*/', '.*', $oid);
297
+			// * replaced by [0-9]+ 
298
+			$oidR=preg_replace('/\*/', '[0-9]+', $oidR);
299 299
             
300
-            // replace * with \* in oid for preg_replace
301
-            $oid=preg_replace('/\*/', '\*', $oid);
300
+			// replace * with \* in oid for preg_replace
301
+			$oid=preg_replace('/\*/', '\*', $oid);
302 302
             
303
-            $this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
303
+			$this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
304 304
             
305
-            foreach($oidList as $val)
306
-            {
307
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
308
-                {
309
-                    if (!preg_match('/^-?[0-9]*\.?[0-9]+$/',$val->value))
310
-                    { // If not a number, change " to ' and put " around it
311
-                        $val->value=preg_replace('/"/',"'",$val->value);
312
-                        $val->value='"'.$val->value.'"';
313
-                    }
314
-                    $rep=0;
315
-                    $rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
316
-                    if ($rep==0)
317
-                    {
318
-                        $this->logging->log("Error in rule_eval",WARN,'');
319
-                        return false;
320
-                    }
321
-                    $found=1;
322
-                    break;
323
-                }
324
-            }
325
-            if ($found==0)
326
-            {	// OID not found : throw error
327
-                throw new Exception('OID '.$oid.' not found in trap');
328
-            }
329
-        }
330
-        $item=0;
331
-        $rule=$this->eval_cleanup($rule);
332
-        $this->logging->log('Rule after clenup: '.$rule,INFO );
305
+			foreach($oidList as $val)
306
+			{
307
+				if (preg_match("/^$oidR$/",$val->oid) == 1)
308
+				{
309
+					if (!preg_match('/^-?[0-9]*\.?[0-9]+$/',$val->value))
310
+					{ // If not a number, change " to ' and put " around it
311
+						$val->value=preg_replace('/"/',"'",$val->value);
312
+						$val->value='"'.$val->value.'"';
313
+					}
314
+					$rep=0;
315
+					$rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
316
+					if ($rep==0)
317
+					{
318
+						$this->logging->log("Error in rule_eval",WARN,'');
319
+						return false;
320
+					}
321
+					$found=1;
322
+					break;
323
+				}
324
+			}
325
+			if ($found==0)
326
+			{	// OID not found : throw error
327
+				throw new Exception('OID '.$oid.' not found in trap');
328
+			}
329
+		}
330
+		$item=0;
331
+		$rule=$this->eval_cleanup($rule);
332
+		$this->logging->log('Rule after clenup: '.$rule,INFO );
333 333
         
334
-        return  $this->evaluation($rule,$item);
335
-    }
334
+		return  $this->evaluation($rule,$item);
335
+	}
336 336
     
337 337
 }
338 338
\ 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
@@ -23,47 +23,47 @@  discard block
 block discarded – undo
23 23
  * Get full number 
24 24
  * @return array<number,string>
25 25
  */
26
-    private function get_number($rule,&$item)
26
+    private function get_number($rule, &$item)
27 27
     {
28
-        $item2=$item+1;
28
+        $item2=$item + 1;
29 29
         while (
30
-            ($item2!=strlen($rule)) 
31
-            && (preg_match('/[\-0-9\.]/',$rule[$item2]))) 
30
+            ($item2 != strlen($rule)) 
31
+            && (preg_match('/[\-0-9\.]/', $rule[$item2]))) 
32 32
         { 
33
-            $item2++ ;
33
+            $item2++;
34 34
         }
35
-        $val=substr($rule,$item,$item2-$item);
35
+        $val=substr($rule, $item, $item2 - $item);
36 36
         $item=$item2;
37 37
         //echo "number ".$val."\n";
38 38
         
39
-        return array(0,$val);
39
+        return array(0, $val);
40 40
     }
41 41
 
42
-    private function get_string($rule,&$item)
42
+    private function get_string($rule, &$item)
43 43
     {
44 44
         $item++;
45
-        $item2=$this->eval_getNext($rule,$item,'"');
46
-        $val=substr($rule,$item,$item2-$item-1);
45
+        $item2=$this->eval_getNext($rule, $item, '"');
46
+        $val=substr($rule, $item, $item2 - $item - 1);
47 47
         $item=$item2;
48 48
         //echo "string : ".$val."\n";
49
-        return array(1,$val);
49
+        return array(1, $val);
50 50
         
51 51
     }
52 52
     
53
-    private function get_group($rule,&$item)
53
+    private function get_group($rule, &$item)
54 54
     {
55 55
         $item++;
56 56
         $start=$item;
57 57
         $parenthesis_count=0;
58 58
         while (($item < strlen($rule)) // Not end of string AND
59
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
59
+            && (($rule[$item] != ')') || $parenthesis_count > 0)) // Closing ')' or embeded ()
60 60
         {
61
-            if ($rule[$item] == '"' )
61
+            if ($rule[$item] == '"')
62 62
             { // pass through string
63 63
                 $item++;
64
-                $item=$this->eval_getNext($rule,$item,'"');
64
+                $item=$this->eval_getNext($rule, $item, '"');
65 65
             }
66
-            else{
66
+            else {
67 67
                 if ($rule[$item] == '(')
68 68
                 {
69 69
                     $parenthesis_count++;
@@ -76,23 +76,23 @@  discard block
 block discarded – undo
76 76
             }
77 77
         }
78 78
         
79
-        if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
80
-        $val=substr($rule,$start,$item-$start);
79
+        if ($item == strlen($rule)) {throw new Exception("no closing () in ".$rule." at ".$item); }
80
+        $val=substr($rule, $start, $item - $start);
81 81
         $item++;
82 82
         $start=0;
83 83
         //echo "group : ".$val."\n";
84 84
         // returns evaluation of group as type 2 (boolean)
85
-        return array(2,$this->evaluation($val,$start));
85
+        return array(2, $this->evaluation($val, $start));
86 86
     }
87 87
     
88
-    protected function eval_getElement($rule,&$item)
88
+    protected function eval_getElement($rule, &$item)
89 89
     {
90 90
         if ($item >= strlen($rule))
91 91
         {
92
-            throw new Exception("Early end of string ".$rule ." at " .$item );
92
+            throw new Exception("Early end of string ".$rule." at ".$item);
93 93
         }
94
-        while ($rule[$item]==' ') $item++;
95
-        if (preg_match('/[\-0-9\.]/',$rule[$item]))
94
+        while ($rule[$item] == ' ') $item++;
95
+        if (preg_match('/[\-0-9\.]/', $rule[$item]))
96 96
         { // number
97 97
             return $this->get_number($rule, $item);
98 98
         }
@@ -105,54 +105,54 @@  discard block
 block discarded – undo
105 105
         { // grouping
106 106
             return $this->get_group($rule, $item);
107 107
         }
108
-        throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
108
+        throw new Exception("number/string not found in ".$rule." at ".$item.' : '.$rule[$item]);
109 109
         
110 110
     }
111 111
     
112
-    protected function eval_getNext($rule,$item,$tok)
112
+    protected function eval_getNext($rule, $item, $tok)
113 113
     {
114 114
         while (
115
-            ($rule[$item] != $tok ) 
115
+            ($rule[$item] != $tok) 
116 116
             && ($item < strlen($rule))) 
117 117
         { 
118 118
             $item++;
119 119
         }
120
-        if ($item==strlen($rule)) {
121
-            throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
120
+        if ($item == strlen($rule)) {
121
+            throw new Exception("closing '".$tok."' not found in ".$rule." at ".$item);
122 122
         }
123
-        return $item+1;
123
+        return $item + 1;
124 124
     }
125 125
     
126
-    protected function eval_getOper($rule,&$item)
126
+    protected function eval_getOper($rule, &$item)
127 127
     {
128
-        while ($rule[$item]==' ') $item++;
128
+        while ($rule[$item] == ' ') $item++;
129 129
         switch ($rule[$item])
130 130
         {
131 131
             case '<':
132
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
133
-                $item++; return array(0,"<");
132
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, "<="); }
133
+                $item++; return array(0, "<");
134 134
             case '>':
135
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
136
-                $item++; return array(0,">");
135
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, ">="); }
136
+                $item++; return array(0, ">");
137 137
             case '=':
138
-                $item++; return array(0,"=");
138
+                $item++; return array(0, "=");
139 139
             case '!':
140
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
141
-                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
140
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, "!="); }
141
+                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule." at ".$item);
142 142
             case '~':
143
-                $item++; return array(0,"~");
143
+                $item++; return array(0, "~");
144 144
             case '|':
145
-                $item++; return array(1,"|");
145
+                $item++; return array(1, "|");
146 146
             case '&':
147
-                $item++; return array(1,"&");
147
+                $item++; return array(1, "&");
148 148
             default	:
149
-                throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
149
+                throw new Exception("Erreur in expr - operator not found in ".$rule." at ".$item);
150 150
         }
151 151
     }
152 152
     
153
-    private function check_negate_first($rule,&$item)
153
+    private function check_negate_first($rule, &$item)
154 154
     {
155
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
155
+        if ($rule[$item] == '!') // If '!' found, negate next expression.
156 156
         {
157 157
             $item++;
158 158
             return true;
@@ -163,21 +163,21 @@  discard block
 block discarded – undo
163 163
         }
164 164
     }
165 165
 
166
-    private function do_compare($val1,$val2,$comp,$negate)
166
+    private function do_compare($val1, $val2, $comp, $negate)
167 167
     {
168
-        switch ($comp){
169
-            case '<':	$retVal= ($val1 < $val2); break;
170
-            case '<=':	$retVal= ($val1 <= $val2); break;
171
-            case '>':	$retVal= ($val1 > $val2); break;
172
-            case '>=':	$retVal= ($val1 >= $val2); break;
173
-            case '=':	$retVal= ($val1 == $val2); break;
174
-            case '!=':	$retVal= ($val1 != $val2); break;
175
-            case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
176
-            case '|':	$retVal= ($val1 || $val2); break;
177
-            case '&':	$retVal= ($val1 && $val2); break;
168
+        switch ($comp) {
169
+            case '<':	$retVal=($val1 < $val2); break;
170
+            case '<=':	$retVal=($val1 <= $val2); break;
171
+            case '>':	$retVal=($val1 > $val2); break;
172
+            case '>=':	$retVal=($val1 >= $val2); break;
173
+            case '=':	$retVal=($val1 == $val2); break;
174
+            case '!=':	$retVal=($val1 != $val2); break;
175
+            case '~':	$retVal=(preg_match('/'.preg_replace('/"/', '', $val2).'/', $val1)); break;
176
+            case '|':	$retVal=($val1 || $val2); break;
177
+            case '&':	$retVal=($val1 && $val2); break;
178 178
             default:  throw new Exception("Error in expression - unknown comp : ".$comp);
179 179
         }
180
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
180
+        if ($negate === true) $retVal=!$retVal; // Inverse result if negate before expression
181 181
         
182 182
         return $retVal;
183 183
     }
@@ -190,56 +190,56 @@  discard block
 block discarded – undo
190 190
      *   comparison int vs strings will return null (error)
191 191
      *	return : bool or null on error
192 192
      */
193
-    public function evaluation($rule,&$item)
193
+    public function evaluation($rule, &$item)
194 194
     {
195 195
         //echo "Evaluation of ".substr($rule,$item)."\n";
196 196
         $negate=$this->check_negate_first($rule, $item);
197 197
         // First element : number, string or ()
198
-        list($type1,$val1) = $this->eval_getElement($rule,$item);
198
+        list($type1, $val1)=$this->eval_getElement($rule, $item);
199 199
         //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
200 200
         
201
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
201
+        if ($item == strlen($rule)) // If only element, return value, but only boolean
202 202
         {
203 203
             if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
204
-            if ($negate === true) $val1= ! $val1;
204
+            if ($negate === true) $val1=!$val1;
205 205
             return $val1;
206 206
         }
207 207
         
208 208
         // Second element : operator
209
-        list($typec,$comp) = $this->eval_getOper($rule,$item);
209
+        list($typec, $comp)=$this->eval_getOper($rule, $item);
210 210
         //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
211 211
         
212 212
         // Third element : number, string or ()
213
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
213
+        if ($rule[$item] == '!') // starts with a ! so evaluate whats next
214 214
         {
215 215
             $item++;
216 216
             if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
217
-            $val2= ! $this->evaluation($rule,$item);
217
+            $val2=!$this->evaluation($rule, $item);
218 218
             $type2=2; // result is a boolean
219 219
         }
220 220
         else
221 221
         {
222
-            list($type2,$val2) = $this->eval_getElement($rule,$item);
222
+            list($type2, $val2)=$this->eval_getElement($rule, $item);
223 223
         }
224 224
         //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
225 225
         
226
-        if ($type1!=$type2)  // cannot compare different types
226
+        if ($type1 != $type2)  // cannot compare different types
227 227
         {
228 228
             throw new Exception("Cannot compare string & number : ".$rule);
229 229
         }
230
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
230
+        if ($typec == 1 && $type1 != 2) // cannot use & or | with string/number
231 231
         {
232 232
             throw new Exception("Cannot use boolean operators with string & number : ".$rule);
233 233
         }
234 234
         
235
-        $retVal = $this->do_compare($val1, $val2, $comp, $negate);
235
+        $retVal=$this->do_compare($val1, $val2, $comp, $negate);
236 236
         
237
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
237
+        if ($item == strlen($rule)) return $retVal; // End of string : return evaluation
238 238
         // check for logical operator :
239 239
         switch ($rule[$item])
240 240
         {
241
-            case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
242
-            case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
241
+            case '|':	$item++; return ($retVal || $this->evaluation($rule, $item));
242
+            case '&':	$item++; return ($retVal && $this->evaluation($rule, $item));
243 243
             
244 244
             default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
245 245
         }
@@ -252,17 +252,17 @@  discard block
 block discarded – undo
252 252
         $rule2='';
253 253
         while ($item < strlen($rule))
254 254
         {
255
-            if ($rule[$item]==' ') { $item++; continue; }
256
-            if ($rule[$item]=='"')
255
+            if ($rule[$item] == ' ') { $item++; continue; }
256
+            if ($rule[$item] == '"')
257 257
             {
258 258
                 $rule2.=$rule[$item];
259 259
                 $item++;
260
-                while (($item < strlen($rule)) && ($rule[$item]!='"') )
260
+                while (($item < strlen($rule)) && ($rule[$item] != '"'))
261 261
                 {
262 262
                     $rule2.=$rule[$item];
263 263
                     $item++;
264 264
                 }
265
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
265
+                if ($item == strlen($rule)) throw new Exception("closing '\"' not found in ".$rule." at ".$item);
266 266
                 $rule2.=$rule[$item];
267 267
                 $item++;
268 268
                 continue;
@@ -281,14 +281,14 @@  discard block
 block discarded – undo
281 281
      *	@return bool : true : rule match, false : rule don't match , throw exception on error.
282 282
      */
283 283
     
284
-    public function eval_rule($rule,$oidList)
284
+    public function eval_rule($rule, $oidList)
285 285
     {
286
-        if ($rule==null || $rule == '') // Empty rule is always true
286
+        if ($rule == null || $rule == '') // Empty rule is always true
287 287
         {
288 288
             return true;
289 289
         }
290 290
         $matches=array();
291
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
291
+        while (preg_match('/_OID\(([0-9\.\*]+)\)/', $rule, $matches) == 1)
292 292
         {
293 293
             $oid=$matches[1];
294 294
             $found=0;
@@ -300,38 +300,38 @@  discard block
 block discarded – undo
300 300
             // replace * with \* in oid for preg_replace
301 301
             $oid=preg_replace('/\*/', '\*', $oid);
302 302
             
303
-            $this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
303
+            $this->logging->log('OID in rule : '.$oid.' / '.$oidR, DEBUG);
304 304
             
305
-            foreach($oidList as $val)
305
+            foreach ($oidList as $val)
306 306
             {
307
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
307
+                if (preg_match("/^$oidR$/", $val->oid) == 1)
308 308
                 {
309
-                    if (!preg_match('/^-?[0-9]*\.?[0-9]+$/',$val->value))
309
+                    if (!preg_match('/^-?[0-9]*\.?[0-9]+$/', $val->value))
310 310
                     { // If not a number, change " to ' and put " around it
311
-                        $val->value=preg_replace('/"/',"'",$val->value);
311
+                        $val->value=preg_replace('/"/', "'", $val->value);
312 312
                         $val->value='"'.$val->value.'"';
313 313
                     }
314 314
                     $rep=0;
315
-                    $rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
316
-                    if ($rep==0)
315
+                    $rule=preg_replace('/_OID\('.$oid.'\)/', $val->value, $rule, -1, $rep);
316
+                    if ($rep == 0)
317 317
                     {
318
-                        $this->logging->log("Error in rule_eval",WARN,'');
318
+                        $this->logging->log("Error in rule_eval", WARN, '');
319 319
                         return false;
320 320
                     }
321 321
                     $found=1;
322 322
                     break;
323 323
                 }
324 324
             }
325
-            if ($found==0)
325
+            if ($found == 0)
326 326
             {	// OID not found : throw error
327 327
                 throw new Exception('OID '.$oid.' not found in trap');
328 328
             }
329 329
         }
330 330
         $item=0;
331 331
         $rule=$this->eval_cleanup($rule);
332
-        $this->logging->log('Rule after clenup: '.$rule,INFO );
332
+        $this->logging->log('Rule after clenup: '.$rule, INFO);
333 333
         
334
-        return  $this->evaluation($rule,$item);
334
+        return  $this->evaluation($rule, $item);
335 335
     }
336 336
     
337 337
 }
338 338
\ 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
@@ -56,14 +56,15 @@  discard block
 block discarded – undo
56 56
         $start=$item;
57 57
         $parenthesis_count=0;
58 58
         while (($item < strlen($rule)) // Not end of string AND
59
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
59
+            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) {
60
+        	// Closing ')' or embeded ()
60 61
         {
61 62
             if ($rule[$item] == '"' )
62 63
             { // pass through string
63 64
                 $item++;
65
+        }
64 66
                 $item=$this->eval_getNext($rule,$item,'"');
65
-            }
66
-            else{
67
+            } else{
67 68
                 if ($rule[$item] == '(')
68 69
                 {
69 70
                     $parenthesis_count++;
@@ -91,7 +92,9 @@  discard block
 block discarded – undo
91 92
         {
92 93
             throw new Exception("Early end of string ".$rule ." at " .$item );
93 94
         }
94
-        while ($rule[$item]==' ') $item++;
95
+        while ($rule[$item]==' ') {
96
+        	$item++;
97
+        }
95 98
         if (preg_match('/[\-0-9\.]/',$rule[$item]))
96 99
         { // number
97 100
             return $this->get_number($rule, $item);
@@ -125,7 +128,9 @@  discard block
 block discarded – undo
125 128
     
126 129
     protected function eval_getOper($rule,&$item)
127 130
     {
128
-        while ($rule[$item]==' ') $item++;
131
+        while ($rule[$item]==' ') {
132
+        	$item++;
133
+        }
129 134
         switch ($rule[$item])
130 135
         {
131 136
             case '<':
@@ -152,12 +157,13 @@  discard block
 block discarded – undo
152 157
     
153 158
     private function check_negate_first($rule,&$item)
154 159
     {
155
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
160
+        if ( $rule[$item] == '!') {
161
+        	// If '!' found, negate next expression.
156 162
         {
157 163
             $item++;
158
-            return true;
159 164
         }
160
-        else
165
+            return true;
166
+        } else
161 167
         {
162 168
             return false;
163 169
         }
@@ -177,7 +183,10 @@  discard block
 block discarded – undo
177 183
             case '&':	$retVal= ($val1 && $val2); break;
178 184
             default:  throw new Exception("Error in expression - unknown comp : ".$comp);
179 185
         }
180
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
186
+        if ($negate === true) {
187
+        	$retVal = ! $retVal;
188
+        }
189
+        // Inverse result if negate before expression
181 190
         
182 191
         return $retVal;
183 192
     }
@@ -198,10 +207,14 @@  discard block
 block discarded – undo
198 207
         list($type1,$val1) = $this->eval_getElement($rule,$item);
199 208
         //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
200 209
         
201
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
210
+        if ($item==strlen($rule)) {
211
+        	// If only element, return value, but only boolean
202 212
         {
203 213
             if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
204
-            if ($negate === true) $val1= ! $val1;
214
+        }
215
+            if ($negate === true) {
216
+            	$val1= ! $val1;
217
+            }
205 218
             return $val1;
206 219
         }
207 220
         
@@ -210,31 +223,41 @@  discard block
 block discarded – undo
210 223
         //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
211 224
         
212 225
         // Third element : number, string or ()
213
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
226
+        if ( $rule[$item] == '!') {
227
+        	// starts with a ! so evaluate whats next
214 228
         {
215 229
             $item++;
216
-            if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
230
+        }
231
+            if ($typec != 1) {
232
+            	throw new Exception("Mixing boolean and comparison : ".$rule);
233
+            }
217 234
             $val2= ! $this->evaluation($rule,$item);
218 235
             $type2=2; // result is a boolean
219
-        }
220
-        else
236
+        } else
221 237
         {
222 238
             list($type2,$val2) = $this->eval_getElement($rule,$item);
223 239
         }
224 240
         //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
225 241
         
226
-        if ($type1!=$type2)  // cannot compare different types
242
+        if ($type1!=$type2) {
243
+        	// cannot compare different types
227 244
         {
228 245
             throw new Exception("Cannot compare string & number : ".$rule);
229 246
         }
230
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
247
+        }
248
+        if ($typec==1 && $type1 !=2) {
249
+        	// cannot use & or | with string/number
231 250
         {
232 251
             throw new Exception("Cannot use boolean operators with string & number : ".$rule);
233 252
         }
253
+        }
234 254
         
235 255
         $retVal = $this->do_compare($val1, $val2, $comp, $negate);
236 256
         
237
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
257
+        if ($item==strlen($rule)) {
258
+        	return $retVal;
259
+        }
260
+        // End of string : return evaluation
238 261
         // check for logical operator :
239 262
         switch ($rule[$item])
240 263
         {
@@ -262,7 +285,9 @@  discard block
 block discarded – undo
262 285
                     $rule2.=$rule[$item];
263 286
                     $item++;
264 287
                 }
265
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
288
+                if ($item == strlen ($rule)) {
289
+                	throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
290
+                }
266 291
                 $rule2.=$rule[$item];
267 292
                 $item++;
268 293
                 continue;
@@ -283,10 +308,12 @@  discard block
 block discarded – undo
283 308
     
284 309
     public function eval_rule($rule,$oidList)
285 310
     {
286
-        if ($rule==null || $rule == '') // Empty rule is always true
311
+        if ($rule==null || $rule == '') {
312
+        	// Empty rule is always true
287 313
         {
288 314
             return true;
289 315
         }
316
+        }
290 317
         $matches=array();
291 318
         while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
292 319
         {
Please login to merge, or discard this patch.
application/controllers/HelperController.php 3 patches
Indentation   +168 added lines, -168 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
 
@@ -472,53 +472,53 @@  discard block
 block discarded – undo
472 472
 	 */
473 473
 	public function pluginAction()
474 474
 	{
475
-	    $postData=$this->getRequest()->getPost();
476
-	    if (isset($postData['name']))
477
-	    {
478
-	        $pluginName=$postData['name'];
479
-	    }
480
-	    else
481
-	    {
482
-	        $this->_helper->json(array('status'=>'No plugin name'));
483
-	    }
484
-	    if (isset($postData['action']))
485
-	    {
486
-	        $action=$postData['action'];
487
-	        if ($action != 'enable' && $action != 'disable')
488
-	        {
489
-	            $this->_helper->json(array('status'=>'unknown action '.$action));
490
-	            return;
491
-	        }
492
-	    }
493
-	    else
494
-	    {
495
-	        $this->_helper->json(array('status'=>'No action'));
496
-	        return;
497
-	    }
475
+		$postData=$this->getRequest()->getPost();
476
+		if (isset($postData['name']))
477
+		{
478
+			$pluginName=$postData['name'];
479
+		}
480
+		else
481
+		{
482
+			$this->_helper->json(array('status'=>'No plugin name'));
483
+		}
484
+		if (isset($postData['action']))
485
+		{
486
+			$action=$postData['action'];
487
+			if ($action != 'enable' && $action != 'disable')
488
+			{
489
+				$this->_helper->json(array('status'=>'unknown action '.$action));
490
+				return;
491
+			}
492
+		}
493
+		else
494
+		{
495
+			$this->_helper->json(array('status'=>'No action'));
496
+			return;
497
+		}
498 498
 
499
-        try
500
-        {
501
-            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
502
-            $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
503
-            $Trap = new Trap($icingaweb2_etc);
504
-            // Enable plugin.
505
-            $action=($action == 'enable') ? true : false;
506
-            $retVal=$Trap->pluginClass->enablePlugin($pluginName, $action);
499
+		try
500
+		{
501
+			require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
502
+			$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
503
+			$Trap = new Trap($icingaweb2_etc);
504
+			// Enable plugin.
505
+			$action=($action == 'enable') ? true : false;
506
+			$retVal=$Trap->pluginClass->enablePlugin($pluginName, $action);
507 507
             
508
-        }
509
-        catch (Exception $e)
510
-        {
511
-            $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
512
-            return;
513
-        }
514
-        if ($retVal === true)
515
-        {
516
-            $this->_helper->json(array('status'=>'OK'));
517
-        }
518
-        else
519
-        {
520
-            $this->_helper->json(array('status'=>'Error, see logs'));
521
-        }
508
+		}
509
+		catch (Exception $e)
510
+		{
511
+			$this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
512
+			return;
513
+		}
514
+		if ($retVal === true)
515
+		{
516
+			$this->_helper->json(array('status'=>'OK'));
517
+		}
518
+		else
519
+		{
520
+			$this->_helper->json(array('status'=>'Error, see logs'));
521
+		}
522 522
 	}
523 523
 	
524 524
 	/** Function evaluation
@@ -528,46 +528,46 @@  discard block
 block discarded – undo
528 528
 	 */
529 529
 	public function functionAction()
530 530
 	{
531
-	    $postData=$this->getRequest()->getPost();
532
-	    if (isset($postData['function']))
533
-	    {
534
-	        $functionString=$postData['function'];
535
-	    }
536
-	    else
537
-	    {
538
-	        $this->_helper->json(array('status'=>'No function name'));
539
-	    }
540
-	    if (isset($postData['action']))
541
-	    {
542
-	        $action=$postData['action'];
543
-	        if ($action != 'evaluate')
544
-	        {
545
-	            $this->_helper->json(array('status'=>'unknown action '.$action));
546
-	            return;
547
-	        }
548
-	    }
549
-	    else
550
-	    {
551
-	        $this->_helper->json(array('status'=>'No action'));
552
-	        return;
553
-	    }
531
+		$postData=$this->getRequest()->getPost();
532
+		if (isset($postData['function']))
533
+		{
534
+			$functionString=$postData['function'];
535
+		}
536
+		else
537
+		{
538
+			$this->_helper->json(array('status'=>'No function name'));
539
+		}
540
+		if (isset($postData['action']))
541
+		{
542
+			$action=$postData['action'];
543
+			if ($action != 'evaluate')
544
+			{
545
+				$this->_helper->json(array('status'=>'unknown action '.$action));
546
+				return;
547
+			}
548
+		}
549
+		else
550
+		{
551
+			$this->_helper->json(array('status'=>'No action'));
552
+			return;
553
+		}
554 554
 	    
555
-	    try
556
-	    {
557
-	        require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
558
-	        $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
559
-	        $Trap = new Trap($icingaweb2_etc);
560
-	        // load plugins.
561
-	        $Trap->pluginClass->registerAllPlugins(false);
562
-	        $result = $Trap->pluginClass->evaluateFunctionString($functionString);	        
563
-	    }
564
-	    catch (Exception $e)
565
-	    {
566
-	        $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
567
-	        return;
568
-	    }
555
+		try
556
+		{
557
+			require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
558
+			$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
559
+			$Trap = new Trap($icingaweb2_etc);
560
+			// load plugins.
561
+			$Trap->pluginClass->registerAllPlugins(false);
562
+			$result = $Trap->pluginClass->evaluateFunctionString($functionString);	        
563
+		}
564
+		catch (Exception $e)
565
+		{
566
+			$this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
567
+			return;
568
+		}
569 569
 	    
570
-        $result = ($result === true)?'True':'False';
571
-        $this->_helper->json(array('status'=>'OK','message' => $result));
570
+		$result = ($result === true)?'True':'False';
571
+		$this->_helper->json(array('status'=>'OK','message' => $result));
572 572
 	}
573 573
 }
Please login to merge, or discard this patch.
Spacing   +44 added lines, -44 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
 	    
@@ -498,9 +498,9 @@  discard block
 block discarded – undo
498 498
 
499 499
         try
500 500
         {
501
-            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
501
+            require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
502 502
             $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
503
-            $Trap = new Trap($icingaweb2_etc);
503
+            $Trap=new Trap($icingaweb2_etc);
504 504
             // Enable plugin.
505 505
             $action=($action == 'enable') ? true : false;
506 506
             $retVal=$Trap->pluginClass->enablePlugin($pluginName, $action);
@@ -508,7 +508,7 @@  discard block
 block discarded – undo
508 508
         }
509 509
         catch (Exception $e)
510 510
         {
511
-            $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
511
+            $this->_helper->json(array('status'=>'Action error : '.$e->getMessage()));
512 512
             return;
513 513
         }
514 514
         if ($retVal === true)
@@ -554,20 +554,20 @@  discard block
 block discarded – undo
554 554
 	    
555 555
 	    try
556 556
 	    {
557
-	        require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
557
+	        require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
558 558
 	        $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
559
-	        $Trap = new Trap($icingaweb2_etc);
559
+	        $Trap=new Trap($icingaweb2_etc);
560 560
 	        // load plugins.
561 561
 	        $Trap->pluginClass->registerAllPlugins(false);
562
-	        $result = $Trap->pluginClass->evaluateFunctionString($functionString);	        
562
+	        $result=$Trap->pluginClass->evaluateFunctionString($functionString);	        
563 563
 	    }
564 564
 	    catch (Exception $e)
565 565
 	    {
566
-	        $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
566
+	        $this->_helper->json(array('status'=>'Action error : '.$e->getMessage()));
567 567
 	        return;
568 568
 	    }
569 569
 	    
570
-        $result = ($result === true)?'True':'False';
571
-        $this->_helper->json(array('status'=>'OK','message' => $result));
570
+        $result=($result === true) ? 'True' : 'False';
571
+        $this->_helper->json(array('status'=>'OK', 'message' => $result));
572 572
 	}
573 573
 }
Please login to merge, or discard this patch.
Braces   +32 added lines, -64 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;
@@ -476,8 +451,7 @@  discard block
 block discarded – undo
476 451
 	    if (isset($postData['name']))
477 452
 	    {
478 453
 	        $pluginName=$postData['name'];
479
-	    }
480
-	    else
454
+	    } else
481 455
 	    {
482 456
 	        $this->_helper->json(array('status'=>'No plugin name'));
483 457
 	    }
@@ -489,8 +463,7 @@  discard block
 block discarded – undo
489 463
 	            $this->_helper->json(array('status'=>'unknown action '.$action));
490 464
 	            return;
491 465
 	        }
492
-	    }
493
-	    else
466
+	    } else
494 467
 	    {
495 468
 	        $this->_helper->json(array('status'=>'No action'));
496 469
 	        return;
@@ -505,8 +478,7 @@  discard block
 block discarded – undo
505 478
             $action=($action == 'enable') ? true : false;
506 479
             $retVal=$Trap->pluginClass->enablePlugin($pluginName, $action);
507 480
             
508
-        }
509
-        catch (Exception $e)
481
+        } catch (Exception $e)
510 482
         {
511 483
             $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
512 484
             return;
@@ -514,8 +486,7 @@  discard block
 block discarded – undo
514 486
         if ($retVal === true)
515 487
         {
516 488
             $this->_helper->json(array('status'=>'OK'));
517
-        }
518
-        else
489
+        } else
519 490
         {
520 491
             $this->_helper->json(array('status'=>'Error, see logs'));
521 492
         }
@@ -532,8 +503,7 @@  discard block
 block discarded – undo
532 503
 	    if (isset($postData['function']))
533 504
 	    {
534 505
 	        $functionString=$postData['function'];
535
-	    }
536
-	    else
506
+	    } else
537 507
 	    {
538 508
 	        $this->_helper->json(array('status'=>'No function name'));
539 509
 	    }
@@ -545,8 +515,7 @@  discard block
 block discarded – undo
545 515
 	            $this->_helper->json(array('status'=>'unknown action '.$action));
546 516
 	            return;
547 517
 	        }
548
-	    }
549
-	    else
518
+	    } else
550 519
 	    {
551 520
 	        $this->_helper->json(array('status'=>'No action'));
552 521
 	        return;
@@ -560,8 +529,7 @@  discard block
 block discarded – undo
560 529
 	        // load plugins.
561 530
 	        $Trap->pluginClass->registerAllPlugins(false);
562 531
 	        $result = $Trap->pluginClass->evaluateFunctionString($functionString);	        
563
-	    }
564
-	    catch (Exception $e)
532
+	    } catch (Exception $e)
565 533
 	    {
566 534
 	        $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
567 535
 	        return;
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Plugins.php 3 patches
Braces   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -56,8 +56,7 @@  discard block
 block discarded – undo
56 56
         if ($pluginDir == '')
57 57
         {
58 58
             $this->pluginDir=dirname(__DIR__).'/Plugins';
59
-        }
60
-        else 
59
+        } else 
61 60
         {
62 61
             $this->pluginDir=$pluginDir;
63 62
         }
@@ -94,8 +93,7 @@  discard block
 block discarded – undo
94 93
         {
95 94
             $this->logClass->log('No enabled plugins',DEBUG);
96 95
             return;
97
-        }
98
-        else
96
+        } else
99 97
         {   // Saved config : <plugin name>;<Catch all OID ? 1|0>;<Trap target ? 1|0>;<func 1 name>|<func 2 name>... ,<plugin2 name>....
100 98
             $this->logClass->log('Enabled plugins = '.$PluginList,DEBUG);
101 99
             
@@ -233,9 +231,11 @@  discard block
 block discarded – undo
233 231
      */
234 232
     public function registerPlugin(string $pluginName)
235 233
     {
236
-        if ( ! isset($this->pluginsList[$pluginName]) ) // Plugin isn't enable, create entry
234
+        if ( ! isset($this->pluginsList[$pluginName]) ) {
235
+        	// Plugin isn't enable, create entry
237 236
         {
238 237
             $pluginListElmt = array();
238
+        }
239 239
             $pluginListElmt['object'] = null; // class not loaded
240 240
             $pluginListElmt['enabled'] = false;
241 241
             $this->pluginsList[$pluginName] = $pluginListElmt;
@@ -282,8 +282,7 @@  discard block
 block discarded – undo
282 282
                             . $pluginName . ' and ' . $this->functionList[$fname]['plugin']);
283 283
                     }
284 284
                     
285
-                }
286
-                else
285
+                } else
287 286
                 {
288 287
                     $this->functionList[$fname]=array();
289 288
                     $this->functionList[$fname]['plugin'] = $pluginName;
@@ -326,11 +325,13 @@  discard block
 block discarded – undo
326 325
                 $retDisplay .= $e->getMessage() . ' / ';
327 326
             }
328 327
         }
329
-        if ($checkEnabled === false) // Load all php files in plugin dir
328
+        if ($checkEnabled === false) {
329
+        	// Load all php files in plugin dir
330 330
         {
331 331
             foreach (glob($this->pluginDir."/*.php") as $filename)
332 332
             {             
333 333
                 $pluginName=basename($filename,'.php');
334
+        }
334 335
                 if (!preg_match('/^[a-zA-Z0-9]+$/',$pluginName))
335 336
                 {
336 337
                     $this->logClass->log("Invalid plugin name : ".$pluginName, WARN);
@@ -348,8 +349,7 @@  discard block
 block discarded – undo
348 349
         if ($retDisplay == '')
349 350
         {
350 351
             return 'All plugins loaded OK';
351
-        }
352
-        else
352
+        } else
353 353
         {
354 354
             return $retDisplay;
355 355
         }
Please login to merge, or discard this patch.
Indentation   +457 added lines, -457 removed lines patch added patch discarded remove patch
@@ -17,519 +17,519 @@
 block discarded – undo
17 17
  */
18 18
 class Plugins
19 19
 {
20
-    /** Array of plugin objects. Keys ar plugin name
21
-     * @var PluginTemplate[] $pluginsList Plugins array with name as index
22
-     * $pluginsList[plugin name]['object']  : plugin object (NULL of not loaded)
23
-     * $pluginsList[plugin name]['allOID']  : bool true if plugin catches all oid
24
-     * $pluginsList[plugin name]['target']  : bool true if plugin can be trap processing target
25
-     * $pluginsList[plugin name]['enabled'] : bool true if plugin is in enabled list 
26
-     **/
27
-    protected $pluginsList = array();
20
+	/** Array of plugin objects. Keys ar plugin name
21
+	 * @var PluginTemplate[] $pluginsList Plugins array with name as index
22
+	 * $pluginsList[plugin name]['object']  : plugin object (NULL of not loaded)
23
+	 * $pluginsList[plugin name]['allOID']  : bool true if plugin catches all oid
24
+	 * $pluginsList[plugin name]['target']  : bool true if plugin can be trap processing target
25
+	 * $pluginsList[plugin name]['enabled'] : bool true if plugin is in enabled list 
26
+	 **/
27
+	protected $pluginsList = array();
28 28
 
29
-    /** Array of functions names
30
-     * @var array $functionList 
31
-     * $functionList[name]['plugin'] : Plugin name
32
-     * $functionList[name]['function'] : Plugin function to call (null if plugin not loaded)
33
-    */
34
-    protected $functionList=array();
29
+	/** Array of functions names
30
+	 * @var array $functionList 
31
+	 * $functionList[name]['plugin'] : Plugin name
32
+	 * $functionList[name]['function'] : Plugin function to call (null if plugin not loaded)
33
+	 */
34
+	protected $functionList=array();
35 35
     
36
-    /** @var string[] $enabledPlugins list of enabled plugins */
37
-    //public $enabledPlugins = array();
36
+	/** @var string[] $enabledPlugins list of enabled plugins */
37
+	//public $enabledPlugins = array();
38 38
 
39 39
     
40
-    /** @var Logging $logClass */
41
-    protected $logClass;
40
+	/** @var Logging $logClass */
41
+	protected $logClass;
42 42
 
43
-    /** @var Trap $trapClass */
44
-    protected $trapClass;
43
+	/** @var Trap $trapClass */
44
+	protected $trapClass;
45 45
     
46
-    /** @var string $pluginDir */
47
-    protected $pluginDir;
46
+	/** @var string $pluginDir */
47
+	protected $pluginDir;
48 48
     
49
-    /** Setup class
50
-     * @param Trap $logClass  the top trap class
51
-     * @param string $plugin_dir optional plugin directory
52
-     * @throws \Exception
53
-     */
54
-    function __construct(Trap $trapClass,string $pluginDir='')
55
-    {
56
-        if ($pluginDir == '')
57
-        {
58
-            $this->pluginDir=dirname(__DIR__).'/Plugins';
59
-        }
60
-        else 
61
-        {
62
-            $this->pluginDir=$pluginDir;
63
-        }
64
-        // Set and check Logging class
65
-        $this->trapClass=$trapClass;
66
-        if ($this->trapClass === null)
67
-        {
68
-            throw new Exception('Log class not loaded into trap class');
69
-        }
70
-        $this->logClass=$trapClass->logging;
71
-        if ($this->logClass === null)
72
-        {
73
-            throw new Exception('Log class not loaded into trap class');
74
-        }
75
-        // check DB class and get plugins list.
76
-        if ($this->trapClass->trapsDB === null)
77
-        {
78
-            throw new Exception('Database class not loaded into trap class');
79
-        }
80
-        $this->loadEnabledPlugins();
81
-    }
49
+	/** Setup class
50
+	 * @param Trap $logClass  the top trap class
51
+	 * @param string $plugin_dir optional plugin directory
52
+	 * @throws \Exception
53
+	 */
54
+	function __construct(Trap $trapClass,string $pluginDir='')
55
+	{
56
+		if ($pluginDir == '')
57
+		{
58
+			$this->pluginDir=dirname(__DIR__).'/Plugins';
59
+		}
60
+		else 
61
+		{
62
+			$this->pluginDir=$pluginDir;
63
+		}
64
+		// Set and check Logging class
65
+		$this->trapClass=$trapClass;
66
+		if ($this->trapClass === null)
67
+		{
68
+			throw new Exception('Log class not loaded into trap class');
69
+		}
70
+		$this->logClass=$trapClass->logging;
71
+		if ($this->logClass === null)
72
+		{
73
+			throw new Exception('Log class not loaded into trap class');
74
+		}
75
+		// check DB class and get plugins list.
76
+		if ($this->trapClass->trapsDB === null)
77
+		{
78
+			throw new Exception('Database class not loaded into trap class');
79
+		}
80
+		$this->loadEnabledPlugins();
81
+	}
82 82
     
83 83
     
84
-    /**
85
-     * Load enabled plugins from database config table.
86
-     * Fills enabledPlugins and functionList properties
87
-     * @throws \Exception
88
-     */
89
-    private function loadEnabledPlugins()
90
-    {
91
-        $PluginList = $this->trapClass->trapsDB->getDBConfig('enabled_plugins');
84
+	/**
85
+	 * Load enabled plugins from database config table.
86
+	 * Fills enabledPlugins and functionList properties
87
+	 * @throws \Exception
88
+	 */
89
+	private function loadEnabledPlugins()
90
+	{
91
+		$PluginList = $this->trapClass->trapsDB->getDBConfig('enabled_plugins');
92 92
                
93
-        if ($PluginList === null || $PluginList == '')
94
-        {
95
-            $this->logClass->log('No enabled plugins',DEBUG);
96
-            return;
97
-        }
98
-        else
99
-        {   // Saved config : <plugin name>;<Catch all OID ? 1|0>;<Trap target ? 1|0>;<func 1 name>|<func 2 name>... ,<plugin2 name>....
100
-            $this->logClass->log('Enabled plugins = '.$PluginList,DEBUG);
93
+		if ($PluginList === null || $PluginList == '')
94
+		{
95
+			$this->logClass->log('No enabled plugins',DEBUG);
96
+			return;
97
+		}
98
+		else
99
+		{   // Saved config : <plugin name>;<Catch all OID ? 1|0>;<Trap target ? 1|0>;<func 1 name>|<func 2 name>... ,<plugin2 name>....
100
+			$this->logClass->log('Enabled plugins = '.$PluginList,DEBUG);
101 101
             
102
-            $pluginArray = explode(',', $PluginList);
103
-            foreach ($pluginArray as $pluginElmt)
104
-            {
105
-                $pluginElmt = explode(';',$pluginElmt);
106
-                if ($pluginElmt === false || count($pluginElmt) != 4)
107
-                {
108
-                    throw new \Exception('Invalid plugin configuration : '. $PluginList );
109
-                }
110
-                $pluginName=$pluginElmt[0];
102
+			$pluginArray = explode(',', $PluginList);
103
+			foreach ($pluginArray as $pluginElmt)
104
+			{
105
+				$pluginElmt = explode(';',$pluginElmt);
106
+				if ($pluginElmt === false || count($pluginElmt) != 4)
107
+				{
108
+					throw new \Exception('Invalid plugin configuration : '. $PluginList );
109
+				}
110
+				$pluginName=$pluginElmt[0];
111 111
                 
112
-                $pluginListElmt = array();
113
-                $pluginListElmt['object'] = null; // class not loaded
114
-                $pluginListElmt['allOID'] = ($pluginElmt[1]=='1') ? true : false;
115
-                $pluginListElmt['target'] = ($pluginElmt[2]=='1') ? true : false;
116
-                $pluginListElmt['enabled'] = true;
112
+				$pluginListElmt = array();
113
+				$pluginListElmt['object'] = null; // class not loaded
114
+				$pluginListElmt['allOID'] = ($pluginElmt[1]=='1') ? true : false;
115
+				$pluginListElmt['target'] = ($pluginElmt[2]=='1') ? true : false;
116
+				$pluginListElmt['enabled'] = true;
117 117
                 
118
-                $this->pluginsList[$pluginName] = $pluginListElmt;
118
+				$this->pluginsList[$pluginName] = $pluginListElmt;
119 119
                 
120
-                // deal with plugin functions
121
-                $pluginFunctions = explode('|',$pluginElmt[3]);
122
-                if ($pluginFunctions !== false)
123
-                {
124
-                    foreach ($pluginFunctions as $function)
125
-                    {
126
-                        $this->functionList[$function] = array(
127
-                            'plugin'    =>   $pluginName,
128
-                            'function'  =>  null
129
-                        );
130
-                    }
131
-                }
132
-            }
120
+				// deal with plugin functions
121
+				$pluginFunctions = explode('|',$pluginElmt[3]);
122
+				if ($pluginFunctions !== false)
123
+				{
124
+					foreach ($pluginFunctions as $function)
125
+					{
126
+						$this->functionList[$function] = array(
127
+							'plugin'    =>   $pluginName,
128
+							'function'  =>  null
129
+						);
130
+					}
131
+				}
132
+			}
133 133
 
134
-        }
134
+		}
135 135
         
136
-    }
136
+	}
137 137
 
138
-    /**
139
-     * Save enabled plugin array in DB config
140
-     * @return bool true if OK, or false (error logged by DB Class)
141
-     */
142
-    private function saveEnabledPlugins()
143
-    {
144
-        $saveString='';
145
-        foreach ($this->pluginsList as $name => $value)
146
-        {
147
-            if ($value['enabled'] == false)
148
-            {
149
-                continue;
150
-            }
151
-            $functionString='';
152
-            foreach ($this->functionList as $fName => $fvalue)
153
-            {
154
-                if ($fvalue['plugin'] != $name)
155
-                {
156
-                    continue;
157
-                }
158
-                $functionString .= ($functionString == '') ? '' : '|'; // add separator if not empty
159
-                $functionString .= $fName;
160
-            }
161
-            $saveString .= ($saveString == '')?'':',' ;
138
+	/**
139
+	 * Save enabled plugin array in DB config
140
+	 * @return bool true if OK, or false (error logged by DB Class)
141
+	 */
142
+	private function saveEnabledPlugins()
143
+	{
144
+		$saveString='';
145
+		foreach ($this->pluginsList as $name => $value)
146
+		{
147
+			if ($value['enabled'] == false)
148
+			{
149
+				continue;
150
+			}
151
+			$functionString='';
152
+			foreach ($this->functionList as $fName => $fvalue)
153
+			{
154
+				if ($fvalue['plugin'] != $name)
155
+				{
156
+					continue;
157
+				}
158
+				$functionString .= ($functionString == '') ? '' : '|'; // add separator if not empty
159
+				$functionString .= $fName;
160
+			}
161
+			$saveString .= ($saveString == '')?'':',' ;
162 162
             
163
-            $allOID = ($value['allOID'] === true) ? 1 : 0;
164
-            $target = ($value['target'] === true) ? 1 : 0;
165
-            $saveString .= $name . ';' . $allOID . ';' . $target . ';' . $functionString ;
166
-        }
167
-        $this->logClass->log('Saving : ' . $saveString,DEBUG);
168
-        return $this->trapClass->trapsDB->setDBConfig('enabled_plugins', $saveString);
169
-    }
163
+			$allOID = ($value['allOID'] === true) ? 1 : 0;
164
+			$target = ($value['target'] === true) ? 1 : 0;
165
+			$saveString .= $name . ';' . $allOID . ';' . $target . ';' . $functionString ;
166
+		}
167
+		$this->logClass->log('Saving : ' . $saveString,DEBUG);
168
+		return $this->trapClass->trapsDB->setDBConfig('enabled_plugins', $saveString);
169
+	}
170 170
     
171
-    /** Get enabled plugin list by name
172
-     * @return array
173
-     */
174
-    public function getEnabledPlugins() : array
175
-    {
176
-        $retArray=array();
177
-        foreach ($this->pluginsList as $name => $value)
178
-        {
179
-            if ($value['enabled'] == true)
180
-            {
181
-                array_push($retArray,$name);
182
-            }
183
-        }
184
-        return $retArray;
185
-    }
171
+	/** Get enabled plugin list by name
172
+	 * @return array
173
+	 */
174
+	public function getEnabledPlugins() : array
175
+	{
176
+		$retArray=array();
177
+		foreach ($this->pluginsList as $name => $value)
178
+		{
179
+			if ($value['enabled'] == true)
180
+			{
181
+				array_push($retArray,$name);
182
+			}
183
+		}
184
+		return $retArray;
185
+	}
186 186
 
187
-    /** Enable plugin (enabling an enabled plugin is OK, same for disabled).
188
-     *  and save in DB config
189
-     * @param string $pluginName
190
-     * @param bool $enabled true to enable, false to disable
191
-     * @return bool true if OK, or false (error logged)
192
-     */
193
-    public function enablePlugin(string $pluginName,bool $enabled)
194
-    {
195
-        if ($enabled === false)
196
-        {
197
-            // If plugin is defined set to disable
198
-            if ( isset($this->pluginsList[$pluginName]))
199
-            {
200
-                $this->pluginsList[$pluginName]['enabled'] = false;
201
-            }            
202
-            return $this->saveEnabledPlugins();
203
-        }
204
-        // Check if plugin is loaded / exists
205
-        if ( ! isset($this->pluginsList[$pluginName]) || 
206
-                $this->pluginsList[$pluginName]['object'] === null)
207
-        {
208
-            try {
209
-                $this->registerPlugin($pluginName);
210
-            } catch (Exception $e) {
211
-                $this->logClass->log('Cannot enable plugin : ' . $e->getMessage(),WARN);
212
-                return false;
213
-            }
214
-        }
215
-        $this->pluginsList[$pluginName]['enabled'] = true;
216
-        // save in DB and return 
217
-        return $this->saveEnabledPlugins();
218
-    }
187
+	/** Enable plugin (enabling an enabled plugin is OK, same for disabled).
188
+	 *  and save in DB config
189
+	 * @param string $pluginName
190
+	 * @param bool $enabled true to enable, false to disable
191
+	 * @return bool true if OK, or false (error logged)
192
+	 */
193
+	public function enablePlugin(string $pluginName,bool $enabled)
194
+	{
195
+		if ($enabled === false)
196
+		{
197
+			// If plugin is defined set to disable
198
+			if ( isset($this->pluginsList[$pluginName]))
199
+			{
200
+				$this->pluginsList[$pluginName]['enabled'] = false;
201
+			}            
202
+			return $this->saveEnabledPlugins();
203
+		}
204
+		// Check if plugin is loaded / exists
205
+		if ( ! isset($this->pluginsList[$pluginName]) || 
206
+				$this->pluginsList[$pluginName]['object'] === null)
207
+		{
208
+			try {
209
+				$this->registerPlugin($pluginName);
210
+			} catch (Exception $e) {
211
+				$this->logClass->log('Cannot enable plugin : ' . $e->getMessage(),WARN);
212
+				return false;
213
+			}
214
+		}
215
+		$this->pluginsList[$pluginName]['enabled'] = true;
216
+		// save in DB and return 
217
+		return $this->saveEnabledPlugins();
218
+	}
219 219
    
220
-    /**
221
-     * Destroy plugin objects and reload them with new enabled list.
222
-     * TODO : Code this function (ref DAEMON_MODE)
223
-     */
224
-    public function reloadAllPlugins()
225
-    {
226
-        return;
227
-    }
220
+	/**
221
+	 * Destroy plugin objects and reload them with new enabled list.
222
+	 * TODO : Code this function (ref DAEMON_MODE)
223
+	 */
224
+	public function reloadAllPlugins()
225
+	{
226
+		return;
227
+	}
228 228
  
229
-    /** Load plugin by name. Create entry if not in $pluginsList
230
-     * @param string $pluginName Plugin name to load
231
-     * @return bool true if created, false if already loaded
232
-     * @throws Exception on error loading plugin
233
-     */
234
-    public function registerPlugin(string $pluginName)
235
-    {
236
-        if ( ! isset($this->pluginsList[$pluginName]) ) // Plugin isn't enable, create entry
237
-        {
238
-            $pluginListElmt = array();
239
-            $pluginListElmt['object'] = null; // class not loaded
240
-            $pluginListElmt['enabled'] = false;
241
-            $this->pluginsList[$pluginName] = $pluginListElmt;
242
-        }
229
+	/** Load plugin by name. Create entry if not in $pluginsList
230
+	 * @param string $pluginName Plugin name to load
231
+	 * @return bool true if created, false if already loaded
232
+	 * @throws Exception on error loading plugin
233
+	 */
234
+	public function registerPlugin(string $pluginName)
235
+	{
236
+		if ( ! isset($this->pluginsList[$pluginName]) ) // Plugin isn't enable, create entry
237
+		{
238
+			$pluginListElmt = array();
239
+			$pluginListElmt['object'] = null; // class not loaded
240
+			$pluginListElmt['enabled'] = false;
241
+			$this->pluginsList[$pluginName] = $pluginListElmt;
242
+		}
243 243
         
244
-        if ($this->pluginsList[$pluginName]['object'] !== null)
245
-        {
246
-            return false;
247
-        }
248
-        try {
249
-            // Include plugin file
250
-            include_once($this->pluginDir.'/' . $pluginName . '.php');
244
+		if ($this->pluginsList[$pluginName]['object'] !== null)
245
+		{
246
+			return false;
247
+		}
248
+		try {
249
+			// Include plugin file
250
+			include_once($this->pluginDir.'/' . $pluginName . '.php');
251 251
             
252
-            // Create full class name with namespace
253
-            $pluginClassName = __NAMESPACE__ . '\\Plugins\\' . $pluginName;
252
+			// Create full class name with namespace
253
+			$pluginClassName = __NAMESPACE__ . '\\Plugins\\' . $pluginName;
254 254
             
255
-            // Create class
256
-            $newClass = new $pluginClassName();
255
+			// Create class
256
+			$newClass = new $pluginClassName();
257 257
             
258
-            // Set logging
259
-            $newClass->setLoggingClass($this->logClass);
258
+			// Set logging
259
+			$newClass->setLoggingClass($this->logClass);
260 260
             
261
-            // Add in plugin array
262
-            $this->pluginsList[$pluginName]['object']=$newClass;
263
-            $this->pluginsList[$pluginName]['allOID']=$newClass->catchAllTraps;
264
-            $this->pluginsList[$pluginName]['target']=$newClass->processTraps;
261
+			// Add in plugin array
262
+			$this->pluginsList[$pluginName]['object']=$newClass;
263
+			$this->pluginsList[$pluginName]['allOID']=$newClass->catchAllTraps;
264
+			$this->pluginsList[$pluginName]['target']=$newClass->processTraps;
265 265
             
266
-            // Delete old functions
267
-            foreach ($this->functionList as $fname => $fvalue)
268
-            {
269
-                if ($fvalue['plugin'] == $pluginName)
270
-                {
271
-                    unset($this->functionList[$fname]);
272
-                }
273
-            }
274
-            // Add functions
275
-            foreach ($newClass->functions as $fname => $function)
276
-            {
277
-                if (isset($this->functionList[$fname]))
278
-                {
279
-                    if ($this->functionList[$fname]['plugin'] != $pluginName )
280
-                    {
281
-                        throw new Exception('Duplicate function name '.$fname . ' in ' 
282
-                            . $pluginName . ' and ' . $this->functionList[$fname]['plugin']);
283
-                    }
266
+			// Delete old functions
267
+			foreach ($this->functionList as $fname => $fvalue)
268
+			{
269
+				if ($fvalue['plugin'] == $pluginName)
270
+				{
271
+					unset($this->functionList[$fname]);
272
+				}
273
+			}
274
+			// Add functions
275
+			foreach ($newClass->functions as $fname => $function)
276
+			{
277
+				if (isset($this->functionList[$fname]))
278
+				{
279
+					if ($this->functionList[$fname]['plugin'] != $pluginName )
280
+					{
281
+						throw new Exception('Duplicate function name '.$fname . ' in ' 
282
+							. $pluginName . ' and ' . $this->functionList[$fname]['plugin']);
283
+					}
284 284
                     
285
-                }
286
-                else
287
-                {
288
-                    $this->functionList[$fname]=array();
289
-                    $this->functionList[$fname]['plugin'] = $pluginName;
290
-                }
291
-                $this->functionList[$fname]['function']=$function['function'];
292
-            }
293
-            $this->logClass->log('Registered plugin '.$pluginName,DEBUG);
285
+				}
286
+				else
287
+				{
288
+					$this->functionList[$fname]=array();
289
+					$this->functionList[$fname]['plugin'] = $pluginName;
290
+				}
291
+				$this->functionList[$fname]['function']=$function['function'];
292
+			}
293
+			$this->logClass->log('Registered plugin '.$pluginName,DEBUG);
294 294
             
295
-        } catch (Exception $e) {
296
-            unset($this->pluginsList[$pluginName]);
297
-            $errorMessage = "Error registering plugin $pluginName : ".$e->getMessage();
298
-            $this->logClass->log($errorMessage,WARN);
299
-            // Disable the plugin
300
-            $this->enablePlugin($pluginName, false);
301
-            throw new \Exception($errorMessage);
302
-        } catch (Throwable $t) {
303
-            unset($this->pluginsList[$pluginName]);
304
-            $errorMessage = $t->getMessage() . ' in file ' . $t->getFile() . ' line ' . $t->getLine();
305
-            $this->logClass->log($errorMessage,WARN);
306
-            // Disable the plugin
307
-            $this->enablePlugin($pluginName, false);
308
-            throw new \Exception($errorMessage);
309
-        }
310
-        return true;
311
-    }
295
+		} catch (Exception $e) {
296
+			unset($this->pluginsList[$pluginName]);
297
+			$errorMessage = "Error registering plugin $pluginName : ".$e->getMessage();
298
+			$this->logClass->log($errorMessage,WARN);
299
+			// Disable the plugin
300
+			$this->enablePlugin($pluginName, false);
301
+			throw new \Exception($errorMessage);
302
+		} catch (Throwable $t) {
303
+			unset($this->pluginsList[$pluginName]);
304
+			$errorMessage = $t->getMessage() . ' in file ' . $t->getFile() . ' line ' . $t->getLine();
305
+			$this->logClass->log($errorMessage,WARN);
306
+			// Disable the plugin
307
+			$this->enablePlugin($pluginName, false);
308
+			throw new \Exception($errorMessage);
309
+		}
310
+		return true;
311
+	}
312 312
     
313
-    /** Registers all plugins (check=false) or only those with name present in array (check=true)
314
-     * @param bool $checkEnabled Check if plugin is enabled before loading it
315
-     * @return string Errors encountered while registering plugins
316
-     */
317
-    public function registerAllPlugins(bool $checkEnabled=true)
318
-    {
319
-        $retDisplay='';
320
-        // First load enabled plugins
321
-        foreach (array_keys($this->pluginsList) as $pluginName)
322
-        {
323
-            try {
324
-                $this->registerPlugin($pluginName);
325
-            } catch (Exception $e) {
326
-                $retDisplay .= $e->getMessage() . ' / ';
327
-            }
328
-        }
329
-        if ($checkEnabled === false) // Load all php files in plugin dir
330
-        {
331
-            foreach (glob($this->pluginDir."/*.php") as $filename)
332
-            {             
333
-                $pluginName=basename($filename,'.php');
334
-                if (!preg_match('/^[a-zA-Z0-9]+$/',$pluginName))
335
-                {
336
-                    $this->logClass->log("Invalid plugin name : ".$pluginName, WARN);
337
-                    $retDisplay .= "Invalid plugin name : ".$pluginName . " / ";
338
-                    break;
339
-                }
340
-                try { // Already registerd plugin will simply return false
341
-                    $this->registerPlugin($pluginName);               
342
-                } catch (Exception $e) {
343
-                    $retDisplay .= $e->getMessage() . ' / ';
344
-                }
345
-            }
346
-        }
313
+	/** Registers all plugins (check=false) or only those with name present in array (check=true)
314
+	 * @param bool $checkEnabled Check if plugin is enabled before loading it
315
+	 * @return string Errors encountered while registering plugins
316
+	 */
317
+	public function registerAllPlugins(bool $checkEnabled=true)
318
+	{
319
+		$retDisplay='';
320
+		// First load enabled plugins
321
+		foreach (array_keys($this->pluginsList) as $pluginName)
322
+		{
323
+			try {
324
+				$this->registerPlugin($pluginName);
325
+			} catch (Exception $e) {
326
+				$retDisplay .= $e->getMessage() . ' / ';
327
+			}
328
+		}
329
+		if ($checkEnabled === false) // Load all php files in plugin dir
330
+		{
331
+			foreach (glob($this->pluginDir."/*.php") as $filename)
332
+			{             
333
+				$pluginName=basename($filename,'.php');
334
+				if (!preg_match('/^[a-zA-Z0-9]+$/',$pluginName))
335
+				{
336
+					$this->logClass->log("Invalid plugin name : ".$pluginName, WARN);
337
+					$retDisplay .= "Invalid plugin name : ".$pluginName . " / ";
338
+					break;
339
+				}
340
+				try { // Already registerd plugin will simply return false
341
+					$this->registerPlugin($pluginName);               
342
+				} catch (Exception $e) {
343
+					$retDisplay .= $e->getMessage() . ' / ';
344
+				}
345
+			}
346
+		}
347 347
         
348
-        if ($retDisplay == '')
349
-        {
350
-            return 'All plugins loaded OK';
351
-        }
352
-        else
353
-        {
354
-            return $retDisplay;
355
-        }
356
-    }
348
+		if ($retDisplay == '')
349
+		{
350
+			return 'All plugins loaded OK';
351
+		}
352
+		else
353
+		{
354
+			return $retDisplay;
355
+		}
356
+	}
357 357
     
358
-    /**
359
-     * Returns array of name of loaded plugins
360
-     * @return array
361
-     */
362
-    public function pluginList() : array
363
-    {
364
-        return array_keys($this->pluginsList);    
365
-    }
358
+	/**
359
+	 * Returns array of name of loaded plugins
360
+	 * @return array
361
+	 */
362
+	public function pluginList() : array
363
+	{
364
+		return array_keys($this->pluginsList);    
365
+	}
366 366
 
367
-    /**
368
-     * Get plugin details
369
-     * @param string $name name of plugins
370
-     * @return boolean|stdClass result as stdClass or false if plugin not found.
371
-     * @throws \Exception if registering is not possible
372
-     */
373
-    public function pluginDetails(string $name)
374
-    {
375
-        if (!array_key_exists($name, $this->pluginsList))
376
-        {
377
-            return false;
378
-        }
379
-        if ($this->pluginsList[$name]['object'] === null)
380
-        {
381
-            $this->registerPlugin($name); // can throw exception handled by caller
382
-        }
383
-        $retObj = new stdClass();
384
-        $retObj->name           = $name;
385
-        $retObj->catchAllTraps  = $this->pluginsList[$name]['allOID'];
386
-        $retObj->processTraps   = $this->pluginsList[$name]['target'];
387
-        $retObj->description    = $this->pluginsList[$name]['object']->description;
388
-        $functions=array();
389
-        foreach ($this->functionList as $fName => $func)
390
-        {
391
-            if ($func['plugin'] == $name)
392
-            {
393
-                array_push($functions,$fName);
394
-            }
395
-        }
396
-        $retObj->funcArray=$functions;
397
-        return $retObj;
398
-    }
367
+	/**
368
+	 * Get plugin details
369
+	 * @param string $name name of plugins
370
+	 * @return boolean|stdClass result as stdClass or false if plugin not found.
371
+	 * @throws \Exception if registering is not possible
372
+	 */
373
+	public function pluginDetails(string $name)
374
+	{
375
+		if (!array_key_exists($name, $this->pluginsList))
376
+		{
377
+			return false;
378
+		}
379
+		if ($this->pluginsList[$name]['object'] === null)
380
+		{
381
+			$this->registerPlugin($name); // can throw exception handled by caller
382
+		}
383
+		$retObj = new stdClass();
384
+		$retObj->name           = $name;
385
+		$retObj->catchAllTraps  = $this->pluginsList[$name]['allOID'];
386
+		$retObj->processTraps   = $this->pluginsList[$name]['target'];
387
+		$retObj->description    = $this->pluginsList[$name]['object']->description;
388
+		$functions=array();
389
+		foreach ($this->functionList as $fName => $func)
390
+		{
391
+			if ($func['plugin'] == $name)
392
+			{
393
+				array_push($functions,$fName);
394
+			}
395
+		}
396
+		$retObj->funcArray=$functions;
397
+		return $retObj;
398
+	}
399 399
        
400
-    /**
401
-     * Get plugin name from function name
402
-     * @param string $funcName
403
-     * @param string $pluginName
404
-     * @return boolean returns plugin object of false;
405
-     */
406
-    public function getFunction($funcName,&$pluginName)
407
-    {
408
-        if (! isset($this->functionList[$funcName]) )
409
-        {
410
-            return false;
411
-        }
412
-        $pluginName = $this->functionList[$funcName]['plugin'];
413
-        return true;
414
-    }
400
+	/**
401
+	 * Get plugin name from function name
402
+	 * @param string $funcName
403
+	 * @param string $pluginName
404
+	 * @return boolean returns plugin object of false;
405
+	 */
406
+	public function getFunction($funcName,&$pluginName)
407
+	{
408
+		if (! isset($this->functionList[$funcName]) )
409
+		{
410
+			return false;
411
+		}
412
+		$pluginName = $this->functionList[$funcName]['plugin'];
413
+		return true;
414
+	}
415 415
     
416
-    /**
417
-     * Get functions params and description
418
-     * @param string $funcName
419
-     * @return boolean|stdClass false if not found or object (name,params,description)
420
-     * @throws \Exception if registering is not possible
421
-     */
422
-    public function getFunctionDetails($funcName)
423
-    {
424
-        if (! isset($this->functionList[$funcName]) )
425
-        {
426
-            return false;
427
-        }
428
-        $pluginName = $this->functionList[$funcName]['plugin']; // plugin name
429
-        $plugin = $this->pluginsList[$pluginName]['object']; // plugin object
430
-        if ($plugin === null)
431
-        {
432
-            $this->registerPlugin($pluginName); // can throw exception handled by caller
433
-        }
434
-        $retObj = new stdClass();
435
-        $retObj->name           = $funcName;
436
-        $retObj->plugin         = $pluginName;
437
-        $retObj->params         = $plugin->functions[$funcName]['params'];
438
-        $retObj->description    = $plugin->functions[$funcName]['description'];
439
-        return $retObj;
440
-    }
416
+	/**
417
+	 * Get functions params and description
418
+	 * @param string $funcName
419
+	 * @return boolean|stdClass false if not found or object (name,params,description)
420
+	 * @throws \Exception if registering is not possible
421
+	 */
422
+	public function getFunctionDetails($funcName)
423
+	{
424
+		if (! isset($this->functionList[$funcName]) )
425
+		{
426
+			return false;
427
+		}
428
+		$pluginName = $this->functionList[$funcName]['plugin']; // plugin name
429
+		$plugin = $this->pluginsList[$pluginName]['object']; // plugin object
430
+		if ($plugin === null)
431
+		{
432
+			$this->registerPlugin($pluginName); // can throw exception handled by caller
433
+		}
434
+		$retObj = new stdClass();
435
+		$retObj->name           = $funcName;
436
+		$retObj->plugin         = $pluginName;
437
+		$retObj->params         = $plugin->functions[$funcName]['params'];
438
+		$retObj->description    = $plugin->functions[$funcName]['description'];
439
+		return $retObj;
440
+	}
441 441
     
442
-    /**
443
-     * Evaluate function with parameters
444
-     * @param string $funcName
445
-     * @param mixed $params
446
-     * @throws Exception
447
-     * @return bool
448
-     */
449
-    public function getFunctionEval(string $funcName,$params) : bool
450
-    {
451
-        if (! isset($this->functionList[$funcName]) )
452
-        {
453
-            throw new Exception($funcName . ' not found.');
454
-        }
455
-        $pluginName = $this->functionList[$funcName]['plugin']; // plugin name
456
-        $plugin = $this->pluginsList[$pluginName]['object']; // plugin object
442
+	/**
443
+	 * Evaluate function with parameters
444
+	 * @param string $funcName
445
+	 * @param mixed $params
446
+	 * @throws Exception
447
+	 * @return bool
448
+	 */
449
+	public function getFunctionEval(string $funcName,$params) : bool
450
+	{
451
+		if (! isset($this->functionList[$funcName]) )
452
+		{
453
+			throw new Exception($funcName . ' not found.');
454
+		}
455
+		$pluginName = $this->functionList[$funcName]['plugin']; // plugin name
456
+		$plugin = $this->pluginsList[$pluginName]['object']; // plugin object
457 457
 
458
-        if ($plugin === null)
459
-        {
460
-            $this->registerPlugin($pluginName); // can throw exception handled by caller
461
-            $plugin = $this->pluginsList[$pluginName]['object'];
462
-        }
458
+		if ($plugin === null)
459
+		{
460
+			$this->registerPlugin($pluginName); // can throw exception handled by caller
461
+			$plugin = $this->pluginsList[$pluginName]['object'];
462
+		}
463 463
         
464
-        $propertyName = $this->functionList[$funcName]['function'];
465
-        $this->logClass->log('Using property '. $propertyName . ' of class : '.$pluginName,DEBUG);
464
+		$propertyName = $this->functionList[$funcName]['function'];
465
+		$this->logClass->log('Using property '. $propertyName . ' of class : '.$pluginName,DEBUG);
466 466
         
467
-        return $plugin->{$propertyName}($params);        
468
-    }
467
+		return $plugin->{$propertyName}($params);        
468
+	}
469 469
     
470
-    public function evaluateFunctionString(string $functionString) : bool
471
-    {
472
-        $matches=array();
473
-        // Cleanup spaces
474
-        $functionString = $this->trapClass->ruleClass->eval_cleanup($functionString);
475
-        $this->logClass->log('eval cleanup : '.$functionString,DEBUG);
470
+	public function evaluateFunctionString(string $functionString) : bool
471
+	{
472
+		$matches=array();
473
+		// Cleanup spaces
474
+		$functionString = $this->trapClass->ruleClass->eval_cleanup($functionString);
475
+		$this->logClass->log('eval cleanup : '.$functionString,DEBUG);
476 476
         
477
-        // Match function call
478
-        $num=preg_match('/^__([a-zA-Z0-9]+)\((.+)\)$/', $functionString , $matches);
479
-        if ($num !=1)
480
-        {
481
-            throw new \ErrorException('Function syntax error : ' . $functionString );
482
-        }
483
-        $this->logClass->log('Got function : '. $matches[1] . ', params : '.$matches[2],DEBUG);
484
-        $funcName=$matches[1];
477
+		// Match function call
478
+		$num=preg_match('/^__([a-zA-Z0-9]+)\((.+)\)$/', $functionString , $matches);
479
+		if ($num !=1)
480
+		{
481
+			throw new \ErrorException('Function syntax error : ' . $functionString );
482
+		}
483
+		$this->logClass->log('Got function : '. $matches[1] . ', params : '.$matches[2],DEBUG);
484
+		$funcName=$matches[1];
485 485
         
486
-        // Get parameters comma separated
487
-        $funcParams=str_getcsv($matches[2],',','"',"\\");
488
-        $this->logClass->log('Function params : ' . print_r($funcParams,true),DEBUG);
486
+		// Get parameters comma separated
487
+		$funcParams=str_getcsv($matches[2],',','"',"\\");
488
+		$this->logClass->log('Function params : ' . print_r($funcParams,true),DEBUG);
489 489
         
490
-        // return evaluation
491
-        return $this->getFunctionEval($funcName, $funcParams);        
490
+		// return evaluation
491
+		return $this->getFunctionEval($funcName, $funcParams);        
492 492
         
493
-    }
493
+	}
494 494
     
495 495
 }
496 496
 
497 497
 abstract class PluginTemplate
498 498
 {
499 499
     
500
-    /** @var Logging $loggingClass */
501
-    private $loggingClass;
500
+	/** @var Logging $loggingClass */
501
+	private $loggingClass;
502 502
     
503
-    /** @var string $name Name of plugin */
504
-    public $name;
503
+	/** @var string $name Name of plugin */
504
+	public $name;
505 505
     
506
-    /** @var string $description Description of plugin */
507
-    public $description='Default plugin description';
506
+	/** @var string $description Description of plugin */
507
+	public $description='Default plugin description';
508 508
     
509
-    /** @var array[string] $functions Functions of this plugin for rule eval*/
510
-    public $functions=array();
509
+	/** @var array[string] $functions Functions of this plugin for rule eval*/
510
+	public $functions=array();
511 511
     
512
-    /** @var boolean $catchAllTraps Set to true if all traps will be sent to the plugin */
513
-    public $catchAllTraps=false;
512
+	/** @var boolean $catchAllTraps Set to true if all traps will be sent to the plugin */
513
+	public $catchAllTraps=false;
514 514
     
515
-    /** @var boolean $processTraps Set to true if plugins can handle traps */
516
-    public $processTraps=false;
515
+	/** @var boolean $processTraps Set to true if plugins can handle traps */
516
+	public $processTraps=false;
517 517
     
518
-    /**
519
-     * @param \Trapdirector\Logging $loggingClass
520
-     */
521
-    public function setLoggingClass($loggingClass)
522
-    {
523
-        $this->loggingClass = $loggingClass;
524
-    }
518
+	/**
519
+	 * @param \Trapdirector\Logging $loggingClass
520
+	 */
521
+	public function setLoggingClass($loggingClass)
522
+	{
523
+		$this->loggingClass = $loggingClass;
524
+	}
525 525
     
526
-    /**
527
-     * 
528
-     * @param string $message
529
-     * @param int $level DEBUG/INFO/WARN/CRIT
530
-     */
531
-    public function log($message,$level)
532
-    {
533
-        $this->loggingClass->log('[ '.get_class($this).'] '. $message, $level);
534
-    }
526
+	/**
527
+	 * 
528
+	 * @param string $message
529
+	 * @param int $level DEBUG/INFO/WARN/CRIT
530
+	 */
531
+	public function log($message,$level)
532
+	{
533
+		$this->loggingClass->log('[ '.get_class($this).'] '. $message, $level);
534
+	}
535 535
 }
536 536
\ 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
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
      * $pluginsList[plugin name]['target']  : bool true if plugin can be trap processing target
25 25
      * $pluginsList[plugin name]['enabled'] : bool true if plugin is in enabled list 
26 26
      **/
27
-    protected $pluginsList = array();
27
+    protected $pluginsList=array();
28 28
 
29 29
     /** Array of functions names
30 30
      * @var array $functionList 
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
      * @param string $plugin_dir optional plugin directory
52 52
      * @throws \Exception
53 53
      */
54
-    function __construct(Trap $trapClass,string $pluginDir='')
54
+    function __construct(Trap $trapClass, string $pluginDir='')
55 55
     {
56 56
         if ($pluginDir == '')
57 57
         {
@@ -88,42 +88,42 @@  discard block
 block discarded – undo
88 88
      */
89 89
     private function loadEnabledPlugins()
90 90
     {
91
-        $PluginList = $this->trapClass->trapsDB->getDBConfig('enabled_plugins');
91
+        $PluginList=$this->trapClass->trapsDB->getDBConfig('enabled_plugins');
92 92
                
93 93
         if ($PluginList === null || $PluginList == '')
94 94
         {
95
-            $this->logClass->log('No enabled plugins',DEBUG);
95
+            $this->logClass->log('No enabled plugins', DEBUG);
96 96
             return;
97 97
         }
98 98
         else
99 99
         {   // Saved config : <plugin name>;<Catch all OID ? 1|0>;<Trap target ? 1|0>;<func 1 name>|<func 2 name>... ,<plugin2 name>....
100
-            $this->logClass->log('Enabled plugins = '.$PluginList,DEBUG);
100
+            $this->logClass->log('Enabled plugins = '.$PluginList, DEBUG);
101 101
             
102
-            $pluginArray = explode(',', $PluginList);
102
+            $pluginArray=explode(',', $PluginList);
103 103
             foreach ($pluginArray as $pluginElmt)
104 104
             {
105
-                $pluginElmt = explode(';',$pluginElmt);
105
+                $pluginElmt=explode(';', $pluginElmt);
106 106
                 if ($pluginElmt === false || count($pluginElmt) != 4)
107 107
                 {
108
-                    throw new \Exception('Invalid plugin configuration : '. $PluginList );
108
+                    throw new \Exception('Invalid plugin configuration : '.$PluginList);
109 109
                 }
110 110
                 $pluginName=$pluginElmt[0];
111 111
                 
112
-                $pluginListElmt = array();
113
-                $pluginListElmt['object'] = null; // class not loaded
114
-                $pluginListElmt['allOID'] = ($pluginElmt[1]=='1') ? true : false;
115
-                $pluginListElmt['target'] = ($pluginElmt[2]=='1') ? true : false;
116
-                $pluginListElmt['enabled'] = true;
112
+                $pluginListElmt=array();
113
+                $pluginListElmt['object']=null; // class not loaded
114
+                $pluginListElmt['allOID']=($pluginElmt[1] == '1') ? true : false;
115
+                $pluginListElmt['target']=($pluginElmt[2] == '1') ? true : false;
116
+                $pluginListElmt['enabled']=true;
117 117
                 
118
-                $this->pluginsList[$pluginName] = $pluginListElmt;
118
+                $this->pluginsList[$pluginName]=$pluginListElmt;
119 119
                 
120 120
                 // deal with plugin functions
121
-                $pluginFunctions = explode('|',$pluginElmt[3]);
121
+                $pluginFunctions=explode('|', $pluginElmt[3]);
122 122
                 if ($pluginFunctions !== false)
123 123
                 {
124 124
                     foreach ($pluginFunctions as $function)
125 125
                     {
126
-                        $this->functionList[$function] = array(
126
+                        $this->functionList[$function]=array(
127 127
                             'plugin'    =>   $pluginName,
128 128
                             'function'  =>  null
129 129
                         );
@@ -155,16 +155,16 @@  discard block
 block discarded – undo
155 155
                 {
156 156
                     continue;
157 157
                 }
158
-                $functionString .= ($functionString == '') ? '' : '|'; // add separator if not empty
159
-                $functionString .= $fName;
158
+                $functionString.=($functionString == '') ? '' : '|'; // add separator if not empty
159
+                $functionString.=$fName;
160 160
             }
161
-            $saveString .= ($saveString == '')?'':',' ;
161
+            $saveString.=($saveString == '') ? '' : ',';
162 162
             
163
-            $allOID = ($value['allOID'] === true) ? 1 : 0;
164
-            $target = ($value['target'] === true) ? 1 : 0;
165
-            $saveString .= $name . ';' . $allOID . ';' . $target . ';' . $functionString ;
163
+            $allOID=($value['allOID'] === true) ? 1 : 0;
164
+            $target=($value['target'] === true) ? 1 : 0;
165
+            $saveString.=$name.';'.$allOID.';'.$target.';'.$functionString;
166 166
         }
167
-        $this->logClass->log('Saving : ' . $saveString,DEBUG);
167
+        $this->logClass->log('Saving : '.$saveString, DEBUG);
168 168
         return $this->trapClass->trapsDB->setDBConfig('enabled_plugins', $saveString);
169 169
     }
170 170
     
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
         {
179 179
             if ($value['enabled'] == true)
180 180
             {
181
-                array_push($retArray,$name);
181
+                array_push($retArray, $name);
182 182
             }
183 183
         }
184 184
         return $retArray;
@@ -190,29 +190,29 @@  discard block
 block discarded – undo
190 190
      * @param bool $enabled true to enable, false to disable
191 191
      * @return bool true if OK, or false (error logged)
192 192
      */
193
-    public function enablePlugin(string $pluginName,bool $enabled)
193
+    public function enablePlugin(string $pluginName, bool $enabled)
194 194
     {
195 195
         if ($enabled === false)
196 196
         {
197 197
             // If plugin is defined set to disable
198
-            if ( isset($this->pluginsList[$pluginName]))
198
+            if (isset($this->pluginsList[$pluginName]))
199 199
             {
200
-                $this->pluginsList[$pluginName]['enabled'] = false;
200
+                $this->pluginsList[$pluginName]['enabled']=false;
201 201
             }            
202 202
             return $this->saveEnabledPlugins();
203 203
         }
204 204
         // Check if plugin is loaded / exists
205
-        if ( ! isset($this->pluginsList[$pluginName]) || 
205
+        if (!isset($this->pluginsList[$pluginName]) || 
206 206
                 $this->pluginsList[$pluginName]['object'] === null)
207 207
         {
208 208
             try {
209 209
                 $this->registerPlugin($pluginName);
210 210
             } catch (Exception $e) {
211
-                $this->logClass->log('Cannot enable plugin : ' . $e->getMessage(),WARN);
211
+                $this->logClass->log('Cannot enable plugin : '.$e->getMessage(), WARN);
212 212
                 return false;
213 213
             }
214 214
         }
215
-        $this->pluginsList[$pluginName]['enabled'] = true;
215
+        $this->pluginsList[$pluginName]['enabled']=true;
216 216
         // save in DB and return 
217 217
         return $this->saveEnabledPlugins();
218 218
     }
@@ -233,12 +233,12 @@  discard block
 block discarded – undo
233 233
      */
234 234
     public function registerPlugin(string $pluginName)
235 235
     {
236
-        if ( ! isset($this->pluginsList[$pluginName]) ) // Plugin isn't enable, create entry
236
+        if (!isset($this->pluginsList[$pluginName])) // Plugin isn't enable, create entry
237 237
         {
238
-            $pluginListElmt = array();
239
-            $pluginListElmt['object'] = null; // class not loaded
240
-            $pluginListElmt['enabled'] = false;
241
-            $this->pluginsList[$pluginName] = $pluginListElmt;
238
+            $pluginListElmt=array();
239
+            $pluginListElmt['object']=null; // class not loaded
240
+            $pluginListElmt['enabled']=false;
241
+            $this->pluginsList[$pluginName]=$pluginListElmt;
242 242
         }
243 243
         
244 244
         if ($this->pluginsList[$pluginName]['object'] !== null)
@@ -247,13 +247,13 @@  discard block
 block discarded – undo
247 247
         }
248 248
         try {
249 249
             // Include plugin file
250
-            include_once($this->pluginDir.'/' . $pluginName . '.php');
250
+            include_once($this->pluginDir.'/'.$pluginName.'.php');
251 251
             
252 252
             // Create full class name with namespace
253
-            $pluginClassName = __NAMESPACE__ . '\\Plugins\\' . $pluginName;
253
+            $pluginClassName=__NAMESPACE__.'\\Plugins\\'.$pluginName;
254 254
             
255 255
             // Create class
256
-            $newClass = new $pluginClassName();
256
+            $newClass=new $pluginClassName();
257 257
             
258 258
             // Set logging
259 259
             $newClass->setLoggingClass($this->logClass);
@@ -276,33 +276,33 @@  discard block
 block discarded – undo
276 276
             {
277 277
                 if (isset($this->functionList[$fname]))
278 278
                 {
279
-                    if ($this->functionList[$fname]['plugin'] != $pluginName )
279
+                    if ($this->functionList[$fname]['plugin'] != $pluginName)
280 280
                     {
281
-                        throw new Exception('Duplicate function name '.$fname . ' in ' 
282
-                            . $pluginName . ' and ' . $this->functionList[$fname]['plugin']);
281
+                        throw new Exception('Duplicate function name '.$fname.' in ' 
282
+                            . $pluginName.' and '.$this->functionList[$fname]['plugin']);
283 283
                     }
284 284
                     
285 285
                 }
286 286
                 else
287 287
                 {
288 288
                     $this->functionList[$fname]=array();
289
-                    $this->functionList[$fname]['plugin'] = $pluginName;
289
+                    $this->functionList[$fname]['plugin']=$pluginName;
290 290
                 }
291 291
                 $this->functionList[$fname]['function']=$function['function'];
292 292
             }
293
-            $this->logClass->log('Registered plugin '.$pluginName,DEBUG);
293
+            $this->logClass->log('Registered plugin '.$pluginName, DEBUG);
294 294
             
295 295
         } catch (Exception $e) {
296 296
             unset($this->pluginsList[$pluginName]);
297
-            $errorMessage = "Error registering plugin $pluginName : ".$e->getMessage();
298
-            $this->logClass->log($errorMessage,WARN);
297
+            $errorMessage="Error registering plugin $pluginName : ".$e->getMessage();
298
+            $this->logClass->log($errorMessage, WARN);
299 299
             // Disable the plugin
300 300
             $this->enablePlugin($pluginName, false);
301 301
             throw new \Exception($errorMessage);
302 302
         } catch (Throwable $t) {
303 303
             unset($this->pluginsList[$pluginName]);
304
-            $errorMessage = $t->getMessage() . ' in file ' . $t->getFile() . ' line ' . $t->getLine();
305
-            $this->logClass->log($errorMessage,WARN);
304
+            $errorMessage=$t->getMessage().' in file '.$t->getFile().' line '.$t->getLine();
305
+            $this->logClass->log($errorMessage, WARN);
306 306
             // Disable the plugin
307 307
             $this->enablePlugin($pluginName, false);
308 308
             throw new \Exception($errorMessage);
@@ -323,24 +323,24 @@  discard block
 block discarded – undo
323 323
             try {
324 324
                 $this->registerPlugin($pluginName);
325 325
             } catch (Exception $e) {
326
-                $retDisplay .= $e->getMessage() . ' / ';
326
+                $retDisplay.=$e->getMessage().' / ';
327 327
             }
328 328
         }
329 329
         if ($checkEnabled === false) // Load all php files in plugin dir
330 330
         {
331 331
             foreach (glob($this->pluginDir."/*.php") as $filename)
332 332
             {             
333
-                $pluginName=basename($filename,'.php');
334
-                if (!preg_match('/^[a-zA-Z0-9]+$/',$pluginName))
333
+                $pluginName=basename($filename, '.php');
334
+                if (!preg_match('/^[a-zA-Z0-9]+$/', $pluginName))
335 335
                 {
336 336
                     $this->logClass->log("Invalid plugin name : ".$pluginName, WARN);
337
-                    $retDisplay .= "Invalid plugin name : ".$pluginName . " / ";
337
+                    $retDisplay.="Invalid plugin name : ".$pluginName." / ";
338 338
                     break;
339 339
                 }
340 340
                 try { // Already registerd plugin will simply return false
341 341
                     $this->registerPlugin($pluginName);               
342 342
                 } catch (Exception $e) {
343
-                    $retDisplay .= $e->getMessage() . ' / ';
343
+                    $retDisplay.=$e->getMessage().' / ';
344 344
                 }
345 345
             }
346 346
         }
@@ -380,17 +380,17 @@  discard block
 block discarded – undo
380 380
         {
381 381
             $this->registerPlugin($name); // can throw exception handled by caller
382 382
         }
383
-        $retObj = new stdClass();
384
-        $retObj->name           = $name;
385
-        $retObj->catchAllTraps  = $this->pluginsList[$name]['allOID'];
386
-        $retObj->processTraps   = $this->pluginsList[$name]['target'];
387
-        $retObj->description    = $this->pluginsList[$name]['object']->description;
383
+        $retObj=new stdClass();
384
+        $retObj->name=$name;
385
+        $retObj->catchAllTraps=$this->pluginsList[$name]['allOID'];
386
+        $retObj->processTraps=$this->pluginsList[$name]['target'];
387
+        $retObj->description=$this->pluginsList[$name]['object']->description;
388 388
         $functions=array();
389 389
         foreach ($this->functionList as $fName => $func)
390 390
         {
391 391
             if ($func['plugin'] == $name)
392 392
             {
393
-                array_push($functions,$fName);
393
+                array_push($functions, $fName);
394 394
             }
395 395
         }
396 396
         $retObj->funcArray=$functions;
@@ -403,13 +403,13 @@  discard block
 block discarded – undo
403 403
      * @param string $pluginName
404 404
      * @return boolean returns plugin object of false;
405 405
      */
406
-    public function getFunction($funcName,&$pluginName)
406
+    public function getFunction($funcName, &$pluginName)
407 407
     {
408
-        if (! isset($this->functionList[$funcName]) )
408
+        if (!isset($this->functionList[$funcName]))
409 409
         {
410 410
             return false;
411 411
         }
412
-        $pluginName = $this->functionList[$funcName]['plugin'];
412
+        $pluginName=$this->functionList[$funcName]['plugin'];
413 413
         return true;
414 414
     }
415 415
     
@@ -421,21 +421,21 @@  discard block
 block discarded – undo
421 421
      */
422 422
     public function getFunctionDetails($funcName)
423 423
     {
424
-        if (! isset($this->functionList[$funcName]) )
424
+        if (!isset($this->functionList[$funcName]))
425 425
         {
426 426
             return false;
427 427
         }
428
-        $pluginName = $this->functionList[$funcName]['plugin']; // plugin name
429
-        $plugin = $this->pluginsList[$pluginName]['object']; // plugin object
428
+        $pluginName=$this->functionList[$funcName]['plugin']; // plugin name
429
+        $plugin=$this->pluginsList[$pluginName]['object']; // plugin object
430 430
         if ($plugin === null)
431 431
         {
432 432
             $this->registerPlugin($pluginName); // can throw exception handled by caller
433 433
         }
434
-        $retObj = new stdClass();
435
-        $retObj->name           = $funcName;
436
-        $retObj->plugin         = $pluginName;
437
-        $retObj->params         = $plugin->functions[$funcName]['params'];
438
-        $retObj->description    = $plugin->functions[$funcName]['description'];
434
+        $retObj=new stdClass();
435
+        $retObj->name=$funcName;
436
+        $retObj->plugin=$pluginName;
437
+        $retObj->params=$plugin->functions[$funcName]['params'];
438
+        $retObj->description=$plugin->functions[$funcName]['description'];
439 439
         return $retObj;
440 440
     }
441 441
     
@@ -446,23 +446,23 @@  discard block
 block discarded – undo
446 446
      * @throws Exception
447 447
      * @return bool
448 448
      */
449
-    public function getFunctionEval(string $funcName,$params) : bool
449
+    public function getFunctionEval(string $funcName, $params) : bool
450 450
     {
451
-        if (! isset($this->functionList[$funcName]) )
451
+        if (!isset($this->functionList[$funcName]))
452 452
         {
453
-            throw new Exception($funcName . ' not found.');
453
+            throw new Exception($funcName.' not found.');
454 454
         }
455
-        $pluginName = $this->functionList[$funcName]['plugin']; // plugin name
456
-        $plugin = $this->pluginsList[$pluginName]['object']; // plugin object
455
+        $pluginName=$this->functionList[$funcName]['plugin']; // plugin name
456
+        $plugin=$this->pluginsList[$pluginName]['object']; // plugin object
457 457
 
458 458
         if ($plugin === null)
459 459
         {
460 460
             $this->registerPlugin($pluginName); // can throw exception handled by caller
461
-            $plugin = $this->pluginsList[$pluginName]['object'];
461
+            $plugin=$this->pluginsList[$pluginName]['object'];
462 462
         }
463 463
         
464
-        $propertyName = $this->functionList[$funcName]['function'];
465
-        $this->logClass->log('Using property '. $propertyName . ' of class : '.$pluginName,DEBUG);
464
+        $propertyName=$this->functionList[$funcName]['function'];
465
+        $this->logClass->log('Using property '.$propertyName.' of class : '.$pluginName, DEBUG);
466 466
         
467 467
         return $plugin->{$propertyName}($params);        
468 468
     }
@@ -471,21 +471,21 @@  discard block
 block discarded – undo
471 471
     {
472 472
         $matches=array();
473 473
         // Cleanup spaces
474
-        $functionString = $this->trapClass->ruleClass->eval_cleanup($functionString);
475
-        $this->logClass->log('eval cleanup : '.$functionString,DEBUG);
474
+        $functionString=$this->trapClass->ruleClass->eval_cleanup($functionString);
475
+        $this->logClass->log('eval cleanup : '.$functionString, DEBUG);
476 476
         
477 477
         // Match function call
478
-        $num=preg_match('/^__([a-zA-Z0-9]+)\((.+)\)$/', $functionString , $matches);
479
-        if ($num !=1)
478
+        $num=preg_match('/^__([a-zA-Z0-9]+)\((.+)\)$/', $functionString, $matches);
479
+        if ($num != 1)
480 480
         {
481
-            throw new \ErrorException('Function syntax error : ' . $functionString );
481
+            throw new \ErrorException('Function syntax error : '.$functionString);
482 482
         }
483
-        $this->logClass->log('Got function : '. $matches[1] . ', params : '.$matches[2],DEBUG);
483
+        $this->logClass->log('Got function : '.$matches[1].', params : '.$matches[2], DEBUG);
484 484
         $funcName=$matches[1];
485 485
         
486 486
         // Get parameters comma separated
487
-        $funcParams=str_getcsv($matches[2],',','"',"\\");
488
-        $this->logClass->log('Function params : ' . print_r($funcParams,true),DEBUG);
487
+        $funcParams=str_getcsv($matches[2], ',', '"', "\\");
488
+        $this->logClass->log('Function params : '.print_r($funcParams, true), DEBUG);
489 489
         
490 490
         // return evaluation
491 491
         return $this->getFunctionEval($funcName, $funcParams);        
@@ -520,7 +520,7 @@  discard block
 block discarded – undo
520 520
      */
521 521
     public function setLoggingClass($loggingClass)
522 522
     {
523
-        $this->loggingClass = $loggingClass;
523
+        $this->loggingClass=$loggingClass;
524 524
     }
525 525
     
526 526
     /**
@@ -528,8 +528,8 @@  discard block
 block discarded – undo
528 528
      * @param string $message
529 529
      * @param int $level DEBUG/INFO/WARN/CRIT
530 530
      */
531
-    public function log($message,$level)
531
+    public function log($message, $level)
532 532
     {
533
-        $this->loggingClass->log('[ '.get_class($this).'] '. $message, $level);
533
+        $this->loggingClass->log('[ '.get_class($this).'] '.$message, $level);
534 534
     }
535 535
 }
536 536
\ No newline at end of file
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Database.php 3 patches
Indentation   +347 added lines, -347 removed lines patch added patch discarded remove patch
@@ -9,383 +9,383 @@
 block discarded – undo
9 9
 class Database
10 10
 {
11 11
 
12
-    // Databases
13
-    /** @var \PDO $trapDB trap database */
14
-    protected $trapDB=null; 
15
-    protected $idoDB=null; //< ido database
16
-    public $trapDBType; //< Type of database for traps (mysql, pgsql)
17
-    public $idoDBType; //< Type of database for ido (mysql, pgsql)
12
+	// Databases
13
+	/** @var \PDO $trapDB trap database */
14
+	protected $trapDB=null; 
15
+	protected $idoDB=null; //< ido database
16
+	public $trapDBType; //< Type of database for traps (mysql, pgsql)
17
+	public $idoDBType; //< Type of database for ido (mysql, pgsql)
18 18
     
19
-    protected $trapDSN; //< trap database connection params
20
-    protected $trapUsername; //< trap database connection params
21
-    protected $trapPass; //< trap database connection params
22
-    public $dbPrefix; //< database tables prefix
19
+	protected $trapDSN; //< trap database connection params
20
+	protected $trapUsername; //< trap database connection params
21
+	protected $trapPass; //< trap database connection params
22
+	public $dbPrefix; //< database tables prefix
23 23
     
24
-    protected $idoSet; //< bool true is ido database set
25
-    protected $idoDSN; //< trap database connection params
26
-    protected $idoUsername; //< trap database connection params
27
-    protected $idoPass; //< trap database connection params
24
+	protected $idoSet; //< bool true is ido database set
25
+	protected $idoDSN; //< trap database connection params
26
+	protected $idoUsername; //< trap database connection params
27
+	protected $idoPass; //< trap database connection params
28 28
     
29
-    // Logging function
29
+	// Logging function
30 30
     
31
-    protected $logging; //< logging class
31
+	protected $logging; //< logging class
32 32
     
33
-    /**
34
-     * @param Logging $logClass : where to log
35
-     * @param array $dbParam : array of named params  type,host,dbname,username,[port],[password]
36
-     */
37
-    function __construct($logClass,$dbParam,$dbPrefix)
38
-    {
39
-        $this->logging=$logClass;
40
-        $this->dbPrefix=$dbPrefix;
33
+	/**
34
+	 * @param Logging $logClass : where to log
35
+	 * @param array $dbParam : array of named params  type,host,dbname,username,[port],[password]
36
+	 */
37
+	function __construct($logClass,$dbParam,$dbPrefix)
38
+	{
39
+		$this->logging=$logClass;
40
+		$this->dbPrefix=$dbPrefix;
41 41
         
42
-        $this->trapDSN=$this->setupDSN($dbParam);
43
-        $this->trapUsername = $dbParam['username'];
44
-        $this->trapPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
45
-        $this->trapDBType=$dbParam['db'];
46
-        $this->logging->log('DSN : '.$this->trapDSN. ';user '.$this->trapUsername.' / prefix : '. $this->dbPrefix,INFO);
47
-        $this->db_connect_trap();
42
+		$this->trapDSN=$this->setupDSN($dbParam);
43
+		$this->trapUsername = $dbParam['username'];
44
+		$this->trapPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
45
+		$this->trapDBType=$dbParam['db'];
46
+		$this->logging->log('DSN : '.$this->trapDSN. ';user '.$this->trapUsername.' / prefix : '. $this->dbPrefix,INFO);
47
+		$this->db_connect_trap();
48 48
         
49
-    }
49
+	}
50 50
     
51
-    /**
52
-     * Setup and connect to IDO database
53
-     * @param array $dbParam : array of named params
54
-     */
55
-    public function setupIDO($dbParam)
56
-    {
57
-        $this->idoDSN=$this->setupDSN($dbParam);
58
-        $this->idoUsername = $dbParam['username'];
59
-        $this->idoPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
60
-        $this->logging->log('DSN : '.$this->idoDSN. ';user '.$this->idoUsername,INFO);
61
-        $this->idoDBType=$dbParam['db'];
62
-        $this->db_connect_ido();
63
-    }
51
+	/**
52
+	 * Setup and connect to IDO database
53
+	 * @param array $dbParam : array of named params
54
+	 */
55
+	public function setupIDO($dbParam)
56
+	{
57
+		$this->idoDSN=$this->setupDSN($dbParam);
58
+		$this->idoUsername = $dbParam['username'];
59
+		$this->idoPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
60
+		$this->logging->log('DSN : '.$this->idoDSN. ';user '.$this->idoUsername,INFO);
61
+		$this->idoDBType=$dbParam['db'];
62
+		$this->db_connect_ido();
63
+	}
64 64
     
65
-    /**
66
-     * Connect to IDO database
67
-     * @return \PDO
68
-     */
69
-    public function db_connect_ido()
70
-    {
71
-        if ($this->idoDB != null) {
72
-            // Check if connection is still alive
73
-            try {
74
-                $this->idoDB->query('select 1')->fetchColumn();
75
-                return $this->idoDB;
76
-            } catch (Exception $e) {
77
-                // select 1 failed, try to reconnect.
78
-                $this->logging->log('Database IDO connection lost, reconnecting',WARN);
79
-            }
80
-        }
81
-        try {
82
-            $this->idoDB = new PDO($this->idoDSN,$this->idoUsername,$this->idoPass);
83
-        } catch (PDOException $e) {
84
-            $this->logging->log('Connection failed to IDO : ' . $e->getMessage(),ERROR,'');
85
-        }
86
-        return $this->idoDB;
87
-    }
65
+	/**
66
+	 * Connect to IDO database
67
+	 * @return \PDO
68
+	 */
69
+	public function db_connect_ido()
70
+	{
71
+		if ($this->idoDB != null) {
72
+			// Check if connection is still alive
73
+			try {
74
+				$this->idoDB->query('select 1')->fetchColumn();
75
+				return $this->idoDB;
76
+			} catch (Exception $e) {
77
+				// select 1 failed, try to reconnect.
78
+				$this->logging->log('Database IDO connection lost, reconnecting',WARN);
79
+			}
80
+		}
81
+		try {
82
+			$this->idoDB = new PDO($this->idoDSN,$this->idoUsername,$this->idoPass);
83
+		} catch (PDOException $e) {
84
+			$this->logging->log('Connection failed to IDO : ' . $e->getMessage(),ERROR,'');
85
+		}
86
+		return $this->idoDB;
87
+	}
88 88
     
89
-    /**
90
-     * Connect to Trap database
91
-     * @return \PDO
92
-     */
93
-    public function db_connect_trap()
94
-    {
95
-        if ($this->trapDB != null) {
96
-            // Check if connection is still alive
97
-            try {
98
-                $this->trapDB->query('select 1')->fetchColumn();
99
-                return $this->trapDB;
100
-            } catch (Exception $e) {
101
-                // select 1 failed, try to reconnect.
102
-                $this->logging->log('Database connection lost, reconnecting',WARN);
103
-            }           
104
-        }       
105
-        try {
106
-            $this->trapDB = new PDO($this->trapDSN,$this->trapUsername,$this->trapPass);
107
-        } catch (PDOException $e) {
108
-            $this->logging->log('Connection failed : ' . $e->getMessage(),ERROR,'');
109
-        }
110
-        return $this->trapDB;
111
-    }
89
+	/**
90
+	 * Connect to Trap database
91
+	 * @return \PDO
92
+	 */
93
+	public function db_connect_trap()
94
+	{
95
+		if ($this->trapDB != null) {
96
+			// Check if connection is still alive
97
+			try {
98
+				$this->trapDB->query('select 1')->fetchColumn();
99
+				return $this->trapDB;
100
+			} catch (Exception $e) {
101
+				// select 1 failed, try to reconnect.
102
+				$this->logging->log('Database connection lost, reconnecting',WARN);
103
+			}           
104
+		}       
105
+		try {
106
+			$this->trapDB = new PDO($this->trapDSN,$this->trapUsername,$this->trapPass);
107
+		} catch (PDOException $e) {
108
+			$this->logging->log('Connection failed : ' . $e->getMessage(),ERROR,'');
109
+		}
110
+		return $this->trapDB;
111
+	}
112 112
     
113
-    /**
114
-     * Setup dsn and check parameters
115
-     * @param array $configElmt
116
-     * @return string
117
-     */
118
-    protected function setupDSN($configElmt)  
119
-    {
120
-        if (!array_key_exists('db',$configElmt) ||
121
-            !array_key_exists('host',$configElmt) ||
122
-            !array_key_exists('dbname',$configElmt) ||
123
-            !array_key_exists('username',$configElmt))
124
-        {
125
-            $this->logging->log('Missing DB params',ERROR);
126
-            return ''; 
127
-        }
113
+	/**
114
+	 * Setup dsn and check parameters
115
+	 * @param array $configElmt
116
+	 * @return string
117
+	 */
118
+	protected function setupDSN($configElmt)  
119
+	{
120
+		if (!array_key_exists('db',$configElmt) ||
121
+			!array_key_exists('host',$configElmt) ||
122
+			!array_key_exists('dbname',$configElmt) ||
123
+			!array_key_exists('username',$configElmt))
124
+		{
125
+			$this->logging->log('Missing DB params',ERROR);
126
+			return ''; 
127
+		}
128 128
         
129
-        //	$dsn = 'mysql:dbname=traps;host=127.0.0.1';
130
-        $dsn= $configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
129
+		//	$dsn = 'mysql:dbname=traps;host=127.0.0.1';
130
+		$dsn= $configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
131 131
         
132
-        if (array_key_exists('port', $configElmt))
133
-        {
134
-            $dsn .= ';port='.$configElmt['port'];
135
-        }
136
-        return $dsn;
137
-    }
132
+		if (array_key_exists('port', $configElmt))
133
+		{
134
+			$dsn .= ';port='.$configElmt['port'];
135
+		}
136
+		return $dsn;
137
+	}
138 138
 
139
-    /** Set name=element in database config table
140
-     * @param string $name
141
-     * @param string $element
142
-     * @return boolean true on success, else false (error logged)
143
-     */
144
-    public function setDBConfig($name,$element)
145
-    {
146
-        $db_conn=$this->db_connect_trap();
147
-        $sql='SELECT id from '.$this->dbPrefix.'db_config WHERE ( name=\''.$name.'\' )';
148
-        if (($ret_code=$db_conn->query($sql)) === false) {
149
-            $this->logging->log('Error setting config element : ' . $sql,WARN,'');           
150
-            return false;
151
-        }
152
-        $value=$ret_code->fetch();
153
-        if ($value != null && isset($value['id']))
154
-        {   // Entry exists -> update
155
-            $sql='UPDATE '.$this->dbPrefix.'db_config SET value = \''.$element.'\' WHERE (id = '.$value['id'].')';
156
-        }
157
-        else
158
-        {   // Entry does no exists -> create
159
-            $sql='INSERT INTO '.$this->dbPrefix.'db_config (name,value) VALUES (\''.$name.'\' , \''.$element.'\' )';
160
-        }
161
-        if (($ret_code=$db_conn->query($sql)) === false) {
162
-            $this->logging->log('Error setting config element : ' . $sql,WARN,'');
163
-            return false;
164
-        }
165
-        $this->logging->log('Setting config '.$name.' = '.$element.' in database',INFO);
166
-        return true;
167
-    }
139
+	/** Set name=element in database config table
140
+	 * @param string $name
141
+	 * @param string $element
142
+	 * @return boolean true on success, else false (error logged)
143
+	 */
144
+	public function setDBConfig($name,$element)
145
+	{
146
+		$db_conn=$this->db_connect_trap();
147
+		$sql='SELECT id from '.$this->dbPrefix.'db_config WHERE ( name=\''.$name.'\' )';
148
+		if (($ret_code=$db_conn->query($sql)) === false) {
149
+			$this->logging->log('Error setting config element : ' . $sql,WARN,'');           
150
+			return false;
151
+		}
152
+		$value=$ret_code->fetch();
153
+		if ($value != null && isset($value['id']))
154
+		{   // Entry exists -> update
155
+			$sql='UPDATE '.$this->dbPrefix.'db_config SET value = \''.$element.'\' WHERE (id = '.$value['id'].')';
156
+		}
157
+		else
158
+		{   // Entry does no exists -> create
159
+			$sql='INSERT INTO '.$this->dbPrefix.'db_config (name,value) VALUES (\''.$name.'\' , \''.$element.'\' )';
160
+		}
161
+		if (($ret_code=$db_conn->query($sql)) === false) {
162
+			$this->logging->log('Error setting config element : ' . $sql,WARN,'');
163
+			return false;
164
+		}
165
+		$this->logging->log('Setting config '.$name.' = '.$element.' in database',INFO);
166
+		return true;
167
+	}
168 168
 
169
-    /**
170
-     *   Get data from db_config
171
-     *	@param $element string name of param
172
-     *	@return mixed : value (or null)
173
-     */
174
-    public function getDBConfig($element)
175
-    {
176
-        $db_conn=$this->db_connect_trap();
177
-        $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
178
-        if (($ret_code=$db_conn->query($sql)) === false) {
179
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
180
-            return null;
181
-        }
182
-        $value=$ret_code->fetch();
183
-        if ($value != null && isset($value['value']))
184
-        {
185
-            return $value['value'];
186
-        }
187
-        return null;
188
-    }
169
+	/**
170
+	 *   Get data from db_config
171
+	 *	@param $element string name of param
172
+	 *	@return mixed : value (or null)
173
+	 */
174
+	public function getDBConfig($element)
175
+	{
176
+		$db_conn=$this->db_connect_trap();
177
+		$sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
178
+		if (($ret_code=$db_conn->query($sql)) === false) {
179
+			$this->logging->log('No result in query : ' . $sql,WARN,'');
180
+			return null;
181
+		}
182
+		$value=$ret_code->fetch();
183
+		if ($value != null && isset($value['value']))
184
+		{
185
+			return $value['value'];
186
+		}
187
+		return null;
188
+	}
189 189
     
190 190
     
191
-    //*********    Schema Management *********************/
191
+	//*********    Schema Management *********************/
192 192
 
193
-    /** Create database schema
194
-     *	@param $schema_file	string File to read schema from
195
-     *	@param $table_prefix string to replace #PREFIX# in schema file by this
196
-     */
197
-    public function create_schema($schema_file,$table_prefix)
198
-    {
199
-        //Read data from snmptrapd from stdin
200
-        $input_stream=fopen($schema_file, 'r');
193
+	/** Create database schema
194
+	 *	@param $schema_file	string File to read schema from
195
+	 *	@param $table_prefix string to replace #PREFIX# in schema file by this
196
+	 */
197
+	public function create_schema($schema_file,$table_prefix)
198
+	{
199
+		//Read data from snmptrapd from stdin
200
+		$input_stream=fopen($schema_file, 'r');
201 201
         
202
-        if ($input_stream=== false)
203
-        {
204
-            $this->logging->log("Error reading schema !",ERROR,'');
205
-            return;
206
-        }
207
-        $newline='';
208
-        $cur_table='';
209
-        $cur_table_array=array();
210
-        $db_conn=$this->db_connect_trap();
202
+		if ($input_stream=== false)
203
+		{
204
+			$this->logging->log("Error reading schema !",ERROR,'');
205
+			return;
206
+		}
207
+		$newline='';
208
+		$cur_table='';
209
+		$cur_table_array=array();
210
+		$db_conn=$this->db_connect_trap();
211 211
         
212
-        while (($line=fgets($input_stream)) !== false)
213
-        {
214
-            $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
215
-            if (preg_match('/; *$/', $newline))
216
-            {
217
-                $sql= $newline;
218
-                if ($db_conn->query($sql) === false) {
219
-                    $this->logging->log('Error create schema : '.$sql,ERROR,'');
220
-                    return;
221
-                }
222
-                if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
223
-                {
224
-                    $cur_table='table '.$cur_table_array[1];
225
-                }
226
-                else
227
-                {
228
-                    $cur_table='secret SQL stuff :-)';
229
-                }
230
-                $this->logging->log('Creating : ' . $cur_table,INFO );
231
-                $newline='';
232
-            }
233
-        }
212
+		while (($line=fgets($input_stream)) !== false)
213
+		{
214
+			$newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
215
+			if (preg_match('/; *$/', $newline))
216
+			{
217
+				$sql= $newline;
218
+				if ($db_conn->query($sql) === false) {
219
+					$this->logging->log('Error create schema : '.$sql,ERROR,'');
220
+					return;
221
+				}
222
+				if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
223
+				{
224
+					$cur_table='table '.$cur_table_array[1];
225
+				}
226
+				else
227
+				{
228
+					$cur_table='secret SQL stuff :-)';
229
+				}
230
+				$this->logging->log('Creating : ' . $cur_table,INFO );
231
+				$newline='';
232
+			}
233
+		}
234 234
         
235
-        $sql= $newline;
236
-        if ($sql != '' )
237
-        {
238
-            if ($db_conn->query($sql) === false) {
239
-                $this->logging->log('Error create schema : '.$sql,ERROR,'');
240
-                return;
241
-            }
242
-        }
243
-        $this->logging->log('Schema created',INFO);
244
-    }
235
+		$sql= $newline;
236
+		if ($sql != '' )
237
+		{
238
+			if ($db_conn->query($sql) === false) {
239
+				$this->logging->log('Error create schema : '.$sql,ERROR,'');
240
+				return;
241
+			}
242
+		}
243
+		$this->logging->log('Schema created',INFO);
244
+	}
245 245
     
246
-    /**
247
-     * Update database schema from current (as set in db) to $target_version
248
-     *     @param $prefix string file prefix of sql update File
249
-     *     @param $target_version int target db version number
250
-     *     @param $table_prefix string to replace #PREFIX# in schema file by this
251
-     *     @param bool $getmsg : only get messages from version upgrades
252
-     *     @return string : if $getmsg=true, return messages or 'ERROR' on error.
253
-     */
254
-    public function update_schema($prefix,$target_version,$table_prefix,$getmsg=false)
255
-    {
256
-        // Get current db number
257
-        $db_conn=$this->db_connect_trap();
258
-        $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE name=\'db_version\' ';
259
-        $this->logging->log('SQL query : '.$sql,DEBUG );
260
-        if (($ret_code=$db_conn->query($sql)) === false) {
261
-            $this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
262
-            return 'ERROR';
263
-        }
264
-        $version=$ret_code->fetchAll();
265
-        $cur_version=$version[0]['value'];
246
+	/**
247
+	 * Update database schema from current (as set in db) to $target_version
248
+	 *     @param $prefix string file prefix of sql update File
249
+	 *     @param $target_version int target db version number
250
+	 *     @param $table_prefix string to replace #PREFIX# in schema file by this
251
+	 *     @param bool $getmsg : only get messages from version upgrades
252
+	 *     @return string : if $getmsg=true, return messages or 'ERROR' on error.
253
+	 */
254
+	public function update_schema($prefix,$target_version,$table_prefix,$getmsg=false)
255
+	{
256
+		// Get current db number
257
+		$db_conn=$this->db_connect_trap();
258
+		$sql='SELECT value from '.$this->dbPrefix.'db_config WHERE name=\'db_version\' ';
259
+		$this->logging->log('SQL query : '.$sql,DEBUG );
260
+		if (($ret_code=$db_conn->query($sql)) === false) {
261
+			$this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
262
+			return 'ERROR';
263
+		}
264
+		$version=$ret_code->fetchAll();
265
+		$cur_version=$version[0]['value'];
266 266
         
267
-        if ($this->trapDBType == 'pgsql')
268
-        {
269
-            $prefix .= 'update_pgsql/schema_';
270
-        }
271
-        else
272
-        {
273
-            $prefix .= 'update_sql/schema_';
274
-        }
275
-        //echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
276
-        if ($getmsg === true)
277
-        {
278
-            return $this->update_schema_message($prefix, $cur_version, $target_version);
279
-        }
267
+		if ($this->trapDBType == 'pgsql')
268
+		{
269
+			$prefix .= 'update_pgsql/schema_';
270
+		}
271
+		else
272
+		{
273
+			$prefix .= 'update_sql/schema_';
274
+		}
275
+		//echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
276
+		if ($getmsg === true)
277
+		{
278
+			return $this->update_schema_message($prefix, $cur_version, $target_version);
279
+		}
280 280
         
281
-        if ($this->update_schema_do($prefix, $cur_version, $target_version, $table_prefix) === true)
282
-        {
283
-            return 'ERROR';
284
-        }
285
-        return '';
281
+		if ($this->update_schema_do($prefix, $cur_version, $target_version, $table_prefix) === true)
282
+		{
283
+			return 'ERROR';
284
+		}
285
+		return '';
286 286
 
287
-    }
287
+	}
288 288
 
289
-    /**
290
-     * Update database schema from current (as set in db) to $target_version
291
-     *     @param string $prefix  file prefix of sql update File
292
-     *     @param int $cur_version  current db version number
293
-     *     @param int $target_version  target db version number
294
-     *     @param string $table_prefix   to replace #PREFIX# in schema file by this
295
-     *     @return bool : true on error
296
-     */
297
-    public function update_schema_do($prefix,$cur_version,$target_version,$table_prefix)
298
-    {
299
-        while($cur_version<$target_version)
300
-        { // TODO : execute pre & post scripts
301
-            $cur_version++;
302
-            $this->logging->log('Updating to version : ' .$cur_version ,INFO );
303
-            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
304
-            $input_stream=fopen($updateFile, 'r');
305
-            if ($input_stream=== false)
306
-            {
307
-                $this->logging->log("Error reading update file ". $updateFile,ERROR);
308
-                return true;
309
-            }
310
-            $newline='';
311
-            $db_conn=$this->db_connect_trap();
312
-            $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
313
-            while (($line=fgets($input_stream)) !== false)
314
-            {
315
-                if (preg_match('/^#/', $line)) continue; // ignore comment lines
316
-                $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
317
-                if (preg_match('/; *$/', $newline))
318
-                {
319
-                    $sql_req=$db_conn->prepare($newline);
320
-                    if ($sql_req->execute() === false) {
321
-                        $this->logging->log('Error create schema : '.$newline,ERROR);
322
-                        return true;
323
-                    }
324
-                    $cur_table_array=array();
325
-                    if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
326
-                    {
327
-                        $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
328
-                    }
329
-                    else
330
-                    {
331
-                        $cur_table='secret SQL stuff :-)';
332
-                        //$cur_table=$newline;
333
-                    }
334
-                    $this->logging->log('Doing : ' . $cur_table,INFO );
289
+	/**
290
+	 * Update database schema from current (as set in db) to $target_version
291
+	 *     @param string $prefix  file prefix of sql update File
292
+	 *     @param int $cur_version  current db version number
293
+	 *     @param int $target_version  target db version number
294
+	 *     @param string $table_prefix   to replace #PREFIX# in schema file by this
295
+	 *     @return bool : true on error
296
+	 */
297
+	public function update_schema_do($prefix,$cur_version,$target_version,$table_prefix)
298
+	{
299
+		while($cur_version<$target_version)
300
+		{ // TODO : execute pre & post scripts
301
+			$cur_version++;
302
+			$this->logging->log('Updating to version : ' .$cur_version ,INFO );
303
+			$updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
304
+			$input_stream=fopen($updateFile, 'r');
305
+			if ($input_stream=== false)
306
+			{
307
+				$this->logging->log("Error reading update file ". $updateFile,ERROR);
308
+				return true;
309
+			}
310
+			$newline='';
311
+			$db_conn=$this->db_connect_trap();
312
+			$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
313
+			while (($line=fgets($input_stream)) !== false)
314
+			{
315
+				if (preg_match('/^#/', $line)) continue; // ignore comment lines
316
+				$newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
317
+				if (preg_match('/; *$/', $newline))
318
+				{
319
+					$sql_req=$db_conn->prepare($newline);
320
+					if ($sql_req->execute() === false) {
321
+						$this->logging->log('Error create schema : '.$newline,ERROR);
322
+						return true;
323
+					}
324
+					$cur_table_array=array();
325
+					if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
326
+					{
327
+						$cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
328
+					}
329
+					else
330
+					{
331
+						$cur_table='secret SQL stuff :-)';
332
+						//$cur_table=$newline;
333
+					}
334
+					$this->logging->log('Doing : ' . $cur_table,INFO );
335 335
                     
336
-                    $newline='';
337
-                }
338
-            }
339
-            fclose($input_stream);
336
+					$newline='';
337
+				}
338
+			}
339
+			fclose($input_stream);
340 340
             
341
-            $sql='UPDATE '.$this->dbPrefix.'db_config SET value='.$cur_version.' WHERE ( name=\'db_version\' )';
342
-            $this->logging->log('SQL query : '.$sql,DEBUG );
343
-            if ($db_conn->query($sql) === false) {
344
-                $this->logging->log('Cannot update db version. Query : ' . $sql,WARN);
345
-                return true;
346
-            }
341
+			$sql='UPDATE '.$this->dbPrefix.'db_config SET value='.$cur_version.' WHERE ( name=\'db_version\' )';
342
+			$this->logging->log('SQL query : '.$sql,DEBUG );
343
+			if ($db_conn->query($sql) === false) {
344
+				$this->logging->log('Cannot update db version. Query : ' . $sql,WARN);
345
+				return true;
346
+			}
347 347
             
348
-            $this->logging->log('Schema updated to version : '.$cur_version ,INFO);
349
-        }
350
-        return false;
351
-    }
348
+			$this->logging->log('Schema updated to version : '.$cur_version ,INFO);
349
+		}
350
+		return false;
351
+	}
352 352
     
353
-    /**
354
-     * Get database message for update to $target_version
355
-     *     @param string $prefix  file prefix of sql update File
356
-     *     @param int $cur_version  current db version number
357
-     *     @param int $target_version  target db version number
358
-     *     @return string : return messages or 'ERROR'.
359
-     */
360
-    private function update_schema_message($prefix,$cur_version,$target_version)
361
-    {
353
+	/**
354
+	 * Get database message for update to $target_version
355
+	 *     @param string $prefix  file prefix of sql update File
356
+	 *     @param int $cur_version  current db version number
357
+	 *     @param int $target_version  target db version number
358
+	 *     @return string : return messages or 'ERROR'.
359
+	 */
360
+	private function update_schema_message($prefix,$cur_version,$target_version)
361
+	{
362 362
  
363
-        $message='';
364
-        $this->logging->log('getting message for upgrade',DEBUG );
365
-        while($cur_version<$target_version)
366
-        {
367
-            $cur_version++;
368
-            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
369
-            $input_stream=fopen($updateFile, 'r');
370
-            if ($input_stream=== false)
371
-            {
372
-                $this->logging->log("Error reading update file ". $updateFile,2,'');
373
-                return 'ERROR';
374
-            }
375
-            do 
376
-            { 
377
-                $line=fgets($input_stream); 
378
-            }
379
-            while ($line !== false && !preg_match('/#MESSAGE/',$line));
380
-            fclose($input_stream);
381
-            if ($line === false)
382
-            {
383
-                $this->logging->log("No message in file ". $updateFile,2,'');
384
-                return '';
385
-            }
386
-            $message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
387
-        }
388
-        return $message;
389
-    }
363
+		$message='';
364
+		$this->logging->log('getting message for upgrade',DEBUG );
365
+		while($cur_version<$target_version)
366
+		{
367
+			$cur_version++;
368
+			$updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
369
+			$input_stream=fopen($updateFile, 'r');
370
+			if ($input_stream=== false)
371
+			{
372
+				$this->logging->log("Error reading update file ". $updateFile,2,'');
373
+				return 'ERROR';
374
+			}
375
+			do 
376
+			{ 
377
+				$line=fgets($input_stream); 
378
+			}
379
+			while ($line !== false && !preg_match('/#MESSAGE/',$line));
380
+			fclose($input_stream);
381
+			if ($line === false)
382
+			{
383
+				$this->logging->log("No message in file ". $updateFile,2,'');
384
+				return '';
385
+			}
386
+			$message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
387
+		}
388
+		return $message;
389
+	}
390 390
     
391 391
 }
392 392
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -34,16 +34,16 @@  discard block
 block discarded – undo
34 34
      * @param Logging $logClass : where to log
35 35
      * @param array $dbParam : array of named params  type,host,dbname,username,[port],[password]
36 36
      */
37
-    function __construct($logClass,$dbParam,$dbPrefix)
37
+    function __construct($logClass, $dbParam, $dbPrefix)
38 38
     {
39 39
         $this->logging=$logClass;
40 40
         $this->dbPrefix=$dbPrefix;
41 41
         
42 42
         $this->trapDSN=$this->setupDSN($dbParam);
43
-        $this->trapUsername = $dbParam['username'];
44
-        $this->trapPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
43
+        $this->trapUsername=$dbParam['username'];
44
+        $this->trapPass=(array_key_exists('password', $dbParam)) ? $dbParam['password'] : '';
45 45
         $this->trapDBType=$dbParam['db'];
46
-        $this->logging->log('DSN : '.$this->trapDSN. ';user '.$this->trapUsername.' / prefix : '. $this->dbPrefix,INFO);
46
+        $this->logging->log('DSN : '.$this->trapDSN.';user '.$this->trapUsername.' / prefix : '.$this->dbPrefix, INFO);
47 47
         $this->db_connect_trap();
48 48
         
49 49
     }
@@ -55,9 +55,9 @@  discard block
 block discarded – undo
55 55
     public function setupIDO($dbParam)
56 56
     {
57 57
         $this->idoDSN=$this->setupDSN($dbParam);
58
-        $this->idoUsername = $dbParam['username'];
59
-        $this->idoPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
60
-        $this->logging->log('DSN : '.$this->idoDSN. ';user '.$this->idoUsername,INFO);
58
+        $this->idoUsername=$dbParam['username'];
59
+        $this->idoPass=(array_key_exists('password', $dbParam)) ? $dbParam['password'] : '';
60
+        $this->logging->log('DSN : '.$this->idoDSN.';user '.$this->idoUsername, INFO);
61 61
         $this->idoDBType=$dbParam['db'];
62 62
         $this->db_connect_ido();
63 63
     }
@@ -75,13 +75,13 @@  discard block
 block discarded – undo
75 75
                 return $this->idoDB;
76 76
             } catch (Exception $e) {
77 77
                 // select 1 failed, try to reconnect.
78
-                $this->logging->log('Database IDO connection lost, reconnecting',WARN);
78
+                $this->logging->log('Database IDO connection lost, reconnecting', WARN);
79 79
             }
80 80
         }
81 81
         try {
82
-            $this->idoDB = new PDO($this->idoDSN,$this->idoUsername,$this->idoPass);
82
+            $this->idoDB=new PDO($this->idoDSN, $this->idoUsername, $this->idoPass);
83 83
         } catch (PDOException $e) {
84
-            $this->logging->log('Connection failed to IDO : ' . $e->getMessage(),ERROR,'');
84
+            $this->logging->log('Connection failed to IDO : '.$e->getMessage(), ERROR, '');
85 85
         }
86 86
         return $this->idoDB;
87 87
     }
@@ -99,13 +99,13 @@  discard block
 block discarded – undo
99 99
                 return $this->trapDB;
100 100
             } catch (Exception $e) {
101 101
                 // select 1 failed, try to reconnect.
102
-                $this->logging->log('Database connection lost, reconnecting',WARN);
102
+                $this->logging->log('Database connection lost, reconnecting', WARN);
103 103
             }           
104 104
         }       
105 105
         try {
106
-            $this->trapDB = new PDO($this->trapDSN,$this->trapUsername,$this->trapPass);
106
+            $this->trapDB=new PDO($this->trapDSN, $this->trapUsername, $this->trapPass);
107 107
         } catch (PDOException $e) {
108
-            $this->logging->log('Connection failed : ' . $e->getMessage(),ERROR,'');
108
+            $this->logging->log('Connection failed : '.$e->getMessage(), ERROR, '');
109 109
         }
110 110
         return $this->trapDB;
111 111
     }
@@ -117,21 +117,21 @@  discard block
 block discarded – undo
117 117
      */
118 118
     protected function setupDSN($configElmt)  
119 119
     {
120
-        if (!array_key_exists('db',$configElmt) ||
121
-            !array_key_exists('host',$configElmt) ||
122
-            !array_key_exists('dbname',$configElmt) ||
123
-            !array_key_exists('username',$configElmt))
120
+        if (!array_key_exists('db', $configElmt) ||
121
+            !array_key_exists('host', $configElmt) ||
122
+            !array_key_exists('dbname', $configElmt) ||
123
+            !array_key_exists('username', $configElmt))
124 124
         {
125
-            $this->logging->log('Missing DB params',ERROR);
125
+            $this->logging->log('Missing DB params', ERROR);
126 126
             return ''; 
127 127
         }
128 128
         
129 129
         //	$dsn = 'mysql:dbname=traps;host=127.0.0.1';
130
-        $dsn= $configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
130
+        $dsn=$configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
131 131
         
132 132
         if (array_key_exists('port', $configElmt))
133 133
         {
134
-            $dsn .= ';port='.$configElmt['port'];
134
+            $dsn.=';port='.$configElmt['port'];
135 135
         }
136 136
         return $dsn;
137 137
     }
@@ -141,12 +141,12 @@  discard block
 block discarded – undo
141 141
      * @param string $element
142 142
      * @return boolean true on success, else false (error logged)
143 143
      */
144
-    public function setDBConfig($name,$element)
144
+    public function setDBConfig($name, $element)
145 145
     {
146 146
         $db_conn=$this->db_connect_trap();
147 147
         $sql='SELECT id from '.$this->dbPrefix.'db_config WHERE ( name=\''.$name.'\' )';
148 148
         if (($ret_code=$db_conn->query($sql)) === false) {
149
-            $this->logging->log('Error setting config element : ' . $sql,WARN,'');           
149
+            $this->logging->log('Error setting config element : '.$sql, WARN, '');           
150 150
             return false;
151 151
         }
152 152
         $value=$ret_code->fetch();
@@ -159,10 +159,10 @@  discard block
 block discarded – undo
159 159
             $sql='INSERT INTO '.$this->dbPrefix.'db_config (name,value) VALUES (\''.$name.'\' , \''.$element.'\' )';
160 160
         }
161 161
         if (($ret_code=$db_conn->query($sql)) === false) {
162
-            $this->logging->log('Error setting config element : ' . $sql,WARN,'');
162
+            $this->logging->log('Error setting config element : '.$sql, WARN, '');
163 163
             return false;
164 164
         }
165
-        $this->logging->log('Setting config '.$name.' = '.$element.' in database',INFO);
165
+        $this->logging->log('Setting config '.$name.' = '.$element.' in database', INFO);
166 166
         return true;
167 167
     }
168 168
 
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
         $db_conn=$this->db_connect_trap();
177 177
         $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
178 178
         if (($ret_code=$db_conn->query($sql)) === false) {
179
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
179
+            $this->logging->log('No result in query : '.$sql, WARN, '');
180 180
             return null;
181 181
         }
182 182
         $value=$ret_code->fetch();
@@ -194,14 +194,14 @@  discard block
 block discarded – undo
194 194
      *	@param $schema_file	string File to read schema from
195 195
      *	@param $table_prefix string to replace #PREFIX# in schema file by this
196 196
      */
197
-    public function create_schema($schema_file,$table_prefix)
197
+    public function create_schema($schema_file, $table_prefix)
198 198
     {
199 199
         //Read data from snmptrapd from stdin
200 200
         $input_stream=fopen($schema_file, 'r');
201 201
         
202
-        if ($input_stream=== false)
202
+        if ($input_stream === false)
203 203
         {
204
-            $this->logging->log("Error reading schema !",ERROR,'');
204
+            $this->logging->log("Error reading schema !", ERROR, '');
205 205
             return;
206 206
         }
207 207
         $newline='';
@@ -211,15 +211,15 @@  discard block
 block discarded – undo
211 211
         
212 212
         while (($line=fgets($input_stream)) !== false)
213 213
         {
214
-            $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
214
+            $newline.=chop(preg_replace('/#PREFIX#/', $table_prefix, $line));
215 215
             if (preg_match('/; *$/', $newline))
216 216
             {
217
-                $sql= $newline;
217
+                $sql=$newline;
218 218
                 if ($db_conn->query($sql) === false) {
219
-                    $this->logging->log('Error create schema : '.$sql,ERROR,'');
219
+                    $this->logging->log('Error create schema : '.$sql, ERROR, '');
220 220
                     return;
221 221
                 }
222
-                if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
222
+                if (preg_match('/^ *CREATE TABLE ([^ ]+)/', $newline, $cur_table_array))
223 223
                 {
224 224
                     $cur_table='table '.$cur_table_array[1];
225 225
                 }
@@ -227,20 +227,20 @@  discard block
 block discarded – undo
227 227
                 {
228 228
                     $cur_table='secret SQL stuff :-)';
229 229
                 }
230
-                $this->logging->log('Creating : ' . $cur_table,INFO );
230
+                $this->logging->log('Creating : '.$cur_table, INFO);
231 231
                 $newline='';
232 232
             }
233 233
         }
234 234
         
235
-        $sql= $newline;
236
-        if ($sql != '' )
235
+        $sql=$newline;
236
+        if ($sql != '')
237 237
         {
238 238
             if ($db_conn->query($sql) === false) {
239
-                $this->logging->log('Error create schema : '.$sql,ERROR,'');
239
+                $this->logging->log('Error create schema : '.$sql, ERROR, '');
240 240
                 return;
241 241
             }
242 242
         }
243
-        $this->logging->log('Schema created',INFO);
243
+        $this->logging->log('Schema created', INFO);
244 244
     }
245 245
     
246 246
     /**
@@ -251,14 +251,14 @@  discard block
 block discarded – undo
251 251
      *     @param bool $getmsg : only get messages from version upgrades
252 252
      *     @return string : if $getmsg=true, return messages or 'ERROR' on error.
253 253
      */
254
-    public function update_schema($prefix,$target_version,$table_prefix,$getmsg=false)
254
+    public function update_schema($prefix, $target_version, $table_prefix, $getmsg=false)
255 255
     {
256 256
         // Get current db number
257 257
         $db_conn=$this->db_connect_trap();
258 258
         $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE name=\'db_version\' ';
259
-        $this->logging->log('SQL query : '.$sql,DEBUG );
259
+        $this->logging->log('SQL query : '.$sql, DEBUG);
260 260
         if (($ret_code=$db_conn->query($sql)) === false) {
261
-            $this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
261
+            $this->logging->log('Cannot get db version. Query : '.$sql, 2, '');
262 262
             return 'ERROR';
263 263
         }
264 264
         $version=$ret_code->fetchAll();
@@ -266,11 +266,11 @@  discard block
 block discarded – undo
266 266
         
267 267
         if ($this->trapDBType == 'pgsql')
268 268
         {
269
-            $prefix .= 'update_pgsql/schema_';
269
+            $prefix.='update_pgsql/schema_';
270 270
         }
271 271
         else
272 272
         {
273
-            $prefix .= 'update_sql/schema_';
273
+            $prefix.='update_sql/schema_';
274 274
         }
275 275
         //echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
276 276
         if ($getmsg === true)
@@ -294,17 +294,17 @@  discard block
 block discarded – undo
294 294
      *     @param string $table_prefix   to replace #PREFIX# in schema file by this
295 295
      *     @return bool : true on error
296 296
      */
297
-    public function update_schema_do($prefix,$cur_version,$target_version,$table_prefix)
297
+    public function update_schema_do($prefix, $cur_version, $target_version, $table_prefix)
298 298
     {
299
-        while($cur_version<$target_version)
299
+        while ($cur_version < $target_version)
300 300
         { // TODO : execute pre & post scripts
301 301
             $cur_version++;
302
-            $this->logging->log('Updating to version : ' .$cur_version ,INFO );
303
-            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
302
+            $this->logging->log('Updating to version : '.$cur_version, INFO);
303
+            $updateFile=$prefix.'v'.($cur_version - 1).'_v'.$cur_version.'.sql';
304 304
             $input_stream=fopen($updateFile, 'r');
305
-            if ($input_stream=== false)
305
+            if ($input_stream === false)
306 306
             {
307
-                $this->logging->log("Error reading update file ". $updateFile,ERROR);
307
+                $this->logging->log("Error reading update file ".$updateFile, ERROR);
308 308
                 return true;
309 309
             }
310 310
             $newline='';
@@ -313,25 +313,25 @@  discard block
 block discarded – undo
313 313
             while (($line=fgets($input_stream)) !== false)
314 314
             {
315 315
                 if (preg_match('/^#/', $line)) continue; // ignore comment lines
316
-                $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
316
+                $newline.=chop(preg_replace('/#PREFIX#/', $table_prefix, $line));
317 317
                 if (preg_match('/; *$/', $newline))
318 318
                 {
319 319
                     $sql_req=$db_conn->prepare($newline);
320 320
                     if ($sql_req->execute() === false) {
321
-                        $this->logging->log('Error create schema : '.$newline,ERROR);
321
+                        $this->logging->log('Error create schema : '.$newline, ERROR);
322 322
                         return true;
323 323
                     }
324 324
                     $cur_table_array=array();
325
-                    if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
325
+                    if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/', $newline, $cur_table_array))
326 326
                     {
327
-                        $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
327
+                        $cur_table=$cur_table_array[1].' SQL table '.$cur_table_array[2];
328 328
                     }
329 329
                     else
330 330
                     {
331 331
                         $cur_table='secret SQL stuff :-)';
332 332
                         //$cur_table=$newline;
333 333
                     }
334
-                    $this->logging->log('Doing : ' . $cur_table,INFO );
334
+                    $this->logging->log('Doing : '.$cur_table, INFO);
335 335
                     
336 336
                     $newline='';
337 337
                 }
@@ -339,13 +339,13 @@  discard block
 block discarded – undo
339 339
             fclose($input_stream);
340 340
             
341 341
             $sql='UPDATE '.$this->dbPrefix.'db_config SET value='.$cur_version.' WHERE ( name=\'db_version\' )';
342
-            $this->logging->log('SQL query : '.$sql,DEBUG );
342
+            $this->logging->log('SQL query : '.$sql, DEBUG);
343 343
             if ($db_conn->query($sql) === false) {
344
-                $this->logging->log('Cannot update db version. Query : ' . $sql,WARN);
344
+                $this->logging->log('Cannot update db version. Query : '.$sql, WARN);
345 345
                 return true;
346 346
             }
347 347
             
348
-            $this->logging->log('Schema updated to version : '.$cur_version ,INFO);
348
+            $this->logging->log('Schema updated to version : '.$cur_version, INFO);
349 349
         }
350 350
         return false;
351 351
     }
@@ -357,33 +357,33 @@  discard block
 block discarded – undo
357 357
      *     @param int $target_version  target db version number
358 358
      *     @return string : return messages or 'ERROR'.
359 359
      */
360
-    private function update_schema_message($prefix,$cur_version,$target_version)
360
+    private function update_schema_message($prefix, $cur_version, $target_version)
361 361
     {
362 362
  
363 363
         $message='';
364
-        $this->logging->log('getting message for upgrade',DEBUG );
365
-        while($cur_version<$target_version)
364
+        $this->logging->log('getting message for upgrade', DEBUG);
365
+        while ($cur_version < $target_version)
366 366
         {
367 367
             $cur_version++;
368
-            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
368
+            $updateFile=$prefix.'v'.($cur_version - 1).'_v'.$cur_version.'.sql';
369 369
             $input_stream=fopen($updateFile, 'r');
370
-            if ($input_stream=== false)
370
+            if ($input_stream === false)
371 371
             {
372
-                $this->logging->log("Error reading update file ". $updateFile,2,'');
372
+                $this->logging->log("Error reading update file ".$updateFile, 2, '');
373 373
                 return 'ERROR';
374 374
             }
375 375
             do 
376 376
             { 
377 377
                 $line=fgets($input_stream); 
378 378
             }
379
-            while ($line !== false && !preg_match('/#MESSAGE/',$line));
379
+            while ($line !== false && !preg_match('/#MESSAGE/', $line));
380 380
             fclose($input_stream);
381 381
             if ($line === false)
382 382
             {
383
-                $this->logging->log("No message in file ". $updateFile,2,'');
383
+                $this->logging->log("No message in file ".$updateFile, 2, '');
384 384
                 return '';
385 385
             }
386
-            $message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
386
+            $message.=($cur_version - 1).'->'.$cur_version.' : '.preg_replace('/#MESSAGE : /', '', $line)."\n";
387 387
         }
388 388
         return $message;
389 389
     }
Please login to merge, or discard this patch.
Braces   +8 added lines, -9 removed lines patch added patch discarded remove patch
@@ -153,8 +153,7 @@  discard block
 block discarded – undo
153 153
         if ($value != null && isset($value['id']))
154 154
         {   // Entry exists -> update
155 155
             $sql='UPDATE '.$this->dbPrefix.'db_config SET value = \''.$element.'\' WHERE (id = '.$value['id'].')';
156
-        }
157
-        else
156
+        } else
158 157
         {   // Entry does no exists -> create
159 158
             $sql='INSERT INTO '.$this->dbPrefix.'db_config (name,value) VALUES (\''.$name.'\' , \''.$element.'\' )';
160 159
         }
@@ -222,8 +221,7 @@  discard block
 block discarded – undo
222 221
                 if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
223 222
                 {
224 223
                     $cur_table='table '.$cur_table_array[1];
225
-                }
226
-                else
224
+                } else
227 225
                 {
228 226
                     $cur_table='secret SQL stuff :-)';
229 227
                 }
@@ -267,8 +265,7 @@  discard block
 block discarded – undo
267 265
         if ($this->trapDBType == 'pgsql')
268 266
         {
269 267
             $prefix .= 'update_pgsql/schema_';
270
-        }
271
-        else
268
+        } else
272 269
         {
273 270
             $prefix .= 'update_sql/schema_';
274 271
         }
@@ -312,7 +309,10 @@  discard block
 block discarded – undo
312 309
             $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
313 310
             while (($line=fgets($input_stream)) !== false)
314 311
             {
315
-                if (preg_match('/^#/', $line)) continue; // ignore comment lines
312
+                if (preg_match('/^#/', $line)) {
313
+                	continue;
314
+                }
315
+                // ignore comment lines
316 316
                 $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
317 317
                 if (preg_match('/; *$/', $newline))
318 318
                 {
@@ -325,8 +325,7 @@  discard block
 block discarded – undo
325 325
                     if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
326 326
                     {
327 327
                         $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
328
-                    }
329
-                    else
328
+                    } else
330 329
                     {
331 330
                         $cur_table='secret SQL stuff :-)';
332 331
                         //$cur_table=$newline;
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Trap.php 3 patches
Indentation   +963 added lines, -963 removed lines patch added patch discarded remove patch
@@ -16,953 +16,953 @@  discard block
 block discarded – undo
16 16
  */
17 17
 class Trap
18 18
 {
19
-    // Configuration files and dirs
20
-    /** @var string Icinga etc path */
21
-    protected $icingaweb2ETC;
22
-    /** @var string $trapModuleConfig config.ini of module */
23
-    protected $trapModuleConfig;
24
-    /** @var string $icingaweb2Ressources resources.ini of icingaweb2 */
25
-    protected $icingaweb2Ressources;
26
-    // Options from config.ini (default values)
27
-    /** @var string $snmptranslate */
28
-    protected $snmptranslate='/usr/bin/snmptranslate';
29
-    /** @var string $snmptranslate_dirs */
30
-    protected $snmptranslate_dirs='/usr/share/icingaweb2/modules/trapdirector/mibs';
31
-    /** @var string $icinga2cmd */
32
-    protected $icinga2cmd='/var/run/icinga2/cmd/icinga2.cmd';
33
-    /** @var string $dbPrefix */
34
-    protected $dbPrefix='traps_';
35
-    
36
-    // API
37
-    /** @var boolean $apiUse */
38
-    protected $apiUse=false;
39
-    /** @var Icinga2API $icinga2api */
40
-    protected $icinga2api=null;
41
-    /** @var string $apiHostname */
42
-    protected $apiHostname='';
43
-    /** @var integer $apiPort */
44
-    protected $apiPort=0;
45
-    /** @var string $apiUsername */
46
-    protected $apiUsername='';
47
-    /** @var string $apiPassword */
48
-    protected $apiPassword='';
49
-    
50
-    // Logs
51
-    /** @var Logging Logging class. */
52
-    public $logging;    //< Logging class.
53
-    /** @var bool true if log was setup in constructor */
54
-    protected $logSetup;   //< bool true if log was setup in constructor
55
-    
56
-    // Databases
57
-    /** @var Database $trapsDB  Database class*/
58
-    public $trapsDB = null;
59
-    
60
-    // Trap received data
61
-    protected $receivingHost;
62
-    /** @var array	Main trap data (oid, source...) */
63
-    public $trap_data=array();
64
-    public $trap_data_ext=array(); //< Additional trap data objects (oid/value).
65
-    public $trap_id=null; //< trap_id after sql insert
66
-    public $trap_action=null; //< trap action for final write
67
-    protected $trap_to_db=true; //< log trap to DB
68
-    
69
-    /** @var Mib mib class */
70
-    public $mibClass = null;
71
-    
72
-    /** @var Rule rule class */
73
-    public $ruleClass = null;
74
-    
75
-    /** @var Plugins plugins manager **/
76
-    public $pluginClass = null;
77
-    
78
-    function __construct($etc_dir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
79
-    {
80
-        // Paths of ini files
81
-        $this->icingaweb2ETC=$etc_dir;
82
-        $this->trapModuleConfig=$this->icingaweb2ETC."/modules/trapdirector/config.ini";
83
-        $this->icingaweb2Ressources=$this->icingaweb2ETC."/resources.ini";
84
-        
85
-        //************* Setup logging
86
-        $this->logging = new Logging();
87
-        if ($baseLogLevel != null)
88
-        {
89
-            $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
90
-            $this->logSetup=true;
91
-        }
92
-        else
93
-        {
94
-            $this->logSetup=false;
95
-        }
96
-        $this->logging->log('Loggin started', INFO);
97
-        
98
-        //*************** Get options from ini files
99
-        if (! is_file($this->trapModuleConfig))
100
-        {
101
-            throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
102
-        }
103
-        $trapConfig=parse_ini_file($this->trapModuleConfig,true);
104
-        if ($trapConfig == false)
105
-        {
106
-            $this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
107
-            throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
108
-        }
109
-        $this->getMainOptions($trapConfig); // Get main options from ini file
110
-        
111
-        //*************** Setup database class & get options
112
-        $this->setupDatabase($trapConfig);
113
-        
114
-        $this->getDatabaseOptions(); // Get options in database
115
-        
116
-        //*************** Setup API
117
-        if ($this->apiUse === true) $this->getAPI(); // Setup API
118
-        
119
-        //*************** Setup MIB
120
-        $this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
121
-        
122
-        //*************** Setup Rule
123
-        $this->ruleClass = new Rule($this->logging); //< Create Rule class
124
-        
125
-        $this->trap_data=array(  // TODO : put this in a reset function (DAEMON_MODE)
126
-            'source_ip'	=> 'unknown',
127
-            'source_port'	=> 'unknown',
128
-            'destination_ip'	=> 'unknown',
129
-            'destination_port'	=> 'unknown',
130
-            'trap_oid'	=> 'unknown'
131
-        );
132
-        
133
-        //*************** Setup Plugins
134
-        //Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
135
-        $this->pluginClass = new Plugins($this);
19
+	// Configuration files and dirs
20
+	/** @var string Icinga etc path */
21
+	protected $icingaweb2ETC;
22
+	/** @var string $trapModuleConfig config.ini of module */
23
+	protected $trapModuleConfig;
24
+	/** @var string $icingaweb2Ressources resources.ini of icingaweb2 */
25
+	protected $icingaweb2Ressources;
26
+	// Options from config.ini (default values)
27
+	/** @var string $snmptranslate */
28
+	protected $snmptranslate='/usr/bin/snmptranslate';
29
+	/** @var string $snmptranslate_dirs */
30
+	protected $snmptranslate_dirs='/usr/share/icingaweb2/modules/trapdirector/mibs';
31
+	/** @var string $icinga2cmd */
32
+	protected $icinga2cmd='/var/run/icinga2/cmd/icinga2.cmd';
33
+	/** @var string $dbPrefix */
34
+	protected $dbPrefix='traps_';
35
+    
36
+	// API
37
+	/** @var boolean $apiUse */
38
+	protected $apiUse=false;
39
+	/** @var Icinga2API $icinga2api */
40
+	protected $icinga2api=null;
41
+	/** @var string $apiHostname */
42
+	protected $apiHostname='';
43
+	/** @var integer $apiPort */
44
+	protected $apiPort=0;
45
+	/** @var string $apiUsername */
46
+	protected $apiUsername='';
47
+	/** @var string $apiPassword */
48
+	protected $apiPassword='';
49
+    
50
+	// Logs
51
+	/** @var Logging Logging class. */
52
+	public $logging;    //< Logging class.
53
+	/** @var bool true if log was setup in constructor */
54
+	protected $logSetup;   //< bool true if log was setup in constructor
55
+    
56
+	// Databases
57
+	/** @var Database $trapsDB  Database class*/
58
+	public $trapsDB = null;
59
+    
60
+	// Trap received data
61
+	protected $receivingHost;
62
+	/** @var array	Main trap data (oid, source...) */
63
+	public $trap_data=array();
64
+	public $trap_data_ext=array(); //< Additional trap data objects (oid/value).
65
+	public $trap_id=null; //< trap_id after sql insert
66
+	public $trap_action=null; //< trap action for final write
67
+	protected $trap_to_db=true; //< log trap to DB
68
+    
69
+	/** @var Mib mib class */
70
+	public $mibClass = null;
71
+    
72
+	/** @var Rule rule class */
73
+	public $ruleClass = null;
74
+    
75
+	/** @var Plugins plugins manager **/
76
+	public $pluginClass = null;
77
+    
78
+	function __construct($etc_dir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
79
+	{
80
+		// Paths of ini files
81
+		$this->icingaweb2ETC=$etc_dir;
82
+		$this->trapModuleConfig=$this->icingaweb2ETC."/modules/trapdirector/config.ini";
83
+		$this->icingaweb2Ressources=$this->icingaweb2ETC."/resources.ini";
84
+        
85
+		//************* Setup logging
86
+		$this->logging = new Logging();
87
+		if ($baseLogLevel != null)
88
+		{
89
+			$this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
90
+			$this->logSetup=true;
91
+		}
92
+		else
93
+		{
94
+			$this->logSetup=false;
95
+		}
96
+		$this->logging->log('Loggin started', INFO);
97
+        
98
+		//*************** Get options from ini files
99
+		if (! is_file($this->trapModuleConfig))
100
+		{
101
+			throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
102
+		}
103
+		$trapConfig=parse_ini_file($this->trapModuleConfig,true);
104
+		if ($trapConfig == false)
105
+		{
106
+			$this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
107
+			throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
108
+		}
109
+		$this->getMainOptions($trapConfig); // Get main options from ini file
110
+        
111
+		//*************** Setup database class & get options
112
+		$this->setupDatabase($trapConfig);
113
+        
114
+		$this->getDatabaseOptions(); // Get options in database
115
+        
116
+		//*************** Setup API
117
+		if ($this->apiUse === true) $this->getAPI(); // Setup API
118
+        
119
+		//*************** Setup MIB
120
+		$this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
121
+        
122
+		//*************** Setup Rule
123
+		$this->ruleClass = new Rule($this->logging); //< Create Rule class
124
+        
125
+		$this->trap_data=array(  // TODO : put this in a reset function (DAEMON_MODE)
126
+			'source_ip'	=> 'unknown',
127
+			'source_port'	=> 'unknown',
128
+			'destination_ip'	=> 'unknown',
129
+			'destination_port'	=> 'unknown',
130
+			'trap_oid'	=> 'unknown'
131
+		);
132
+        
133
+		//*************** Setup Plugins
134
+		//Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
135
+		$this->pluginClass = new Plugins($this);
136 136
             
137 137
             
138
-    }
139
-    
140
-    /**
141
-     * Get option from array of ini file, send message if empty
142
-     * @param string $option_array Array of ini file
143
-     * @param string $option_category category in ini file
144
-     * @param string $option_name name of option in category
145
-     * @param mixed $option_var variable to fill if found, left untouched if not found
146
-     * @param integer $log_level default 2 (warning)
147
-     * @param string $message warning message if not found
148
-     * @return boolean true if found, or false
149
-     */
150
-    protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
151
-    {
152
-        if (!isset($option_array[$option_category][$option_name]))
153
-        {
154
-            if ($message === null)
155
-            {
156
-                $message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
157
-            }
158
-            $this->logging->log($message,$log_level);
159
-            return false;
160
-        }
161
-        else
162
-        {
163
-            $option_var=$option_array[$option_category][$option_name];
164
-            return true;
165
-        }
166
-    }
167
-    
168
-    /**
169
-     * Get options from ini file
170
-     * @param array $trap_config : ini file array
171
-     */
172
-    protected function getMainOptions($trapConfig)
173
-    {
174
-        
175
-        // Snmptranslate binary path
176
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
177
-        
178
-        // mibs path
179
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
180
-        
181
-        // icinga2cmd path
182
-        $this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
183
-        
184
-        // table prefix
185
-        $this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
186
-        
187
-        // API options
188
-        if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
189
-        {
190
-            $this->apiUse=true;
191
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort);
192
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername);
193
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword);
194
-        }
195
-    }
196
-    
197
-    /**
198
-     * Create and setup database class for trap & ido (if no api) db
199
-     * @param array $trap_config : ini file array
200
-     */
201
-    protected function setupDatabase($trapConfig)
202
-    {
203
-        // Trap database
204
-        if (!array_key_exists('database',$trapConfig['config']))
205
-        {
206
-            $this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
207
-            return;
208
-        }
209
-        $dbTrapName=$trapConfig['config']['database'];
210
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
211
-        
212
-        if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
213
-        {
214
-            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
215
-            return;
216
-        }
217
-        if (!array_key_exists($dbTrapName,$dbConfig))
218
-        {
219
-            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
220
-            return;
221
-        }
222
-        
223
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
224
-        
225
-        if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
226
-        
227
-        // IDO Database
228
-        if (!array_key_exists('IDOdatabase',$trapConfig['config']))
229
-        {
230
-            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
231
-        }
232
-        $dbIdoName=$trapConfig['config']['IDOdatabase'];
233
-        
234
-        $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
235
-        if (!array_key_exists($dbIdoName,$dbConfig))
236
-        {
237
-            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
238
-            return;
239
-        }
240
-        
241
-        $this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
242
-    }
243
-    
244
-    /**
245
-     * Get options in database
246
-     */
247
-    protected function getDatabaseOptions()
248
-    {
249
-        // Database options
250
-        if ($this->logSetup === false) // Only if logging was no setup in constructor
251
-        {
252
-            $this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
253
-            $this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
254
-            $this->getDBConfigIfSet('log_file',$this->logging->outputFile);
255
-        }
256
-    }
257
-    
258
-    /** Set $variable to value if $element found in database config table
259
-     * @param string $element
260
-     * @param string $variable
261
-     */
262
-    protected function getDBConfigIfSet($element,&$variable)
263
-    {
264
-        $value=$this->getDBConfig($element);
265
-        if ($value != null) $variable=$value;
266
-    }
267
-    
268
-    /**
269
-     *   Get data from db_config
270
-     *	@param $element string name of param
271
-     *	@return mixed : value (or null)
272
-     */
273
-    protected function getDBConfig($element)  // TODO : put this in DB class
274
-    {
275
-        $db_conn=$this->trapsDB->db_connect_trap();
276
-        $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
277
-        if (($ret_code=$db_conn->query($sql)) === false) {
278
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
279
-            return null;
280
-        }
281
-        $value=$ret_code->fetch();
282
-        if ($value != null && isset($value['value']))
283
-        {
284
-            return $value['value'];
285
-        }
286
-        return null;
287
-    }
288
-    
289
-    /** OBSOLETE Send log. Throws exception on critical error
290
-     *	@param	string $message Message to log
291
-     *	@param	int $level 1=critical 2=warning 3=trace 4=debug
292
-     *	@param  string $destination file/syslog/display
293
-     *	@return void
294
-     **/
295
-    public function trapLog( $message, $level, $destination ='') // OBSOLETE
296
-    {
297
-        // TODO : replace ref with $this->logging->log
298
-        $this->logging->log($message, $level, $destination);
299
-    }
300
-    
301
-    public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
302
-    {
303
-        $this->logging->setLogging($debugLvl, $outputType,$outputOption);
304
-    }
305
-    
306
-    /**
307
-     * Returns or create new IcingaAPI object
308
-     * @return \Icinga\Module\Trapdirector\Icinga2API
309
-     */
310
-    protected function getAPI()
311
-    {
312
-        if ($this->icinga2api == null)
313
-        {
314
-            $this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
315
-        }
316
-        return $this->icinga2api;
317
-    }
318
-    
319
-    
320
-    /**
321
-     * read data from stream
322
-     *	@param $stream string input stream, defaults to "php://stdin"
323
-     *	@return mixed array trap data or exception with error
324
-     */
325
-    public function read_trap($stream='php://stdin')
326
-    {
327
-        //Read data from snmptrapd from stdin
328
-        $input_stream=fopen($stream, 'r');
329
-        
330
-        if ($input_stream === false)
331
-        {
332
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
333
-            $this->logging->log("Error reading stdin !",ERROR,'');
334
-            return null; // note : exception thrown by logging
335
-        }
336
-        
337
-        // line 1 : host
338
-        $this->receivingHost=chop(fgets($input_stream));
339
-        if ($this->receivingHost === false)
340
-        {
341
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
342
-            $this->logging->log("Error reading Host !",ERROR,'');
343
-        }
344
-        // line 2 IP:port=>IP:port
345
-        $IP=chop(fgets($input_stream));
346
-        if ($IP === false)
347
-        {
348
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
349
-            $this->logging->log("Error reading IP !",ERROR,'');
350
-        }
351
-        $matches=array();
352
-        $ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
353
-        if ($ret_code===0 || $ret_code===false)
354
-        {
355
-            $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
356
-            $this->logging->log('Error parsing IP : '.$IP,ERROR,'');
357
-        }
358
-        else
359
-        {
360
-            $this->trap_data['source_ip']=$matches[1];
361
-            $this->trap_data['destination_ip']=$matches[3];
362
-            $this->trap_data['source_port']=$matches[2];
363
-            $this->trap_data['destination_port']=$matches[4];
364
-        }
365
-        
366
-        while (($vars=fgets($input_stream)) !==false)
367
-        {
368
-            $vars=chop($vars);
369
-            $ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
370
-            if ($ret_code===0 || $ret_code===false)
371
-            {
372
-                $this->logging->log('No match on trap data : '.$vars,WARN,'');
373
-            }
374
-            else
375
-            {
376
-                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'))
377
-                {
378
-                    $this->trap_data['trap_oid']=$matches[2];
379
-                }
380
-                else
381
-                {
382
-                    $object= new stdClass;
383
-                    $object->oid =$matches[1];
384
-                    $object->value = $matches[2];
385
-                    array_push($this->trap_data_ext,$object);
386
-                }
387
-            }
388
-        }
389
-        
390
-        if ($this->trap_data['trap_oid']=='unknown')
391
-        {
392
-            $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
393
-            $this->logging->log('no trap oid found',ERROR,'');
394
-        }
395
-        
396
-        // Translate oids.
397
-        
398
-        $retArray=$this->translateOID($this->trap_data['trap_oid']);
399
-        if ($retArray != null)
400
-        {
401
-            $this->trap_data['trap_name']=$retArray['trap_name'];
402
-            $this->trap_data['trap_name_mib']=$retArray['trap_name_mib'];
403
-        }
404
-        foreach ($this->trap_data_ext as $key => $val)
405
-        {
406
-            $retArray=$this->translateOID($val->oid);
407
-            if ($retArray != null)
408
-            {
409
-                $this->trap_data_ext[$key]->oid_name=$retArray['trap_name'];
410
-                $this->trap_data_ext[$key]->oid_name_mib=$retArray['trap_name_mib'];
411
-            }
412
-        }
413
-        
414
-        
415
-        $this->trap_data['status']= 'waiting';
416
-        
417
-        return $this->trap_data;
418
-    }
419
-    
420
-    /**
421
-     * Translate oid into array(MIB,Name)
422
-     * @param $oid string oid to translate
423
-     * @return mixed : null if not found or array(MIB,Name)
424
-     */
425
-    public function translateOID($oid)
426
-    {
427
-        // try from database
428
-        $db_conn=$this->trapsDB->db_connect_trap();
429
-        
430
-        $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
431
-        $this->logging->log('SQL query : '.$sql,DEBUG );
432
-        if (($ret_code=$db_conn->query($sql)) === false) {
433
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
434
-        }
435
-        $name=$ret_code->fetch();
436
-        if ($name['name'] != null)
437
-        {
438
-            return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
439
-        }
440
-        
441
-        // Also check if it is an instance of OID
442
-        $oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
443
-        
444
-        $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
445
-        $this->logging->log('SQL query : '.$sql,DEBUG );
446
-        if (($ret_code=$db_conn->query($sql)) === false) {
447
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
448
-        }
449
-        $name=$ret_code->fetch();
450
-        if ($name['name'] != null)
451
-        {
452
-            return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
453
-        }
454
-        
455
-        // Try to get oid name from snmptranslate
456
-        $translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
457
-            ' '.$oid);
458
-        $matches=array();
459
-        $ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
460
-        if ($ret_code===0 || $ret_code === false) {
461
-            return NULL;
462
-        } else {
463
-            $this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
464
-            return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
465
-        }
466
-    }
467
-    
468
-    /**
469
-     * Erase old trap records
470
-     *	@param integer $days : erase traps when more than $days old
471
-     *	@return integer : number of lines deleted
472
-     **/
473
-    public function eraseOldTraps($days=0)
474
-    {
475
-        if ($days==0)
476
-        {
477
-            if (($days=$this->getDBConfig('db_remove_days')) == null)
478
-            {
479
-                $this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
480
-                return;
481
-            }
482
-        }
483
-        $db_conn=$this->trapsDB->db_connect_trap();
484
-        $daysago = strtotime("-".$days." day");
485
-        $sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
486
-        if ($db_conn->query($sql) === false) {
487
-            $this->logging->log('Error erasing traps : '.$sql,ERROR,'');
488
-        }
489
-        $this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
490
-    }
491
-    
492
-    /** Write error to received trap database
493
-     */
494
-    public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
495
-    {
496
-        
497
-        $db_conn=$this->trapsDB->db_connect_trap();
498
-        
499
-        // add date time
500
-        $insert_col ='date_received,status';
501
-        $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
502
-        
503
-        if ($sourceIP !=null)
504
-        {
505
-            $insert_col .=',source_ip';
506
-            $insert_val .=",'". $sourceIP ."'";
507
-        }
508
-        if ($trapoid !=null)
509
-        {
510
-            $insert_col .=',trap_oid';
511
-            $insert_val .=",'". $trapoid ."'";
512
-        }
513
-        $insert_col .=',status_detail';
514
-        $insert_val .=",'". $message ."'";
515
-        
516
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
517
-        
518
-        switch ($this->trapsDB->trapDBType)
519
-        {
520
-            case 'pgsql':
521
-                $sql .= ' RETURNING id;';
522
-                $this->logging->log('sql : '.$sql,INFO);
523
-                if (($ret_code=$db_conn->query($sql)) === false) {
524
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
525
-                }
526
-                $this->logging->log('SQL insertion OK',INFO );
527
-                // Get last id to insert oid/values in secondary table
528
-                if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
138
+	}
139
+    
140
+	/**
141
+	 * Get option from array of ini file, send message if empty
142
+	 * @param string $option_array Array of ini file
143
+	 * @param string $option_category category in ini file
144
+	 * @param string $option_name name of option in category
145
+	 * @param mixed $option_var variable to fill if found, left untouched if not found
146
+	 * @param integer $log_level default 2 (warning)
147
+	 * @param string $message warning message if not found
148
+	 * @return boolean true if found, or false
149
+	 */
150
+	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
151
+	{
152
+		if (!isset($option_array[$option_category][$option_name]))
153
+		{
154
+			if ($message === null)
155
+			{
156
+				$message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
157
+			}
158
+			$this->logging->log($message,$log_level);
159
+			return false;
160
+		}
161
+		else
162
+		{
163
+			$option_var=$option_array[$option_category][$option_name];
164
+			return true;
165
+		}
166
+	}
167
+    
168
+	/**
169
+	 * Get options from ini file
170
+	 * @param array $trap_config : ini file array
171
+	 */
172
+	protected function getMainOptions($trapConfig)
173
+	{
174
+        
175
+		// Snmptranslate binary path
176
+		$this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
177
+        
178
+		// mibs path
179
+		$this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
180
+        
181
+		// icinga2cmd path
182
+		$this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
183
+        
184
+		// table prefix
185
+		$this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
186
+        
187
+		// API options
188
+		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
189
+		{
190
+			$this->apiUse=true;
191
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort);
192
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername);
193
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword);
194
+		}
195
+	}
196
+    
197
+	/**
198
+	 * Create and setup database class for trap & ido (if no api) db
199
+	 * @param array $trap_config : ini file array
200
+	 */
201
+	protected function setupDatabase($trapConfig)
202
+	{
203
+		// Trap database
204
+		if (!array_key_exists('database',$trapConfig['config']))
205
+		{
206
+			$this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
207
+			return;
208
+		}
209
+		$dbTrapName=$trapConfig['config']['database'];
210
+		$this->logging->log("Found database in config file: ".$dbTrapName,INFO );
211
+        
212
+		if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
213
+		{
214
+			$this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
215
+			return;
216
+		}
217
+		if (!array_key_exists($dbTrapName,$dbConfig))
218
+		{
219
+			$this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
220
+			return;
221
+		}
222
+        
223
+		$this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
224
+        
225
+		if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
226
+        
227
+		// IDO Database
228
+		if (!array_key_exists('IDOdatabase',$trapConfig['config']))
229
+		{
230
+			$this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
231
+		}
232
+		$dbIdoName=$trapConfig['config']['IDOdatabase'];
233
+        
234
+		$this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
235
+		if (!array_key_exists($dbIdoName,$dbConfig))
236
+		{
237
+			$this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
238
+			return;
239
+		}
240
+        
241
+		$this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
242
+	}
243
+    
244
+	/**
245
+	 * Get options in database
246
+	 */
247
+	protected function getDatabaseOptions()
248
+	{
249
+		// Database options
250
+		if ($this->logSetup === false) // Only if logging was no setup in constructor
251
+		{
252
+			$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
253
+			$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
254
+			$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
255
+		}
256
+	}
257
+    
258
+	/** Set $variable to value if $element found in database config table
259
+	 * @param string $element
260
+	 * @param string $variable
261
+	 */
262
+	protected function getDBConfigIfSet($element,&$variable)
263
+	{
264
+		$value=$this->getDBConfig($element);
265
+		if ($value != null) $variable=$value;
266
+	}
267
+    
268
+	/**
269
+	 *   Get data from db_config
270
+	 *	@param $element string name of param
271
+	 *	@return mixed : value (or null)
272
+	 */
273
+	protected function getDBConfig($element)  // TODO : put this in DB class
274
+	{
275
+		$db_conn=$this->trapsDB->db_connect_trap();
276
+		$sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
277
+		if (($ret_code=$db_conn->query($sql)) === false) {
278
+			$this->logging->log('No result in query : ' . $sql,WARN,'');
279
+			return null;
280
+		}
281
+		$value=$ret_code->fetch();
282
+		if ($value != null && isset($value['value']))
283
+		{
284
+			return $value['value'];
285
+		}
286
+		return null;
287
+	}
288
+    
289
+	/** OBSOLETE Send log. Throws exception on critical error
290
+	 *	@param	string $message Message to log
291
+	 *	@param	int $level 1=critical 2=warning 3=trace 4=debug
292
+	 *	@param  string $destination file/syslog/display
293
+	 *	@return void
294
+	 **/
295
+	public function trapLog( $message, $level, $destination ='') // OBSOLETE
296
+	{
297
+		// TODO : replace ref with $this->logging->log
298
+		$this->logging->log($message, $level, $destination);
299
+	}
300
+    
301
+	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
302
+	{
303
+		$this->logging->setLogging($debugLvl, $outputType,$outputOption);
304
+	}
305
+    
306
+	/**
307
+	 * Returns or create new IcingaAPI object
308
+	 * @return \Icinga\Module\Trapdirector\Icinga2API
309
+	 */
310
+	protected function getAPI()
311
+	{
312
+		if ($this->icinga2api == null)
313
+		{
314
+			$this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
315
+		}
316
+		return $this->icinga2api;
317
+	}
318
+    
319
+    
320
+	/**
321
+	 * read data from stream
322
+	 *	@param $stream string input stream, defaults to "php://stdin"
323
+	 *	@return mixed array trap data or exception with error
324
+	 */
325
+	public function read_trap($stream='php://stdin')
326
+	{
327
+		//Read data from snmptrapd from stdin
328
+		$input_stream=fopen($stream, 'r');
329
+        
330
+		if ($input_stream === false)
331
+		{
332
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
333
+			$this->logging->log("Error reading stdin !",ERROR,'');
334
+			return null; // note : exception thrown by logging
335
+		}
336
+        
337
+		// line 1 : host
338
+		$this->receivingHost=chop(fgets($input_stream));
339
+		if ($this->receivingHost === false)
340
+		{
341
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
342
+			$this->logging->log("Error reading Host !",ERROR,'');
343
+		}
344
+		// line 2 IP:port=>IP:port
345
+		$IP=chop(fgets($input_stream));
346
+		if ($IP === false)
347
+		{
348
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
349
+			$this->logging->log("Error reading IP !",ERROR,'');
350
+		}
351
+		$matches=array();
352
+		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
353
+		if ($ret_code===0 || $ret_code===false)
354
+		{
355
+			$this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
356
+			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
357
+		}
358
+		else
359
+		{
360
+			$this->trap_data['source_ip']=$matches[1];
361
+			$this->trap_data['destination_ip']=$matches[3];
362
+			$this->trap_data['source_port']=$matches[2];
363
+			$this->trap_data['destination_port']=$matches[4];
364
+		}
365
+        
366
+		while (($vars=fgets($input_stream)) !==false)
367
+		{
368
+			$vars=chop($vars);
369
+			$ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
370
+			if ($ret_code===0 || $ret_code===false)
371
+			{
372
+				$this->logging->log('No match on trap data : '.$vars,WARN,'');
373
+			}
374
+			else
375
+			{
376
+				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'))
377
+				{
378
+					$this->trap_data['trap_oid']=$matches[2];
379
+				}
380
+				else
381
+				{
382
+					$object= new stdClass;
383
+					$object->oid =$matches[1];
384
+					$object->value = $matches[2];
385
+					array_push($this->trap_data_ext,$object);
386
+				}
387
+			}
388
+		}
389
+        
390
+		if ($this->trap_data['trap_oid']=='unknown')
391
+		{
392
+			$this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
393
+			$this->logging->log('no trap oid found',ERROR,'');
394
+		}
395
+        
396
+		// Translate oids.
397
+        
398
+		$retArray=$this->translateOID($this->trap_data['trap_oid']);
399
+		if ($retArray != null)
400
+		{
401
+			$this->trap_data['trap_name']=$retArray['trap_name'];
402
+			$this->trap_data['trap_name_mib']=$retArray['trap_name_mib'];
403
+		}
404
+		foreach ($this->trap_data_ext as $key => $val)
405
+		{
406
+			$retArray=$this->translateOID($val->oid);
407
+			if ($retArray != null)
408
+			{
409
+				$this->trap_data_ext[$key]->oid_name=$retArray['trap_name'];
410
+				$this->trap_data_ext[$key]->oid_name_mib=$retArray['trap_name_mib'];
411
+			}
412
+		}
413
+        
414
+        
415
+		$this->trap_data['status']= 'waiting';
416
+        
417
+		return $this->trap_data;
418
+	}
419
+    
420
+	/**
421
+	 * Translate oid into array(MIB,Name)
422
+	 * @param $oid string oid to translate
423
+	 * @return mixed : null if not found or array(MIB,Name)
424
+	 */
425
+	public function translateOID($oid)
426
+	{
427
+		// try from database
428
+		$db_conn=$this->trapsDB->db_connect_trap();
429
+        
430
+		$sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
431
+		$this->logging->log('SQL query : '.$sql,DEBUG );
432
+		if (($ret_code=$db_conn->query($sql)) === false) {
433
+			$this->logging->log('No result in query : ' . $sql,ERROR,'');
434
+		}
435
+		$name=$ret_code->fetch();
436
+		if ($name['name'] != null)
437
+		{
438
+			return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
439
+		}
440
+        
441
+		// Also check if it is an instance of OID
442
+		$oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
443
+        
444
+		$sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
445
+		$this->logging->log('SQL query : '.$sql,DEBUG );
446
+		if (($ret_code=$db_conn->query($sql)) === false) {
447
+			$this->logging->log('No result in query : ' . $sql,ERROR,'');
448
+		}
449
+		$name=$ret_code->fetch();
450
+		if ($name['name'] != null)
451
+		{
452
+			return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
453
+		}
454
+        
455
+		// Try to get oid name from snmptranslate
456
+		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
457
+			' '.$oid);
458
+		$matches=array();
459
+		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
460
+		if ($ret_code===0 || $ret_code === false) {
461
+			return NULL;
462
+		} else {
463
+			$this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
464
+			return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
465
+		}
466
+	}
467
+    
468
+	/**
469
+	 * Erase old trap records
470
+	 *	@param integer $days : erase traps when more than $days old
471
+	 *	@return integer : number of lines deleted
472
+	 **/
473
+	public function eraseOldTraps($days=0)
474
+	{
475
+		if ($days==0)
476
+		{
477
+			if (($days=$this->getDBConfig('db_remove_days')) == null)
478
+			{
479
+				$this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
480
+				return;
481
+			}
482
+		}
483
+		$db_conn=$this->trapsDB->db_connect_trap();
484
+		$daysago = strtotime("-".$days." day");
485
+		$sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
486
+		if ($db_conn->query($sql) === false) {
487
+			$this->logging->log('Error erasing traps : '.$sql,ERROR,'');
488
+		}
489
+		$this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
490
+	}
491
+    
492
+	/** Write error to received trap database
493
+	 */
494
+	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
495
+	{
496
+        
497
+		$db_conn=$this->trapsDB->db_connect_trap();
498
+        
499
+		// add date time
500
+		$insert_col ='date_received,status';
501
+		$insert_val = "'" . date("Y-m-d H:i:s")."','error'";
502
+        
503
+		if ($sourceIP !=null)
504
+		{
505
+			$insert_col .=',source_ip';
506
+			$insert_val .=",'". $sourceIP ."'";
507
+		}
508
+		if ($trapoid !=null)
509
+		{
510
+			$insert_col .=',trap_oid';
511
+			$insert_val .=",'". $trapoid ."'";
512
+		}
513
+		$insert_col .=',status_detail';
514
+		$insert_val .=",'". $message ."'";
515
+        
516
+		$sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
517
+        
518
+		switch ($this->trapsDB->trapDBType)
519
+		{
520
+			case 'pgsql':
521
+				$sql .= ' RETURNING id;';
522
+				$this->logging->log('sql : '.$sql,INFO);
523
+				if (($ret_code=$db_conn->query($sql)) === false) {
524
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
525
+				}
526
+				$this->logging->log('SQL insertion OK',INFO );
527
+				// Get last id to insert oid/values in secondary table
528
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
529 529
                     
530
-                    $this->logging->log('Erreur recuperation id',1,'');
531
-                }
532
-                if (! isset($inserted_id_ret['id'])) {
533
-                    $this->logging->log('Error getting id',1,'');
534
-                }
535
-                $this->trap_id=$inserted_id_ret['id'];
536
-                break;
537
-            case 'mysql':
538
-                $sql .= ';';
539
-                $this->logging->log('sql : '.$sql,INFO );
540
-                if ($db_conn->query($sql) === false) {
541
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
542
-                }
543
-                $this->logging->log('SQL insertion OK',INFO );
544
-                // Get last id to insert oid/values in secondary table
545
-                $sql='SELECT LAST_INSERT_ID();';
546
-                if (($ret_code=$db_conn->query($sql)) === false) {
547
-                    $this->logging->log('Erreur recuperation id',1,'');
548
-                }
530
+					$this->logging->log('Erreur recuperation id',1,'');
531
+				}
532
+				if (! isset($inserted_id_ret['id'])) {
533
+					$this->logging->log('Error getting id',1,'');
534
+				}
535
+				$this->trap_id=$inserted_id_ret['id'];
536
+				break;
537
+			case 'mysql':
538
+				$sql .= ';';
539
+				$this->logging->log('sql : '.$sql,INFO );
540
+				if ($db_conn->query($sql) === false) {
541
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
542
+				}
543
+				$this->logging->log('SQL insertion OK',INFO );
544
+				// Get last id to insert oid/values in secondary table
545
+				$sql='SELECT LAST_INSERT_ID();';
546
+				if (($ret_code=$db_conn->query($sql)) === false) {
547
+					$this->logging->log('Erreur recuperation id',1,'');
548
+				}
549 549
                 
550
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
551
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
552
-                $this->trap_id=$inserted_id;
553
-                break;
554
-            default:
555
-                $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
556
-        }
557
-        
558
-        $this->logging->log('id found: '. $this->trap_id,INFO );
559
-    }
560
-    
561
-    /** Write trap data to trap database
562
-     */
563
-    public function writeTrapToDB()
564
-    {
565
-        
566
-        // If action is ignore -> don't send t DB
567
-        if ($this->trap_to_db === false) return;
568
-        
569
-        
570
-        $db_conn=$this->trapsDB->db_connect_trap();
571
-        
572
-        $insert_col='';
573
-        $insert_val='';
574
-        // add date time
575
-        $this->trap_data['date_received'] = date("Y-m-d H:i:s");
576
-        
577
-        $firstcol=1;
578
-        foreach ($this->trap_data as $col => $val)
579
-        {
580
-            if ($firstcol==0)
581
-            {
582
-                $insert_col .=',';
583
-                $insert_val .=',';
584
-            }
585
-            $insert_col .= $col ;
586
-            $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
587
-            $firstcol=0;
588
-        }
589
-        
590
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
591
-        switch ($this->trapsDB->trapDBType)
592
-        {
593
-            case 'pgsql':
594
-                $sql .= ' RETURNING id;';
595
-                $this->logging->log('sql : '.$sql,INFO );
596
-                if (($ret_code=$db_conn->query($sql)) === false) {
597
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
598
-                }
599
-                $this->logging->log('SQL insertion OK',INFO );
600
-                // Get last id to insert oid/values in secondary table
601
-                if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
550
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
551
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
552
+				$this->trap_id=$inserted_id;
553
+				break;
554
+			default:
555
+				$this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
556
+		}
557
+        
558
+		$this->logging->log('id found: '. $this->trap_id,INFO );
559
+	}
560
+    
561
+	/** Write trap data to trap database
562
+	 */
563
+	public function writeTrapToDB()
564
+	{
565
+        
566
+		// If action is ignore -> don't send t DB
567
+		if ($this->trap_to_db === false) return;
568
+        
569
+        
570
+		$db_conn=$this->trapsDB->db_connect_trap();
571
+        
572
+		$insert_col='';
573
+		$insert_val='';
574
+		// add date time
575
+		$this->trap_data['date_received'] = date("Y-m-d H:i:s");
576
+        
577
+		$firstcol=1;
578
+		foreach ($this->trap_data as $col => $val)
579
+		{
580
+			if ($firstcol==0)
581
+			{
582
+				$insert_col .=',';
583
+				$insert_val .=',';
584
+			}
585
+			$insert_col .= $col ;
586
+			$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
587
+			$firstcol=0;
588
+		}
589
+        
590
+		$sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
591
+		switch ($this->trapsDB->trapDBType)
592
+		{
593
+			case 'pgsql':
594
+				$sql .= ' RETURNING id;';
595
+				$this->logging->log('sql : '.$sql,INFO );
596
+				if (($ret_code=$db_conn->query($sql)) === false) {
597
+					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
598
+				}
599
+				$this->logging->log('SQL insertion OK',INFO );
600
+				// Get last id to insert oid/values in secondary table
601
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
602 602
                     
603
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
604
-                }
605
-                if (! isset($inserted_id_ret['id'])) {
606
-                    $this->logging->log('Error getting id',ERROR,'');
607
-                }
608
-                $this->trap_id=$inserted_id_ret['id'];
609
-                break;
610
-            case 'mysql':
611
-                $sql .= ';';
612
-                $this->logging->log('sql : '.$sql,INFO );
613
-                if ($db_conn->query($sql) === false) {
614
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
615
-                }
616
-                $this->logging->log('SQL insertion OK',INFO );
617
-                // Get last id to insert oid/values in secondary table
618
-                $sql='SELECT LAST_INSERT_ID();';
619
-                if (($ret_code=$db_conn->query($sql)) === false) {
620
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
621
-                }
603
+					$this->logging->log('Erreur recuperation id',ERROR,'');
604
+				}
605
+				if (! isset($inserted_id_ret['id'])) {
606
+					$this->logging->log('Error getting id',ERROR,'');
607
+				}
608
+				$this->trap_id=$inserted_id_ret['id'];
609
+				break;
610
+			case 'mysql':
611
+				$sql .= ';';
612
+				$this->logging->log('sql : '.$sql,INFO );
613
+				if ($db_conn->query($sql) === false) {
614
+					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
615
+				}
616
+				$this->logging->log('SQL insertion OK',INFO );
617
+				// Get last id to insert oid/values in secondary table
618
+				$sql='SELECT LAST_INSERT_ID();';
619
+				if (($ret_code=$db_conn->query($sql)) === false) {
620
+					$this->logging->log('Erreur recuperation id',ERROR,'');
621
+				}
622 622
                 
623
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
624
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
625
-                $this->trap_id=$inserted_id;
626
-                break;
627
-            default:
628
-                $this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
629
-        }
630
-        $this->logging->log('id found: '.$this->trap_id,INFO );
631
-        
632
-        // Fill trap extended data table
633
-        foreach ($this->trap_data_ext as $value) {
634
-            // TODO : detect if trap value is encoded and decode it to UTF-8 for database
635
-            $firstcol=1;
636
-            $value->trap_id = $this->trap_id;
637
-            $insert_col='';
638
-            $insert_val='';
639
-            foreach ($value as $col => $val)
640
-            {
641
-                if ($firstcol==0)
642
-                {
643
-                    $insert_col .=',';
644
-                    $insert_val .=',';
645
-                }
646
-                $insert_col .= $col;
647
-                $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
648
-                $firstcol=0;
649
-            }
623
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
624
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
625
+				$this->trap_id=$inserted_id;
626
+				break;
627
+			default:
628
+				$this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
629
+		}
630
+		$this->logging->log('id found: '.$this->trap_id,INFO );
631
+        
632
+		// Fill trap extended data table
633
+		foreach ($this->trap_data_ext as $value) {
634
+			// TODO : detect if trap value is encoded and decode it to UTF-8 for database
635
+			$firstcol=1;
636
+			$value->trap_id = $this->trap_id;
637
+			$insert_col='';
638
+			$insert_val='';
639
+			foreach ($value as $col => $val)
640
+			{
641
+				if ($firstcol==0)
642
+				{
643
+					$insert_col .=',';
644
+					$insert_val .=',';
645
+				}
646
+				$insert_col .= $col;
647
+				$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
648
+				$firstcol=0;
649
+			}
650 650
             
651
-            $sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
651
+			$sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
652 652
             
653
-            if ($db_conn->query($sql) === false) {
654
-                $this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
655
-            }
656
-        }
657
-    }
658
-    
659
-    /** Get rules from rule database with ip and oid
660
-     *	@param $ip string ipv4 or ipv6
661
-     *	@param $oid string oid in numeric
662
-     *	@return mixed|boolean : PDO object or false
663
-     */
664
-    protected function getRules($ip,$oid)
665
-    {
666
-        $db_conn=$this->trapsDB->db_connect_trap();
667
-        // fetch rules based on IP in rule and OID
668
-        $sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
669
-        $this->logging->log('SQL query : '.$sql,DEBUG );
670
-        if (($ret_code=$db_conn->query($sql)) === false) {
671
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
672
-            return false;
673
-        }
674
-        $rules_all=$ret_code->fetchAll();
675
-        //echo "rule all :\n";print_r($rules_all);echo "\n";
676
-        $rules_ret=array();
677
-        $rule_ret_key=0;
678
-        foreach ($rules_all as $key => $rule)
679
-        {
680
-            if ($rule['ip4']==$ip || $rule['ip6']==$ip)
681
-            {
682
-                $rules_ret[$rule_ret_key]=$rules_all[$key];
683
-                //TODO : get host name by API (and check if correct in rule).
684
-                $rule_ret_key++;
685
-                continue;
686
-            }
687
-            // TODO : get hosts IP by API
688
-            if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
689
-            { // get ips of group members by oid
690
-                $db_conn2=$this->trapsDB->db_connect_ido();
691
-                $sql="SELECT m.host_object_id, a.address as ip4, a.address6 as ip6, b.name1 as host_name
653
+			if ($db_conn->query($sql) === false) {
654
+				$this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
655
+			}
656
+		}
657
+	}
658
+    
659
+	/** Get rules from rule database with ip and oid
660
+	 *	@param $ip string ipv4 or ipv6
661
+	 *	@param $oid string oid in numeric
662
+	 *	@return mixed|boolean : PDO object or false
663
+	 */
664
+	protected function getRules($ip,$oid)
665
+	{
666
+		$db_conn=$this->trapsDB->db_connect_trap();
667
+		// fetch rules based on IP in rule and OID
668
+		$sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
669
+		$this->logging->log('SQL query : '.$sql,DEBUG );
670
+		if (($ret_code=$db_conn->query($sql)) === false) {
671
+			$this->logging->log('No result in query : ' . $sql,WARN,'');
672
+			return false;
673
+		}
674
+		$rules_all=$ret_code->fetchAll();
675
+		//echo "rule all :\n";print_r($rules_all);echo "\n";
676
+		$rules_ret=array();
677
+		$rule_ret_key=0;
678
+		foreach ($rules_all as $key => $rule)
679
+		{
680
+			if ($rule['ip4']==$ip || $rule['ip6']==$ip)
681
+			{
682
+				$rules_ret[$rule_ret_key]=$rules_all[$key];
683
+				//TODO : get host name by API (and check if correct in rule).
684
+				$rule_ret_key++;
685
+				continue;
686
+			}
687
+			// TODO : get hosts IP by API
688
+			if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
689
+			{ // get ips of group members by oid
690
+				$db_conn2=$this->trapsDB->db_connect_ido();
691
+				$sql="SELECT m.host_object_id, a.address as ip4, a.address6 as ip6, b.name1 as host_name
692 692
 						FROM icinga_objects as o
693 693
 						LEFT JOIN icinga_hostgroups as h ON o.object_id=h.hostgroup_object_id
694 694
 						LEFT JOIN icinga_hostgroup_members as m ON h.hostgroup_id=m.hostgroup_id
695 695
 						LEFT JOIN icinga_hosts as a ON a.host_object_id = m.host_object_id
696 696
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
697 697
 						WHERE o.name1='".$rule['host_group_name']."';";
698
-                if (($ret_code2=$db_conn2->query($sql)) === false) {
699
-                    $this->logging->log('No result in query : ' . $sql,WARN,'');
700
-                    continue;
701
-                }
702
-                $grouphosts=$ret_code2->fetchAll();
703
-                //echo "rule grp :\n";print_r($grouphosts);echo "\n";
704
-                foreach ( $grouphosts as $host)
705
-                {
706
-                    //echo $host['ip4']."\n";
707
-                    if ($host['ip4']==$ip || $host['ip6']==$ip)
708
-                    {
709
-                        //echo "Rule added \n";
710
-                        $rules_ret[$rule_ret_key]=$rules_all[$key];
711
-                        $rules_ret[$rule_ret_key]['host_name']=$host['host_name'];
712
-                        $rule_ret_key++;
713
-                    }
714
-                }
715
-            }
716
-        }
717
-        //echo "rule rest :\n";print_r($rules_ret);echo "\n";exit(0);
718
-        return $rules_ret;
719
-    }
720
-    
721
-    /** Add rule match to rule
722
-     *	@param id int : rule id
723
-     *   @param set int : value to set
724
-     */
725
-    protected function add_rule_match($id, $set)
726
-    {
727
-        $db_conn=$this->trapsDB->db_connect_trap();
728
-        $sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
729
-        if ($db_conn->query($sql) === false) {
730
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
731
-        }
732
-    }
733
-    
734
-    /** Send SERVICE_CHECK_RESULT with icinga2cmd or API
735
-     *
736
-     * @param string $host
737
-     * @param string $service
738
-     * @param integer $state numerical staus
739
-     * @param string $display
740
-     * @returnn bool true is service check was sent without error
741
-     */
742
-    public function serviceCheckResult($host,$service,$state,$display)
743
-    {
744
-        if ($this->apiUse === false)
745
-        {
746
-            $send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
747
-                $host.';' .$service .';' . $state . ';'.$display;
748
-                $this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
698
+				if (($ret_code2=$db_conn2->query($sql)) === false) {
699
+					$this->logging->log('No result in query : ' . $sql,WARN,'');
700
+					continue;
701
+				}
702
+				$grouphosts=$ret_code2->fetchAll();
703
+				//echo "rule grp :\n";print_r($grouphosts);echo "\n";
704
+				foreach ( $grouphosts as $host)
705
+				{
706
+					//echo $host['ip4']."\n";
707
+					if ($host['ip4']==$ip || $host['ip6']==$ip)
708
+					{
709
+						//echo "Rule added \n";
710
+						$rules_ret[$rule_ret_key]=$rules_all[$key];
711
+						$rules_ret[$rule_ret_key]['host_name']=$host['host_name'];
712
+						$rule_ret_key++;
713
+					}
714
+				}
715
+			}
716
+		}
717
+		//echo "rule rest :\n";print_r($rules_ret);echo "\n";exit(0);
718
+		return $rules_ret;
719
+	}
720
+    
721
+	/** Add rule match to rule
722
+	 *	@param id int : rule id
723
+	 *   @param set int : value to set
724
+	 */
725
+	protected function add_rule_match($id, $set)
726
+	{
727
+		$db_conn=$this->trapsDB->db_connect_trap();
728
+		$sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
729
+		if ($db_conn->query($sql) === false) {
730
+			$this->logging->log('Error in update query : ' . $sql,WARN,'');
731
+		}
732
+	}
733
+    
734
+	/** Send SERVICE_CHECK_RESULT with icinga2cmd or API
735
+	 *
736
+	 * @param string $host
737
+	 * @param string $service
738
+	 * @param integer $state numerical staus
739
+	 * @param string $display
740
+	 * @returnn bool true is service check was sent without error
741
+	 */
742
+	public function serviceCheckResult($host,$service,$state,$display)
743
+	{
744
+		if ($this->apiUse === false)
745
+		{
746
+			$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
747
+				$host.';' .$service .';' . $state . ';'.$display;
748
+				$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
749 749
                 
750
-                // TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
751
-                exec('echo "'.$send.'" > ' .$this->icinga2cmd);
752
-                return true;
753
-        }
754
-        else
755
-        {
756
-            // Get perfdata if found
757
-            $matches=array();
758
-            if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
759
-            {
760
-                $display=$matches[1];
761
-                $perfdata=$matches[2];
762
-            }
763
-            else
764
-            {
765
-                $perfdata='';
766
-            }
750
+				// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
751
+				exec('echo "'.$send.'" > ' .$this->icinga2cmd);
752
+				return true;
753
+		}
754
+		else
755
+		{
756
+			// Get perfdata if found
757
+			$matches=array();
758
+			if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
759
+			{
760
+				$display=$matches[1];
761
+				$perfdata=$matches[2];
762
+			}
763
+			else
764
+			{
765
+				$perfdata='';
766
+			}
767 767
             
768
-            $api = $this->getAPI();
769
-            $api->setCredentials($this->apiUsername, $this->apiPassword);
770
-            list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
771
-            if ($retcode == false)
772
-            {
773
-                $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
774
-                return false;
775
-            }
776
-            else
777
-            {
778
-                $this->logging->log( "Sent result : " .$retmessage,INFO );
779
-                return true;
780
-            }
781
-        }
782
-    }
783
-    
784
-    public function getHostByIP($ip)
785
-    {
786
-        $api = $this->getAPI();
787
-        $api->setCredentials($this->apiUsername, $this->apiPassword);
788
-        return $api->getHostByIP($ip);
789
-    }
790
-    
791
-    /** Resolve display.
792
-     *	Changes _OID(<oid>) to value if found or text "<not in trap>"
793
-     *	@param $display string
794
-     *	@return string display
795
-     */
796
-    protected function applyDisplay($display)
797
-    {
798
-        $matches=array();
799
-        while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
800
-        {
801
-            $oid=$matches[1];
802
-            $found=0;
803
-            foreach($this->trap_data_ext as $val)
804
-            {
805
-                if ($oid == $val->oid)
806
-                {
807
-                    $val->value=preg_replace('/"/','',$val->value);
808
-                    $rep=0;
809
-                    $display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
810
-                    if ($rep==0)
811
-                    {
812
-                        $this->logging->log("Error in display",WARN,'');
813
-                        return $display;
814
-                    }
815
-                    $found=1;
816
-                    break;
817
-                }
818
-            }
819
-            if ($found==0)
820
-            {
821
-                $display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
822
-                if ($rep==0)
823
-                {
824
-                    $this->logging->log("Error in display",WARN,'');
825
-                    return $display;
826
-                }
827
-            }
828
-        }
829
-        return $display;
830
-    }
831
-    
832
-    /** Match rules for current trap and do action
833
-     */
834
-    public function applyRules()
835
-    {
836
-        $rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
837
-        
838
-        if ($rules===false || count($rules)==0)
839
-        {
840
-            $this->logging->log('No rules found for this trap',INFO );
841
-            $this->trap_data['status']='unknown';
842
-            $this->trap_to_db=true;
843
-            return;
844
-        }
845
-        //print_r($rules);
846
-        // Evaluate all rules in sequence
847
-        $this->trap_action=null;
848
-        foreach ($rules as $rule)
849
-        {
768
+			$api = $this->getAPI();
769
+			$api->setCredentials($this->apiUsername, $this->apiPassword);
770
+			list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
771
+			if ($retcode == false)
772
+			{
773
+				$this->logging->log( "Error sending result : " .$retmessage,WARN,'');
774
+				return false;
775
+			}
776
+			else
777
+			{
778
+				$this->logging->log( "Sent result : " .$retmessage,INFO );
779
+				return true;
780
+			}
781
+		}
782
+	}
783
+    
784
+	public function getHostByIP($ip)
785
+	{
786
+		$api = $this->getAPI();
787
+		$api->setCredentials($this->apiUsername, $this->apiPassword);
788
+		return $api->getHostByIP($ip);
789
+	}
790
+    
791
+	/** Resolve display.
792
+	 *	Changes _OID(<oid>) to value if found or text "<not in trap>"
793
+	 *	@param $display string
794
+	 *	@return string display
795
+	 */
796
+	protected function applyDisplay($display)
797
+	{
798
+		$matches=array();
799
+		while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
800
+		{
801
+			$oid=$matches[1];
802
+			$found=0;
803
+			foreach($this->trap_data_ext as $val)
804
+			{
805
+				if ($oid == $val->oid)
806
+				{
807
+					$val->value=preg_replace('/"/','',$val->value);
808
+					$rep=0;
809
+					$display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
810
+					if ($rep==0)
811
+					{
812
+						$this->logging->log("Error in display",WARN,'');
813
+						return $display;
814
+					}
815
+					$found=1;
816
+					break;
817
+				}
818
+			}
819
+			if ($found==0)
820
+			{
821
+				$display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
822
+				if ($rep==0)
823
+				{
824
+					$this->logging->log("Error in display",WARN,'');
825
+					return $display;
826
+				}
827
+			}
828
+		}
829
+		return $display;
830
+	}
831
+    
832
+	/** Match rules for current trap and do action
833
+	 */
834
+	public function applyRules()
835
+	{
836
+		$rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
837
+        
838
+		if ($rules===false || count($rules)==0)
839
+		{
840
+			$this->logging->log('No rules found for this trap',INFO );
841
+			$this->trap_data['status']='unknown';
842
+			$this->trap_to_db=true;
843
+			return;
844
+		}
845
+		//print_r($rules);
846
+		// Evaluate all rules in sequence
847
+		$this->trap_action=null;
848
+		foreach ($rules as $rule)
849
+		{
850 850
             
851
-            $host_name=$rule['host_name'];
852
-            $service_name=$rule['service_name'];
851
+			$host_name=$rule['host_name'];
852
+			$service_name=$rule['service_name'];
853 853
             
854
-            $display=$this->applyDisplay($rule['display']);
855
-            $this->trap_action = ($this->trap_action==null)? '' : $this->trap_action . ', ';
856
-            try
857
-            {
858
-                $this->logging->log('Rule to eval : '.$rule['rule'],INFO );
859
-                $evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trap_data_ext) ;
860
-                //->eval_rule($rule['rule']);
854
+			$display=$this->applyDisplay($rule['display']);
855
+			$this->trap_action = ($this->trap_action==null)? '' : $this->trap_action . ', ';
856
+			try
857
+			{
858
+				$this->logging->log('Rule to eval : '.$rule['rule'],INFO );
859
+				$evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trap_data_ext) ;
860
+				//->eval_rule($rule['rule']);
861 861
                 
862
-                if ($evalr == true)
863
-                {
864
-                    //$this->logging->log('rules OOK: '.print_r($rule),INFO );
865
-                    $action=$rule['action_match'];
866
-                    $this->logging->log('action OK : '.$action,INFO );
867
-                    if ($action >= 0)
868
-                    {
869
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
870
-                        {
871
-                            $this->trap_action.='Error sending status : check cmd/API';
872
-                        }
873
-                        else
874
-                        {
875
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
876
-                            $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
877
-                        }
878
-                    }
879
-                    else
880
-                    {
881
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
882
-                    }
883
-                    $this->trap_to_db=($action==-2)?false:true;
884
-                }
885
-                else
886
-                {
887
-                    //$this->logging->log('rules KOO : '.print_r($rule),INFO );
862
+				if ($evalr == true)
863
+				{
864
+					//$this->logging->log('rules OOK: '.print_r($rule),INFO );
865
+					$action=$rule['action_match'];
866
+					$this->logging->log('action OK : '.$action,INFO );
867
+					if ($action >= 0)
868
+					{
869
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
870
+						{
871
+							$this->trap_action.='Error sending status : check cmd/API';
872
+						}
873
+						else
874
+						{
875
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
876
+							$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
877
+						}
878
+					}
879
+					else
880
+					{
881
+						$this->add_rule_match($rule['id'],$rule['num_match']+1);
882
+					}
883
+					$this->trap_to_db=($action==-2)?false:true;
884
+				}
885
+				else
886
+				{
887
+					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
888 888
                     
889
-                    $action=$rule['action_nomatch'];
890
-                    $this->logging->log('action NOK : '.$action,INFO );
891
-                    if ($action >= 0)
892
-                    {
893
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
894
-                        {
895
-                            $this->trap_action.='Error sending status : check cmd/API';
896
-                        }
897
-                        else
898
-                        {
899
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
900
-                            $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
901
-                        }
902
-                    }
903
-                    else
904
-                    {
905
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
906
-                    }
907
-                    $this->trap_to_db=($action==-2)?false:true;
908
-                }
909
-                // Put name in source_name
910
-                if (!isset($this->trap_data['source_name']))
911
-                {
912
-                    $this->trap_data['source_name']=$rule['host_name'];
913
-                }
914
-                else
915
-                {
916
-                    if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
917
-                    { // only add if not present
918
-                        $this->trap_data['source_name'].=','.$rule['host_name'];
919
-                    }
920
-                }
921
-            }
922
-            catch (Exception $e)
923
-            {
924
-                $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
925
-                $this->trap_action.=' ERR : '.$e->getMessage();
926
-                $this->trap_data['status']='error';
927
-            }
889
+					$action=$rule['action_nomatch'];
890
+					$this->logging->log('action NOK : '.$action,INFO );
891
+					if ($action >= 0)
892
+					{
893
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
894
+						{
895
+							$this->trap_action.='Error sending status : check cmd/API';
896
+						}
897
+						else
898
+						{
899
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
900
+							$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
901
+						}
902
+					}
903
+					else
904
+					{
905
+						$this->add_rule_match($rule['id'],$rule['num_match']+1);
906
+					}
907
+					$this->trap_to_db=($action==-2)?false:true;
908
+				}
909
+				// Put name in source_name
910
+				if (!isset($this->trap_data['source_name']))
911
+				{
912
+					$this->trap_data['source_name']=$rule['host_name'];
913
+				}
914
+				else
915
+				{
916
+					if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
917
+					{ // only add if not present
918
+						$this->trap_data['source_name'].=','.$rule['host_name'];
919
+					}
920
+				}
921
+			}
922
+			catch (Exception $e)
923
+			{
924
+				$this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
925
+				$this->trap_action.=' ERR : '.$e->getMessage();
926
+				$this->trap_data['status']='error';
927
+			}
928 928
             
929
-        }
930
-        if ($this->trap_data['status']=='error')
931
-        {
932
-            $this->trap_to_db=true; // Always put errors in DB for the use can see
933
-        }
934
-        else
935
-        {
936
-            $this->trap_data['status']='done';
937
-        }
938
-    }
939
-    
940
-    /** Add Time a action to rule
941
-     *	@param string $time : time to process to insert in SQL
942
-     */
943
-    public function add_rule_final($time)
944
-    {
945
-        $db_conn=$this->trapsDB->db_connect_trap();
946
-        if ($this->trap_action==null)
947
-        {
948
-            $this->trap_action='No action';
949
-        }
950
-        $sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trap_action."'  WHERE (id = '".$this->trap_id."');";
951
-        if ($db_conn->query($sql) === false) {
952
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
953
-        }
954
-    }
955
-    
956
-    /*********** UTILITIES *********************/
957
-    
958
-    /** reset service to OK after time defined in rule
959
-     *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better
960
-     *	@return integer : not in use
961
-     **/
962
-    public function reset_services()
963
-    {
964
-        // Get all services not in 'ok' state
965
-        $sql_query="SELECT s.service_object_id,
929
+		}
930
+		if ($this->trap_data['status']=='error')
931
+		{
932
+			$this->trap_to_db=true; // Always put errors in DB for the use can see
933
+		}
934
+		else
935
+		{
936
+			$this->trap_data['status']='done';
937
+		}
938
+	}
939
+    
940
+	/** Add Time a action to rule
941
+	 *	@param string $time : time to process to insert in SQL
942
+	 */
943
+	public function add_rule_final($time)
944
+	{
945
+		$db_conn=$this->trapsDB->db_connect_trap();
946
+		if ($this->trap_action==null)
947
+		{
948
+			$this->trap_action='No action';
949
+		}
950
+		$sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trap_action."'  WHERE (id = '".$this->trap_id."');";
951
+		if ($db_conn->query($sql) === false) {
952
+			$this->logging->log('Error in update query : ' . $sql,WARN,'');
953
+		}
954
+	}
955
+    
956
+	/*********** UTILITIES *********************/
957
+    
958
+	/** reset service to OK after time defined in rule
959
+	 *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better
960
+	 *	@return integer : not in use
961
+	 **/
962
+	public function reset_services()
963
+	{
964
+		// Get all services not in 'ok' state
965
+		$sql_query="SELECT s.service_object_id,
966 966
 	 UNIX_TIMESTAMP(s.last_check) AS last_check,
967 967
 	s.current_state as state,
968 968
 	v.name1 as host_name,
@@ -970,43 +970,43 @@  discard block
 block discarded – undo
970 970
 	FROM icinga_servicestatus AS s
971 971
     LEFT JOIN icinga_objects as v ON s.service_object_id=v.object_id
972 972
     WHERE s.current_state != 0;";
973
-        $db_conn=$this->trapsDB->db_connect_ido();
974
-        if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
975
-            $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
976
-            return 0;
977
-        }
978
-        $services=$services_db->fetchAll();
979
-        
980
-        // Get all rules
981
-        $sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
982
-        $db_conn2=$this->trapsDB->db_connect_trap();
983
-        if (($rules_db=$db_conn2->query($sql_query)) === false) {
984
-            $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
985
-            return 0;
986
-        }
987
-        $rules=$rules_db->fetchAll();
988
-        
989
-        $now=date('U');
990
-        
991
-        $numreset=0;
992
-        foreach ($rules as $rule)
993
-        {
994
-            foreach ($services as $service)
995
-            {
996
-                if ($service['service_name'] == $rule['service_name'] &&
997
-                    $service['host_name'] == $rule['host_name'] &&
998
-                    ($service['last_check'] + $rule['revert_ok']) < $now)
999
-                {
1000
-                    $this->serviceCheckResult($service['host_name'],$service['service_name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
1001
-                    $numreset++;
1002
-                }
1003
-            }
1004
-        }
1005
-        echo "\n";
1006
-        echo $numreset . " service(s) reset to OK\n";
1007
-        return 0;
1008
-        
1009
-    }
973
+		$db_conn=$this->trapsDB->db_connect_ido();
974
+		if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
975
+			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
976
+			return 0;
977
+		}
978
+		$services=$services_db->fetchAll();
979
+        
980
+		// Get all rules
981
+		$sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
982
+		$db_conn2=$this->trapsDB->db_connect_trap();
983
+		if (($rules_db=$db_conn2->query($sql_query)) === false) {
984
+			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
985
+			return 0;
986
+		}
987
+		$rules=$rules_db->fetchAll();
988
+        
989
+		$now=date('U');
990
+        
991
+		$numreset=0;
992
+		foreach ($rules as $rule)
993
+		{
994
+			foreach ($services as $service)
995
+			{
996
+				if ($service['service_name'] == $rule['service_name'] &&
997
+					$service['host_name'] == $rule['host_name'] &&
998
+					($service['last_check'] + $rule['revert_ok']) < $now)
999
+				{
1000
+					$this->serviceCheckResult($service['host_name'],$service['service_name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
1001
+					$numreset++;
1002
+				}
1003
+			}
1004
+		}
1005
+		echo "\n";
1006
+		echo $numreset . " service(s) reset to OK\n";
1007
+		return 0;
1008
+        
1009
+	}
1010 1010
     
1011 1011
     
1012 1012
 }
1013 1013
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +197 added lines, -197 removed lines patch added patch discarded remove patch
@@ -49,13 +49,13 @@  discard block
 block discarded – undo
49 49
     
50 50
     // Logs
51 51
     /** @var Logging Logging class. */
52
-    public $logging;    //< Logging class.
52
+    public $logging; //< Logging class.
53 53
     /** @var bool true if log was setup in constructor */
54
-    protected $logSetup;   //< bool true if log was setup in constructor
54
+    protected $logSetup; //< bool true if log was setup in constructor
55 55
     
56 56
     // Databases
57 57
     /** @var Database $trapsDB  Database class*/
58
-    public $trapsDB = null;
58
+    public $trapsDB=null;
59 59
     
60 60
     // Trap received data
61 61
     protected $receivingHost;
@@ -67,15 +67,15 @@  discard block
 block discarded – undo
67 67
     protected $trap_to_db=true; //< log trap to DB
68 68
     
69 69
     /** @var Mib mib class */
70
-    public $mibClass = null;
70
+    public $mibClass=null;
71 71
     
72 72
     /** @var Rule rule class */
73
-    public $ruleClass = null;
73
+    public $ruleClass=null;
74 74
     
75 75
     /** @var Plugins plugins manager **/
76
-    public $pluginClass = null;
76
+    public $pluginClass=null;
77 77
     
78
-    function __construct($etc_dir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
78
+    function __construct($etc_dir='/etc/icingaweb2', $baseLogLevel=null, $baseLogMode='syslog', $baseLogFile='')
79 79
     {
80 80
         // Paths of ini files
81 81
         $this->icingaweb2ETC=$etc_dir;
@@ -83,10 +83,10 @@  discard block
 block discarded – undo
83 83
         $this->icingaweb2Ressources=$this->icingaweb2ETC."/resources.ini";
84 84
         
85 85
         //************* Setup logging
86
-        $this->logging = new Logging();
86
+        $this->logging=new Logging();
87 87
         if ($baseLogLevel != null)
88 88
         {
89
-            $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
89
+            $this->logging->setLogging($baseLogLevel, $baseLogMode, $baseLogFile);
90 90
             $this->logSetup=true;
91 91
         }
92 92
         else
@@ -96,14 +96,14 @@  discard block
 block discarded – undo
96 96
         $this->logging->log('Loggin started', INFO);
97 97
         
98 98
         //*************** Get options from ini files
99
-        if (! is_file($this->trapModuleConfig))
99
+        if (!is_file($this->trapModuleConfig))
100 100
         {
101 101
             throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
102 102
         }
103
-        $trapConfig=parse_ini_file($this->trapModuleConfig,true);
103
+        $trapConfig=parse_ini_file($this->trapModuleConfig, true);
104 104
         if ($trapConfig == false)
105 105
         {
106
-            $this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
106
+            $this->logging->log("Error reading ini file : ".$this->trapModuleConfig, ERROR, 'syslog');
107 107
             throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
108 108
         }
109 109
         $this->getMainOptions($trapConfig); // Get main options from ini file
@@ -117,10 +117,10 @@  discard block
 block discarded – undo
117 117
         if ($this->apiUse === true) $this->getAPI(); // Setup API
118 118
         
119 119
         //*************** Setup MIB
120
-        $this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
120
+        $this->mibClass=new Mib($this->logging, $this->trapsDB, $this->snmptranslate, $this->snmptranslate_dirs); // Create Mib class
121 121
         
122 122
         //*************** Setup Rule
123
-        $this->ruleClass = new Rule($this->logging); //< Create Rule class
123
+        $this->ruleClass=new Rule($this->logging); //< Create Rule class
124 124
         
125 125
         $this->trap_data=array(  // TODO : put this in a reset function (DAEMON_MODE)
126 126
             'source_ip'	=> 'unknown',
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
         
133 133
         //*************** Setup Plugins
134 134
         //Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
135
-        $this->pluginClass = new Plugins($this);
135
+        $this->pluginClass=new Plugins($this);
136 136
             
137 137
             
138 138
     }
@@ -147,15 +147,15 @@  discard block
 block discarded – undo
147 147
      * @param string $message warning message if not found
148 148
      * @return boolean true if found, or false
149 149
      */
150
-    protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
150
+    protected function getOptionIfSet($option_array, $option_category, $option_name, &$option_var, $log_level=2, $message=null)
151 151
     {
152 152
         if (!isset($option_array[$option_category][$option_name]))
153 153
         {
154 154
             if ($message === null)
155 155
             {
156
-                $message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
156
+                $message='No '.$option_name.' in config file: '.$this->trapModuleConfig;
157 157
             }
158
-            $this->logging->log($message,$log_level);
158
+            $this->logging->log($message, $log_level);
159 159
             return false;
160 160
         }
161 161
         else
@@ -173,24 +173,24 @@  discard block
 block discarded – undo
173 173
     {
174 174
         
175 175
         // Snmptranslate binary path
176
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
176
+        $this->getOptionIfSet($trapConfig, 'config', 'snmptranslate', $this->snmptranslate);
177 177
         
178 178
         // mibs path
179
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
179
+        $this->getOptionIfSet($trapConfig, 'config', 'snmptranslate_dirs', $this->snmptranslate_dirs);
180 180
         
181 181
         // icinga2cmd path
182
-        $this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
182
+        $this->getOptionIfSet($trapConfig, 'config', 'icingacmd', $this->icinga2cmd);
183 183
         
184 184
         // table prefix
185
-        $this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
185
+        $this->getOptionIfSet($trapConfig, 'config', 'database_prefix', $this->dbPrefix);
186 186
         
187 187
         // API options
188
-        if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
188
+        if ($this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_host', $this->apiHostname))
189 189
         {
190 190
             $this->apiUse=true;
191
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort);
192
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername);
193
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword);
191
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_port', $this->apiPort);
192
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_user', $this->apiUsername);
193
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_password', $this->apiPassword);
194 194
         }
195 195
     }
196 196
     
@@ -201,40 +201,40 @@  discard block
 block discarded – undo
201 201
     protected function setupDatabase($trapConfig)
202 202
     {
203 203
         // Trap database
204
-        if (!array_key_exists('database',$trapConfig['config']))
204
+        if (!array_key_exists('database', $trapConfig['config']))
205 205
         {
206
-            $this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
206
+            $this->logging->log("No database in config file: ".$this->trapModuleConfig, ERROR, '');
207 207
             return;
208 208
         }
209 209
         $dbTrapName=$trapConfig['config']['database'];
210
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
210
+        $this->logging->log("Found database in config file: ".$dbTrapName, INFO);
211 211
         
212
-        if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
212
+        if (($dbConfig=parse_ini_file($this->icingaweb2Ressources, true)) === false)
213 213
         {
214
-            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
214
+            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources, ERROR, '');
215 215
             return;
216 216
         }
217
-        if (!array_key_exists($dbTrapName,$dbConfig))
217
+        if (!array_key_exists($dbTrapName, $dbConfig))
218 218
         {
219
-            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
219
+            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources, ERROR, '');
220 220
             return;
221 221
         }
222 222
         
223
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
223
+        $this->trapsDB=new Database($this->logging, $dbConfig[$dbTrapName], $this->dbPrefix);
224 224
         
225 225
         if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
226 226
         
227 227
         // IDO Database
228
-        if (!array_key_exists('IDOdatabase',$trapConfig['config']))
228
+        if (!array_key_exists('IDOdatabase', $trapConfig['config']))
229 229
         {
230
-            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
230
+            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig, ERROR, '');
231 231
         }
232 232
         $dbIdoName=$trapConfig['config']['IDOdatabase'];
233 233
         
234
-        $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
235
-        if (!array_key_exists($dbIdoName,$dbConfig))
234
+        $this->logging->log("Found IDO database in config file: ".$dbIdoName, INFO);
235
+        if (!array_key_exists($dbIdoName, $dbConfig))
236 236
         {
237
-            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
237
+            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources, ERROR, '');
238 238
             return;
239 239
         }
240 240
         
@@ -249,9 +249,9 @@  discard block
 block discarded – undo
249 249
         // Database options
250 250
         if ($this->logSetup === false) // Only if logging was no setup in constructor
251 251
         {
252
-            $this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
253
-            $this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
254
-            $this->getDBConfigIfSet('log_file',$this->logging->outputFile);
252
+            $this->getDBConfigIfSet('log_level', $this->logging->debugLevel);
253
+            $this->getDBConfigIfSet('log_destination', $this->logging->outputMode);
254
+            $this->getDBConfigIfSet('log_file', $this->logging->outputFile);
255 255
         }
256 256
     }
257 257
     
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
      * @param string $element
260 260
      * @param string $variable
261 261
      */
262
-    protected function getDBConfigIfSet($element,&$variable)
262
+    protected function getDBConfigIfSet($element, &$variable)
263 263
     {
264 264
         $value=$this->getDBConfig($element);
265 265
         if ($value != null) $variable=$value;
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
         $db_conn=$this->trapsDB->db_connect_trap();
276 276
         $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
277 277
         if (($ret_code=$db_conn->query($sql)) === false) {
278
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
278
+            $this->logging->log('No result in query : '.$sql, WARN, '');
279 279
             return null;
280 280
         }
281 281
         $value=$ret_code->fetch();
@@ -292,15 +292,15 @@  discard block
 block discarded – undo
292 292
      *	@param  string $destination file/syslog/display
293 293
      *	@return void
294 294
      **/
295
-    public function trapLog( $message, $level, $destination ='') // OBSOLETE
295
+    public function trapLog($message, $level, $destination='') // OBSOLETE
296 296
     {
297 297
         // TODO : replace ref with $this->logging->log
298 298
         $this->logging->log($message, $level, $destination);
299 299
     }
300 300
     
301
-    public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
301
+    public function setLogging($debugLvl, $outputType, $outputOption=null)  // OBSOLETE
302 302
     {
303
-        $this->logging->setLogging($debugLvl, $outputType,$outputOption);
303
+        $this->logging->setLogging($debugLvl, $outputType, $outputOption);
304 304
     }
305 305
     
306 306
     /**
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
     {
312 312
         if ($this->icinga2api == null)
313 313
         {
314
-            $this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
314
+            $this->icinga2api=new Icinga2API($this->apiHostname, $this->apiPort);
315 315
         }
316 316
         return $this->icinga2api;
317 317
     }
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
         if ($input_stream === false)
331 331
         {
332 332
             $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
333
-            $this->logging->log("Error reading stdin !",ERROR,'');
333
+            $this->logging->log("Error reading stdin !", ERROR, '');
334 334
             return null; // note : exception thrown by logging
335 335
         }
336 336
         
@@ -339,21 +339,21 @@  discard block
 block discarded – undo
339 339
         if ($this->receivingHost === false)
340 340
         {
341 341
             $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
342
-            $this->logging->log("Error reading Host !",ERROR,'');
342
+            $this->logging->log("Error reading Host !", ERROR, '');
343 343
         }
344 344
         // line 2 IP:port=>IP:port
345 345
         $IP=chop(fgets($input_stream));
346 346
         if ($IP === false)
347 347
         {
348 348
             $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
349
-            $this->logging->log("Error reading IP !",ERROR,'');
349
+            $this->logging->log("Error reading IP !", ERROR, '');
350 350
         }
351 351
         $matches=array();
352
-        $ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
353
-        if ($ret_code===0 || $ret_code===false)
352
+        $ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/', $IP, $matches);
353
+        if ($ret_code === 0 || $ret_code === false)
354 354
         {
355 355
             $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
356
-            $this->logging->log('Error parsing IP : '.$IP,ERROR,'');
356
+            $this->logging->log('Error parsing IP : '.$IP, ERROR, '');
357 357
         }
358 358
         else
359 359
         {
@@ -363,34 +363,34 @@  discard block
 block discarded – undo
363 363
             $this->trap_data['destination_port']=$matches[4];
364 364
         }
365 365
         
366
-        while (($vars=fgets($input_stream)) !==false)
366
+        while (($vars=fgets($input_stream)) !== false)
367 367
         {
368 368
             $vars=chop($vars);
369
-            $ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
370
-            if ($ret_code===0 || $ret_code===false)
369
+            $ret_code=preg_match('/^([^ ]+) (.*)$/', $vars, $matches);
370
+            if ($ret_code === 0 || $ret_code === false)
371 371
             {
372
-                $this->logging->log('No match on trap data : '.$vars,WARN,'');
372
+                $this->logging->log('No match on trap data : '.$vars, WARN, '');
373 373
             }
374 374
             else
375 375
             {
376
-                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'))
376
+                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'))
377 377
                 {
378 378
                     $this->trap_data['trap_oid']=$matches[2];
379 379
                 }
380 380
                 else
381 381
                 {
382
-                    $object= new stdClass;
383
-                    $object->oid =$matches[1];
384
-                    $object->value = $matches[2];
385
-                    array_push($this->trap_data_ext,$object);
382
+                    $object=new stdClass;
383
+                    $object->oid=$matches[1];
384
+                    $object->value=$matches[2];
385
+                    array_push($this->trap_data_ext, $object);
386 386
                 }
387 387
             }
388 388
         }
389 389
         
390
-        if ($this->trap_data['trap_oid']=='unknown')
390
+        if ($this->trap_data['trap_oid'] == 'unknown')
391 391
         {
392
-            $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
393
-            $this->logging->log('no trap oid found',ERROR,'');
392
+            $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)", $this->trap_data['source_ip']);
393
+            $this->logging->log('no trap oid found', ERROR, '');
394 394
         }
395 395
         
396 396
         // Translate oids.
@@ -412,7 +412,7 @@  discard block
 block discarded – undo
412 412
         }
413 413
         
414 414
         
415
-        $this->trap_data['status']= 'waiting';
415
+        $this->trap_data['status']='waiting';
416 416
         
417 417
         return $this->trap_data;
418 418
     }
@@ -428,40 +428,40 @@  discard block
 block discarded – undo
428 428
         $db_conn=$this->trapsDB->db_connect_trap();
429 429
         
430 430
         $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
431
-        $this->logging->log('SQL query : '.$sql,DEBUG );
431
+        $this->logging->log('SQL query : '.$sql, DEBUG);
432 432
         if (($ret_code=$db_conn->query($sql)) === false) {
433
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
433
+            $this->logging->log('No result in query : '.$sql, ERROR, '');
434 434
         }
435 435
         $name=$ret_code->fetch();
436 436
         if ($name['name'] != null)
437 437
         {
438
-            return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
438
+            return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
439 439
         }
440 440
         
441 441
         // Also check if it is an instance of OID
442
-        $oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
442
+        $oid_instance=preg_replace('/\.[0-9]+$/', '', $oid);
443 443
         
444 444
         $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
445
-        $this->logging->log('SQL query : '.$sql,DEBUG );
445
+        $this->logging->log('SQL query : '.$sql, DEBUG);
446 446
         if (($ret_code=$db_conn->query($sql)) === false) {
447
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
447
+            $this->logging->log('No result in query : '.$sql, ERROR, '');
448 448
         }
449 449
         $name=$ret_code->fetch();
450 450
         if ($name['name'] != null)
451 451
         {
452
-            return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
452
+            return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
453 453
         }
454 454
         
455 455
         // Try to get oid name from snmptranslate
456
-        $translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
456
+        $translate=exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
457 457
             ' '.$oid);
458 458
         $matches=array();
459
-        $ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
460
-        if ($ret_code===0 || $ret_code === false) {
459
+        $ret_code=preg_match('/(.*)::(.*)/', $translate, $matches);
460
+        if ($ret_code === 0 || $ret_code === false) {
461 461
             return NULL;
462 462
         } else {
463
-            $this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
464
-            return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
463
+            $this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid, INFO);
464
+            return array('trap_name_mib'=>$matches[1], 'trap_name'=>$matches[2]);
465 465
         }
466 466
     }
467 467
     
@@ -472,90 +472,90 @@  discard block
 block discarded – undo
472 472
      **/
473 473
     public function eraseOldTraps($days=0)
474 474
     {
475
-        if ($days==0)
475
+        if ($days == 0)
476 476
         {
477 477
             if (($days=$this->getDBConfig('db_remove_days')) == null)
478 478
             {
479
-                $this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
479
+                $this->logging->log('No days specified & no db value : no tap erase', WARN, '');
480 480
                 return;
481 481
             }
482 482
         }
483 483
         $db_conn=$this->trapsDB->db_connect_trap();
484
-        $daysago = strtotime("-".$days." day");
485
-        $sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
484
+        $daysago=strtotime("-".$days." day");
485
+        $sql='delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s", $daysago).'\';';
486 486
         if ($db_conn->query($sql) === false) {
487
-            $this->logging->log('Error erasing traps : '.$sql,ERROR,'');
487
+            $this->logging->log('Error erasing traps : '.$sql, ERROR, '');
488 488
         }
489
-        $this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
489
+        $this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql, INFO);
490 490
     }
491 491
     
492 492
     /** Write error to received trap database
493 493
      */
494
-    public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
494
+    public function writeTrapErrorToDB($message, $sourceIP=null, $trapoid=null)
495 495
     {
496 496
         
497 497
         $db_conn=$this->trapsDB->db_connect_trap();
498 498
         
499 499
         // add date time
500
-        $insert_col ='date_received,status';
501
-        $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
500
+        $insert_col='date_received,status';
501
+        $insert_val="'".date("Y-m-d H:i:s")."','error'";
502 502
         
503
-        if ($sourceIP !=null)
503
+        if ($sourceIP != null)
504 504
         {
505
-            $insert_col .=',source_ip';
506
-            $insert_val .=",'". $sourceIP ."'";
505
+            $insert_col.=',source_ip';
506
+            $insert_val.=",'".$sourceIP."'";
507 507
         }
508
-        if ($trapoid !=null)
508
+        if ($trapoid != null)
509 509
         {
510
-            $insert_col .=',trap_oid';
511
-            $insert_val .=",'". $trapoid ."'";
510
+            $insert_col.=',trap_oid';
511
+            $insert_val.=",'".$trapoid."'";
512 512
         }
513
-        $insert_col .=',status_detail';
514
-        $insert_val .=",'". $message ."'";
513
+        $insert_col.=',status_detail';
514
+        $insert_val.=",'".$message."'";
515 515
         
516
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
516
+        $sql='INSERT INTO '.$this->dbPrefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
517 517
         
518 518
         switch ($this->trapsDB->trapDBType)
519 519
         {
520 520
             case 'pgsql':
521
-                $sql .= ' RETURNING id;';
522
-                $this->logging->log('sql : '.$sql,INFO);
521
+                $sql.=' RETURNING id;';
522
+                $this->logging->log('sql : '.$sql, INFO);
523 523
                 if (($ret_code=$db_conn->query($sql)) === false) {
524
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
524
+                    $this->logging->log('Error SQL insert : '.$sql, 1, '');
525 525
                 }
526
-                $this->logging->log('SQL insertion OK',INFO );
526
+                $this->logging->log('SQL insertion OK', INFO);
527 527
                 // Get last id to insert oid/values in secondary table
528 528
                 if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
529 529
                     
530
-                    $this->logging->log('Erreur recuperation id',1,'');
530
+                    $this->logging->log('Erreur recuperation id', 1, '');
531 531
                 }
532
-                if (! isset($inserted_id_ret['id'])) {
533
-                    $this->logging->log('Error getting id',1,'');
532
+                if (!isset($inserted_id_ret['id'])) {
533
+                    $this->logging->log('Error getting id', 1, '');
534 534
                 }
535 535
                 $this->trap_id=$inserted_id_ret['id'];
536 536
                 break;
537 537
             case 'mysql':
538
-                $sql .= ';';
539
-                $this->logging->log('sql : '.$sql,INFO );
538
+                $sql.=';';
539
+                $this->logging->log('sql : '.$sql, INFO);
540 540
                 if ($db_conn->query($sql) === false) {
541
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
541
+                    $this->logging->log('Error SQL insert : '.$sql, 1, '');
542 542
                 }
543
-                $this->logging->log('SQL insertion OK',INFO );
543
+                $this->logging->log('SQL insertion OK', INFO);
544 544
                 // Get last id to insert oid/values in secondary table
545 545
                 $sql='SELECT LAST_INSERT_ID();';
546 546
                 if (($ret_code=$db_conn->query($sql)) === false) {
547
-                    $this->logging->log('Erreur recuperation id',1,'');
547
+                    $this->logging->log('Erreur recuperation id', 1, '');
548 548
                 }
549 549
                 
550 550
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
551
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
551
+                if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
552 552
                 $this->trap_id=$inserted_id;
553 553
                 break;
554 554
             default:
555
-                $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
555
+                $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType, 1, '');
556 556
         }
557 557
         
558
-        $this->logging->log('id found: '. $this->trap_id,INFO );
558
+        $this->logging->log('id found: '.$this->trap_id, INFO);
559 559
     }
560 560
     
561 561
     /** Write trap data to trap database
@@ -572,86 +572,86 @@  discard block
 block discarded – undo
572 572
         $insert_col='';
573 573
         $insert_val='';
574 574
         // add date time
575
-        $this->trap_data['date_received'] = date("Y-m-d H:i:s");
575
+        $this->trap_data['date_received']=date("Y-m-d H:i:s");
576 576
         
577 577
         $firstcol=1;
578 578
         foreach ($this->trap_data as $col => $val)
579 579
         {
580
-            if ($firstcol==0)
580
+            if ($firstcol == 0)
581 581
             {
582
-                $insert_col .=',';
583
-                $insert_val .=',';
582
+                $insert_col.=',';
583
+                $insert_val.=',';
584 584
             }
585
-            $insert_col .= $col ;
586
-            $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
585
+            $insert_col.=$col;
586
+            $insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
587 587
             $firstcol=0;
588 588
         }
589 589
         
590
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
590
+        $sql='INSERT INTO '.$this->dbPrefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
591 591
         switch ($this->trapsDB->trapDBType)
592 592
         {
593 593
             case 'pgsql':
594
-                $sql .= ' RETURNING id;';
595
-                $this->logging->log('sql : '.$sql,INFO );
594
+                $sql.=' RETURNING id;';
595
+                $this->logging->log('sql : '.$sql, INFO);
596 596
                 if (($ret_code=$db_conn->query($sql)) === false) {
597
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
597
+                    $this->logging->log('Error SQL insert : '.$sql, ERROR, '');
598 598
                 }
599
-                $this->logging->log('SQL insertion OK',INFO );
599
+                $this->logging->log('SQL insertion OK', INFO);
600 600
                 // Get last id to insert oid/values in secondary table
601 601
                 if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
602 602
                     
603
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
603
+                    $this->logging->log('Erreur recuperation id', ERROR, '');
604 604
                 }
605
-                if (! isset($inserted_id_ret['id'])) {
606
-                    $this->logging->log('Error getting id',ERROR,'');
605
+                if (!isset($inserted_id_ret['id'])) {
606
+                    $this->logging->log('Error getting id', ERROR, '');
607 607
                 }
608 608
                 $this->trap_id=$inserted_id_ret['id'];
609 609
                 break;
610 610
             case 'mysql':
611
-                $sql .= ';';
612
-                $this->logging->log('sql : '.$sql,INFO );
611
+                $sql.=';';
612
+                $this->logging->log('sql : '.$sql, INFO);
613 613
                 if ($db_conn->query($sql) === false) {
614
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
614
+                    $this->logging->log('Error SQL insert : '.$sql, ERROR, '');
615 615
                 }
616
-                $this->logging->log('SQL insertion OK',INFO );
616
+                $this->logging->log('SQL insertion OK', INFO);
617 617
                 // Get last id to insert oid/values in secondary table
618 618
                 $sql='SELECT LAST_INSERT_ID();';
619 619
                 if (($ret_code=$db_conn->query($sql)) === false) {
620
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
620
+                    $this->logging->log('Erreur recuperation id', ERROR, '');
621 621
                 }
622 622
                 
623 623
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
624
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
624
+                if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
625 625
                 $this->trap_id=$inserted_id;
626 626
                 break;
627 627
             default:
628
-                $this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
628
+                $this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType, ERROR, '');
629 629
         }
630
-        $this->logging->log('id found: '.$this->trap_id,INFO );
630
+        $this->logging->log('id found: '.$this->trap_id, INFO);
631 631
         
632 632
         // Fill trap extended data table
633 633
         foreach ($this->trap_data_ext as $value) {
634 634
             // TODO : detect if trap value is encoded and decode it to UTF-8 for database
635 635
             $firstcol=1;
636
-            $value->trap_id = $this->trap_id;
636
+            $value->trap_id=$this->trap_id;
637 637
             $insert_col='';
638 638
             $insert_val='';
639 639
             foreach ($value as $col => $val)
640 640
             {
641
-                if ($firstcol==0)
641
+                if ($firstcol == 0)
642 642
                 {
643
-                    $insert_col .=',';
644
-                    $insert_val .=',';
643
+                    $insert_col.=',';
644
+                    $insert_val.=',';
645 645
                 }
646
-                $insert_col .= $col;
647
-                $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
646
+                $insert_col.=$col;
647
+                $insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
648 648
                 $firstcol=0;
649 649
             }
650 650
             
651
-            $sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
651
+            $sql='INSERT INTO '.$this->dbPrefix.'received_data ('.$insert_col.') VALUES ('.$insert_val.');';
652 652
             
653 653
             if ($db_conn->query($sql) === false) {
654
-                $this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
654
+                $this->logging->log('Erreur insertion data : '.$sql, WARN, '');
655 655
             }
656 656
         }
657 657
     }
@@ -661,14 +661,14 @@  discard block
 block discarded – undo
661 661
      *	@param $oid string oid in numeric
662 662
      *	@return mixed|boolean : PDO object or false
663 663
      */
664
-    protected function getRules($ip,$oid)
664
+    protected function getRules($ip, $oid)
665 665
     {
666 666
         $db_conn=$this->trapsDB->db_connect_trap();
667 667
         // fetch rules based on IP in rule and OID
668 668
         $sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
669
-        $this->logging->log('SQL query : '.$sql,DEBUG );
669
+        $this->logging->log('SQL query : '.$sql, DEBUG);
670 670
         if (($ret_code=$db_conn->query($sql)) === false) {
671
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
671
+            $this->logging->log('No result in query : '.$sql, WARN, '');
672 672
             return false;
673 673
         }
674 674
         $rules_all=$ret_code->fetchAll();
@@ -677,7 +677,7 @@  discard block
 block discarded – undo
677 677
         $rule_ret_key=0;
678 678
         foreach ($rules_all as $key => $rule)
679 679
         {
680
-            if ($rule['ip4']==$ip || $rule['ip6']==$ip)
680
+            if ($rule['ip4'] == $ip || $rule['ip6'] == $ip)
681 681
             {
682 682
                 $rules_ret[$rule_ret_key]=$rules_all[$key];
683 683
                 //TODO : get host name by API (and check if correct in rule).
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
                 continue;
686 686
             }
687 687
             // TODO : get hosts IP by API
688
-            if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
688
+            if (isset($rule['host_group_name']) && $rule['host_group_name'] != null)
689 689
             { // get ips of group members by oid
690 690
                 $db_conn2=$this->trapsDB->db_connect_ido();
691 691
                 $sql="SELECT m.host_object_id, a.address as ip4, a.address6 as ip6, b.name1 as host_name
@@ -696,15 +696,15 @@  discard block
 block discarded – undo
696 696
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
697 697
 						WHERE o.name1='".$rule['host_group_name']."';";
698 698
                 if (($ret_code2=$db_conn2->query($sql)) === false) {
699
-                    $this->logging->log('No result in query : ' . $sql,WARN,'');
699
+                    $this->logging->log('No result in query : '.$sql, WARN, '');
700 700
                     continue;
701 701
                 }
702 702
                 $grouphosts=$ret_code2->fetchAll();
703 703
                 //echo "rule grp :\n";print_r($grouphosts);echo "\n";
704
-                foreach ( $grouphosts as $host)
704
+                foreach ($grouphosts as $host)
705 705
                 {
706 706
                     //echo $host['ip4']."\n";
707
-                    if ($host['ip4']==$ip || $host['ip6']==$ip)
707
+                    if ($host['ip4'] == $ip || $host['ip6'] == $ip)
708 708
                     {
709 709
                         //echo "Rule added \n";
710 710
                         $rules_ret[$rule_ret_key]=$rules_all[$key];
@@ -727,7 +727,7 @@  discard block
 block discarded – undo
727 727
         $db_conn=$this->trapsDB->db_connect_trap();
728 728
         $sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
729 729
         if ($db_conn->query($sql) === false) {
730
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
730
+            $this->logging->log('Error in update query : '.$sql, WARN, '');
731 731
         }
732 732
     }
733 733
     
@@ -739,23 +739,23 @@  discard block
 block discarded – undo
739 739
      * @param string $display
740 740
      * @returnn bool true is service check was sent without error
741 741
      */
742
-    public function serviceCheckResult($host,$service,$state,$display)
742
+    public function serviceCheckResult($host, $service, $state, $display)
743 743
     {
744 744
         if ($this->apiUse === false)
745 745
         {
746
-            $send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
747
-                $host.';' .$service .';' . $state . ';'.$display;
748
-                $this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
746
+            $send='['.date('U').'] PROCESS_SERVICE_CHECK_RESULT;'.
747
+                $host.';'.$service.';'.$state.';'.$display;
748
+                $this->logging->log($send." : to : ".$this->icinga2cmd, INFO);
749 749
                 
750 750
                 // TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
751
-                exec('echo "'.$send.'" > ' .$this->icinga2cmd);
751
+                exec('echo "'.$send.'" > '.$this->icinga2cmd);
752 752
                 return true;
753 753
         }
754 754
         else
755 755
         {
756 756
             // Get perfdata if found
757 757
             $matches=array();
758
-            if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
758
+            if (preg_match('/(.*)\|(.*)/', $display, $matches) == 1)
759 759
             {
760 760
                 $display=$matches[1];
761 761
                 $perfdata=$matches[2];
@@ -765,17 +765,17 @@  discard block
 block discarded – undo
765 765
                 $perfdata='';
766 766
             }
767 767
             
768
-            $api = $this->getAPI();
768
+            $api=$this->getAPI();
769 769
             $api->setCredentials($this->apiUsername, $this->apiPassword);
770
-            list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
770
+            list($retcode, $retmessage)=$api->serviceCheckResult($host, $service, $state, $display, $perfdata);
771 771
             if ($retcode == false)
772 772
             {
773
-                $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
773
+                $this->logging->log("Error sending result : ".$retmessage, WARN, '');
774 774
                 return false;
775 775
             }
776 776
             else
777 777
             {
778
-                $this->logging->log( "Sent result : " .$retmessage,INFO );
778
+                $this->logging->log("Sent result : ".$retmessage, INFO);
779 779
                 return true;
780 780
             }
781 781
         }
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
     
784 784
     public function getHostByIP($ip)
785 785
     {
786
-        $api = $this->getAPI();
786
+        $api=$this->getAPI();
787 787
         $api->setCredentials($this->apiUsername, $this->apiPassword);
788 788
         return $api->getHostByIP($ip);
789 789
     }
@@ -796,32 +796,32 @@  discard block
 block discarded – undo
796 796
     protected function applyDisplay($display)
797 797
     {
798 798
         $matches=array();
799
-        while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
799
+        while (preg_match('/_OID\(([0-9\.]+)\)/', $display, $matches) == 1)
800 800
         {
801 801
             $oid=$matches[1];
802 802
             $found=0;
803
-            foreach($this->trap_data_ext as $val)
803
+            foreach ($this->trap_data_ext as $val)
804 804
             {
805 805
                 if ($oid == $val->oid)
806 806
                 {
807
-                    $val->value=preg_replace('/"/','',$val->value);
807
+                    $val->value=preg_replace('/"/', '', $val->value);
808 808
                     $rep=0;
809
-                    $display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
810
-                    if ($rep==0)
809
+                    $display=preg_replace('/_OID\('.$oid.'\)/', $val->value, $display, -1, $rep);
810
+                    if ($rep == 0)
811 811
                     {
812
-                        $this->logging->log("Error in display",WARN,'');
812
+                        $this->logging->log("Error in display", WARN, '');
813 813
                         return $display;
814 814
                     }
815 815
                     $found=1;
816 816
                     break;
817 817
                 }
818 818
             }
819
-            if ($found==0)
819
+            if ($found == 0)
820 820
             {
821
-                $display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
822
-                if ($rep==0)
821
+                $display=preg_replace('/_OID\('.$oid.'\)/', '<not in trap>', $display, -1, $rep);
822
+                if ($rep == 0)
823 823
                 {
824
-                    $this->logging->log("Error in display",WARN,'');
824
+                    $this->logging->log("Error in display", WARN, '');
825 825
                     return $display;
826 826
                 }
827 827
             }
@@ -833,11 +833,11 @@  discard block
 block discarded – undo
833 833
      */
834 834
     public function applyRules()
835 835
     {
836
-        $rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
836
+        $rules=$this->getRules($this->trap_data['source_ip'], $this->trap_data['trap_oid']);
837 837
         
838
-        if ($rules===false || count($rules)==0)
838
+        if ($rules === false || count($rules) == 0)
839 839
         {
840
-            $this->logging->log('No rules found for this trap',INFO );
840
+            $this->logging->log('No rules found for this trap', INFO);
841 841
             $this->trap_data['status']='unknown';
842 842
             $this->trap_to_db=true;
843 843
             return;
@@ -852,59 +852,59 @@  discard block
 block discarded – undo
852 852
             $service_name=$rule['service_name'];
853 853
             
854 854
             $display=$this->applyDisplay($rule['display']);
855
-            $this->trap_action = ($this->trap_action==null)? '' : $this->trap_action . ', ';
855
+            $this->trap_action=($this->trap_action == null) ? '' : $this->trap_action.', ';
856 856
             try
857 857
             {
858
-                $this->logging->log('Rule to eval : '.$rule['rule'],INFO );
859
-                $evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trap_data_ext) ;
858
+                $this->logging->log('Rule to eval : '.$rule['rule'], INFO);
859
+                $evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trap_data_ext);
860 860
                 //->eval_rule($rule['rule']);
861 861
                 
862 862
                 if ($evalr == true)
863 863
                 {
864 864
                     //$this->logging->log('rules OOK: '.print_r($rule),INFO );
865 865
                     $action=$rule['action_match'];
866
-                    $this->logging->log('action OK : '.$action,INFO );
866
+                    $this->logging->log('action OK : '.$action, INFO);
867 867
                     if ($action >= 0)
868 868
                     {
869
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
869
+                        if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
870 870
                         {
871 871
                             $this->trap_action.='Error sending status : check cmd/API';
872 872
                         }
873 873
                         else
874 874
                         {
875
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
875
+                            $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
876 876
                             $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
877 877
                         }
878 878
                     }
879 879
                     else
880 880
                     {
881
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
881
+                        $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
882 882
                     }
883
-                    $this->trap_to_db=($action==-2)?false:true;
883
+                    $this->trap_to_db=($action == -2) ?false:true;
884 884
                 }
885 885
                 else
886 886
                 {
887 887
                     //$this->logging->log('rules KOO : '.print_r($rule),INFO );
888 888
                     
889 889
                     $action=$rule['action_nomatch'];
890
-                    $this->logging->log('action NOK : '.$action,INFO );
890
+                    $this->logging->log('action NOK : '.$action, INFO);
891 891
                     if ($action >= 0)
892 892
                     {
893
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
893
+                        if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
894 894
                         {
895 895
                             $this->trap_action.='Error sending status : check cmd/API';
896 896
                         }
897 897
                         else
898 898
                         {
899
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
899
+                            $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
900 900
                             $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
901 901
                         }
902 902
                     }
903 903
                     else
904 904
                     {
905
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
905
+                        $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
906 906
                     }
907
-                    $this->trap_to_db=($action==-2)?false:true;
907
+                    $this->trap_to_db=($action == -2) ?false:true;
908 908
                 }
909 909
                 // Put name in source_name
910 910
                 if (!isset($this->trap_data['source_name']))
@@ -913,7 +913,7 @@  discard block
 block discarded – undo
913 913
                 }
914 914
                 else
915 915
                 {
916
-                    if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
916
+                    if (!preg_match('/'.$rule['host_name'].'/', $this->trap_data['source_name']))
917 917
                     { // only add if not present
918 918
                         $this->trap_data['source_name'].=','.$rule['host_name'];
919 919
                     }
@@ -921,13 +921,13 @@  discard block
 block discarded – undo
921 921
             }
922 922
             catch (Exception $e)
923 923
             {
924
-                $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
924
+                $this->logging->log('Error in rule eval : '.$e->getMessage(), WARN, '');
925 925
                 $this->trap_action.=' ERR : '.$e->getMessage();
926 926
                 $this->trap_data['status']='error';
927 927
             }
928 928
             
929 929
         }
930
-        if ($this->trap_data['status']=='error')
930
+        if ($this->trap_data['status'] == 'error')
931 931
         {
932 932
             $this->trap_to_db=true; // Always put errors in DB for the use can see
933 933
         }
@@ -943,13 +943,13 @@  discard block
 block discarded – undo
943 943
     public function add_rule_final($time)
944 944
     {
945 945
         $db_conn=$this->trapsDB->db_connect_trap();
946
-        if ($this->trap_action==null)
946
+        if ($this->trap_action == null)
947 947
         {
948 948
             $this->trap_action='No action';
949 949
         }
950 950
         $sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trap_action."'  WHERE (id = '".$this->trap_id."');";
951 951
         if ($db_conn->query($sql) === false) {
952
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
952
+            $this->logging->log('Error in update query : '.$sql, WARN, '');
953 953
         }
954 954
     }
955 955
     
@@ -972,7 +972,7 @@  discard block
 block discarded – undo
972 972
     WHERE s.current_state != 0;";
973 973
         $db_conn=$this->trapsDB->db_connect_ido();
974 974
         if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
975
-            $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
975
+            $this->logging->log('No result in query : '.$sql_query, ERROR, '');
976 976
             return 0;
977 977
         }
978 978
         $services=$services_db->fetchAll();
@@ -981,7 +981,7 @@  discard block
 block discarded – undo
981 981
         $sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
982 982
         $db_conn2=$this->trapsDB->db_connect_trap();
983 983
         if (($rules_db=$db_conn2->query($sql_query)) === false) {
984
-            $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
984
+            $this->logging->log('No result in query : '.$sql_query, ERROR, '');
985 985
             return 0;
986 986
         }
987 987
         $rules=$rules_db->fetchAll();
@@ -997,13 +997,13 @@  discard block
 block discarded – undo
997 997
                     $service['host_name'] == $rule['host_name'] &&
998 998
                     ($service['last_check'] + $rule['revert_ok']) < $now)
999 999
                 {
1000
-                    $this->serviceCheckResult($service['host_name'],$service['service_name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
1000
+                    $this->serviceCheckResult($service['host_name'], $service['service_name'], 0, 'Reset service to OK after '.$rule['revert_ok'].' seconds');
1001 1001
                     $numreset++;
1002 1002
                 }
1003 1003
             }
1004 1004
         }
1005 1005
         echo "\n";
1006
-        echo $numreset . " service(s) reset to OK\n";
1006
+        echo $numreset." service(s) reset to OK\n";
1007 1007
         return 0;
1008 1008
         
1009 1009
     }
Please login to merge, or discard this patch.
Braces   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -88,8 +88,7 @@  discard block
 block discarded – undo
88 88
         {
89 89
             $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
90 90
             $this->logSetup=true;
91
-        }
92
-        else
91
+        } else
93 92
         {
94 93
             $this->logSetup=false;
95 94
         }
@@ -114,7 +113,10 @@  discard block
 block discarded – undo
114 113
         $this->getDatabaseOptions(); // Get options in database
115 114
         
116 115
         //*************** Setup API
117
-        if ($this->apiUse === true) $this->getAPI(); // Setup API
116
+        if ($this->apiUse === true) {
117
+        	$this->getAPI();
118
+        }
119
+        // Setup API
118 120
         
119 121
         //*************** Setup MIB
120 122
         $this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
@@ -157,8 +159,7 @@  discard block
 block discarded – undo
157 159
             }
158 160
             $this->logging->log($message,$log_level);
159 161
             return false;
160
-        }
161
-        else
162
+        } else
162 163
         {
163 164
             $option_var=$option_array[$option_category][$option_name];
164 165
             return true;
@@ -222,7 +223,10 @@  discard block
 block discarded – undo
222 223
         
223 224
         $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
224 225
         
225
-        if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
226
+        if ($this->apiUse === true) {
227
+        	return;
228
+        }
229
+        // In case of API use, no IDO is necessary
226 230
         
227 231
         // IDO Database
228 232
         if (!array_key_exists('IDOdatabase',$trapConfig['config']))
@@ -247,9 +251,11 @@  discard block
 block discarded – undo
247 251
     protected function getDatabaseOptions()
248 252
     {
249 253
         // Database options
250
-        if ($this->logSetup === false) // Only if logging was no setup in constructor
254
+        if ($this->logSetup === false) {
255
+        	// Only if logging was no setup in constructor
251 256
         {
252 257
             $this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
258
+        }
253 259
             $this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
254 260
             $this->getDBConfigIfSet('log_file',$this->logging->outputFile);
255 261
         }
@@ -262,7 +268,9 @@  discard block
 block discarded – undo
262 268
     protected function getDBConfigIfSet($element,&$variable)
263 269
     {
264 270
         $value=$this->getDBConfig($element);
265
-        if ($value != null) $variable=$value;
271
+        if ($value != null) {
272
+        	$variable=$value;
273
+        }
266 274
     }
267 275
     
268 276
     /**
@@ -354,8 +362,7 @@  discard block
 block discarded – undo
354 362
         {
355 363
             $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
356 364
             $this->logging->log('Error parsing IP : '.$IP,ERROR,'');
357
-        }
358
-        else
365
+        } else
359 366
         {
360 367
             $this->trap_data['source_ip']=$matches[1];
361 368
             $this->trap_data['destination_ip']=$matches[3];
@@ -370,14 +377,12 @@  discard block
 block discarded – undo
370 377
             if ($ret_code===0 || $ret_code===false)
371 378
             {
372 379
                 $this->logging->log('No match on trap data : '.$vars,WARN,'');
373
-            }
374
-            else
380
+            } else
375 381
             {
376 382
                 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'))
377 383
                 {
378 384
                     $this->trap_data['trap_oid']=$matches[2];
379
-                }
380
-                else
385
+                } else
381 386
                 {
382 387
                     $object= new stdClass;
383 388
                     $object->oid =$matches[1];
@@ -548,7 +553,9 @@  discard block
 block discarded – undo
548 553
                 }
549 554
                 
550 555
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
551
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
556
+                if ($inserted_id==false) {
557
+                	throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
558
+                }
552 559
                 $this->trap_id=$inserted_id;
553 560
                 break;
554 561
             default:
@@ -564,7 +571,9 @@  discard block
 block discarded – undo
564 571
     {
565 572
         
566 573
         // If action is ignore -> don't send t DB
567
-        if ($this->trap_to_db === false) return;
574
+        if ($this->trap_to_db === false) {
575
+        	return;
576
+        }
568 577
         
569 578
         
570 579
         $db_conn=$this->trapsDB->db_connect_trap();
@@ -621,7 +630,9 @@  discard block
 block discarded – undo
621 630
                 }
622 631
                 
623 632
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
624
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
633
+                if ($inserted_id==false) {
634
+                	throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
635
+                }
625 636
                 $this->trap_id=$inserted_id;
626 637
                 break;
627 638
             default:
@@ -750,8 +761,7 @@  discard block
 block discarded – undo
750 761
                 // TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
751 762
                 exec('echo "'.$send.'" > ' .$this->icinga2cmd);
752 763
                 return true;
753
-        }
754
-        else
764
+        } else
755 765
         {
756 766
             // Get perfdata if found
757 767
             $matches=array();
@@ -759,8 +769,7 @@  discard block
 block discarded – undo
759 769
             {
760 770
                 $display=$matches[1];
761 771
                 $perfdata=$matches[2];
762
-            }
763
-            else
772
+            } else
764 773
             {
765 774
                 $perfdata='';
766 775
             }
@@ -772,8 +781,7 @@  discard block
 block discarded – undo
772 781
             {
773 782
                 $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
774 783
                 return false;
775
-            }
776
-            else
784
+            } else
777 785
             {
778 786
                 $this->logging->log( "Sent result : " .$retmessage,INFO );
779 787
                 return true;
@@ -869,20 +877,17 @@  discard block
 block discarded – undo
869 877
                         if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
870 878
                         {
871 879
                             $this->trap_action.='Error sending status : check cmd/API';
872
-                        }
873
-                        else
880
+                        } else
874 881
                         {
875 882
                             $this->add_rule_match($rule['id'],$rule['num_match']+1);
876 883
                             $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
877 884
                         }
878
-                    }
879
-                    else
885
+                    } else
880 886
                     {
881 887
                         $this->add_rule_match($rule['id'],$rule['num_match']+1);
882 888
                     }
883 889
                     $this->trap_to_db=($action==-2)?false:true;
884
-                }
885
-                else
890
+                } else
886 891
                 {
887 892
                     //$this->logging->log('rules KOO : '.print_r($rule),INFO );
888 893
                     
@@ -893,14 +898,12 @@  discard block
 block discarded – undo
893 898
                         if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
894 899
                         {
895 900
                             $this->trap_action.='Error sending status : check cmd/API';
896
-                        }
897
-                        else
901
+                        } else
898 902
                         {
899 903
                             $this->add_rule_match($rule['id'],$rule['num_match']+1);
900 904
                             $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
901 905
                         }
902
-                    }
903
-                    else
906
+                    } else
904 907
                     {
905 908
                         $this->add_rule_match($rule['id'],$rule['num_match']+1);
906 909
                     }
@@ -910,16 +913,14 @@  discard block
 block discarded – undo
910 913
                 if (!isset($this->trap_data['source_name']))
911 914
                 {
912 915
                     $this->trap_data['source_name']=$rule['host_name'];
913
-                }
914
-                else
916
+                } else
915 917
                 {
916 918
                     if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
917 919
                     { // only add if not present
918 920
                         $this->trap_data['source_name'].=','.$rule['host_name'];
919 921
                     }
920 922
                 }
921
-            }
922
-            catch (Exception $e)
923
+            } catch (Exception $e)
923 924
             {
924 925
                 $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
925 926
                 $this->trap_action.=' ERR : '.$e->getMessage();
@@ -930,8 +931,7 @@  discard block
 block discarded – undo
930 931
         if ($this->trap_data['status']=='error')
931 932
         {
932 933
             $this->trap_to_db=true; // Always put errors in DB for the use can see
933
-        }
934
-        else
934
+        } else
935 935
         {
936 936
             $this->trap_data['status']='done';
937 937
         }
Please login to merge, or discard this patch.
library/Trapdirector/Plugins/NetworkRule.php 2 patches
Indentation   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -17,82 +17,82 @@
 block discarded – undo
17 17
  */
18 18
 class NetworkRule extends PluginTemplate
19 19
 {        
20
-    /** @var string $description Description of plugin */
21
-    public $description='Network functions to use into rules
20
+	/** @var string $description Description of plugin */
21
+	public $description='Network functions to use into rules
22 22
 test test test';
23 23
     
24
-    /** @var array[] $functions Functions of this plugin for rule eval. 
25
-     * If no functions are declared, set to empty array
26
-    */
27
-    public $functions=array(
28
-        'inNetwork' => array( // The name of the function 
29
-            'function'      =>  'isInNetwork', // Name of the function in rules
30
-            'params'        =>  '<IP to test>,<Network IP>,<Network mask (CIDR)>', // parameters description
31
-            'description'   =>  'Test if IP is in network, ex : __inNetwork(192.168.123.5,192.168.123.0,24) returns true
24
+	/** @var array[] $functions Functions of this plugin for rule eval. 
25
+	 * If no functions are declared, set to empty array
26
+	 */
27
+	public $functions=array(
28
+		'inNetwork' => array( // The name of the function 
29
+			'function'      =>  'isInNetwork', // Name of the function in rules
30
+			'params'        =>  '<IP to test>,<Network IP>,<Network mask (CIDR)>', // parameters description
31
+			'description'   =>  'Test if IP is in network, ex : __inNetwork(192.168.123.5,192.168.123.0,24) returns true
32 32
 Does not work with IPV6' // Description (can be multiline).
33
-        )
34
-    );
33
+		)
34
+	);
35 35
     
36
-    /** @var boolean $catchAllTraps Set to true if all traps will be sent to the plugin */
37
-    public $catchAllTraps=false;
36
+	/** @var boolean $catchAllTraps Set to true if all traps will be sent to the plugin */
37
+	public $catchAllTraps=false;
38 38
     
39 39
 
40
-    /**
41
-     * Constructor. Can throw exceptions on error, but no logging at this point.
42
-     * @throws \Exception
43
-     * @return \Trapdirector\Plugins\NetworkRule
44
-     */
45
-    function __construct()
46
-    {
47
-        $this->name=basename(__FILE__,'.php');
48
-        return $this;
49
-    }
40
+	/**
41
+	 * Constructor. Can throw exceptions on error, but no logging at this point.
42
+	 * @throws \Exception
43
+	 * @return \Trapdirector\Plugins\NetworkRule
44
+	 */
45
+	function __construct()
46
+	{
47
+		$this->name=basename(__FILE__,'.php');
48
+		return $this;
49
+	}
50 50
     
51
-    /**
52
-     * 
53
-     * @param array $params Function parameters
54
-     * @throws Exception
55
-     * @return bool Evaluation 
56
-     */
57
-    public function isInNetwork(array $params) : bool
58
-    {
59
-        $this->log('Function params : ' . print_r($params,true),DEBUG);
60
-        if (count($params)!=3)
61
-        {
62
-            throw new Exception('Invalid number of parameters : ' . count($params));
63
-        }
51
+	/**
52
+	 * 
53
+	 * @param array $params Function parameters
54
+	 * @throws Exception
55
+	 * @return bool Evaluation 
56
+	 */
57
+	public function isInNetwork(array $params) : bool
58
+	{
59
+		$this->log('Function params : ' . print_r($params,true),DEBUG);
60
+		if (count($params)!=3)
61
+		{
62
+			throw new Exception('Invalid number of parameters : ' . count($params));
63
+		}
64 64
         
65
-        $ip = $params[0];
66
-        $net = $params[1];
67
-        $masq = $params[2];
65
+		$ip = $params[0];
66
+		$net = $params[1];
67
+		$masq = $params[2];
68 68
         
69
-        $this->log('#'. $ip . '# / #' . $net . '# / #' . $masq,DEBUG);
69
+		$this->log('#'. $ip . '# / #' . $net . '# / #' . $masq,DEBUG);
70 70
         
71
-        $ip2 = ip2long($ip);
72
-        $net2 = ip2long($net);
71
+		$ip2 = ip2long($ip);
72
+		$net2 = ip2long($net);
73 73
         
74
-        if ($ip2 === false )
75
-        {
76
-            $this->log('Invalid IP : #' . $ip.'#',WARN);
77
-            throw new Exception('Invalid IP');
78
-        }
79
-        if ($net2 === false)
80
-        {
81
-            $this->log('Invalid network',WARN);
82
-            throw new Exception('Invalid net');
83
-        }
84
-        if ($masq<1 || $masq > 32)
85
-        {
86
-            $this->log('Invalid masq',WARN);
87
-            throw new Exception('Invalid net masq');
88
-        }
89
-        // $range is in IP/CIDR format eg 127.0.0.1/24
74
+		if ($ip2 === false )
75
+		{
76
+			$this->log('Invalid IP : #' . $ip.'#',WARN);
77
+			throw new Exception('Invalid IP');
78
+		}
79
+		if ($net2 === false)
80
+		{
81
+			$this->log('Invalid network',WARN);
82
+			throw new Exception('Invalid net');
83
+		}
84
+		if ($masq<1 || $masq > 32)
85
+		{
86
+			$this->log('Invalid masq',WARN);
87
+			throw new Exception('Invalid net masq');
88
+		}
89
+		// $range is in IP/CIDR format eg 127.0.0.1/24
90 90
 
91
-        $masq = pow( 2, ( 32 - $masq ) ) - 1;
92
-        $masq = ~ $masq;
93
-        return ( ( $ip2 & $masq ) == ( $net2 & $masq ) );
91
+		$masq = pow( 2, ( 32 - $masq ) ) - 1;
92
+		$masq = ~ $masq;
93
+		return ( ( $ip2 & $masq ) == ( $net2 & $masq ) );
94 94
         
95
-    }
95
+	}
96 96
 }
97 97
 
98 98
 
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
      */
45 45
     function __construct()
46 46
     {
47
-        $this->name=basename(__FILE__,'.php');
47
+        $this->name=basename(__FILE__, '.php');
48 48
         return $this;
49 49
     }
50 50
     
@@ -56,41 +56,41 @@  discard block
 block discarded – undo
56 56
      */
57 57
     public function isInNetwork(array $params) : bool
58 58
     {
59
-        $this->log('Function params : ' . print_r($params,true),DEBUG);
60
-        if (count($params)!=3)
59
+        $this->log('Function params : '.print_r($params, true), DEBUG);
60
+        if (count($params) != 3)
61 61
         {
62
-            throw new Exception('Invalid number of parameters : ' . count($params));
62
+            throw new Exception('Invalid number of parameters : '.count($params));
63 63
         }
64 64
         
65
-        $ip = $params[0];
66
-        $net = $params[1];
67
-        $masq = $params[2];
65
+        $ip=$params[0];
66
+        $net=$params[1];
67
+        $masq=$params[2];
68 68
         
69
-        $this->log('#'. $ip . '# / #' . $net . '# / #' . $masq,DEBUG);
69
+        $this->log('#'.$ip.'# / #'.$net.'# / #'.$masq, DEBUG);
70 70
         
71
-        $ip2 = ip2long($ip);
72
-        $net2 = ip2long($net);
71
+        $ip2=ip2long($ip);
72
+        $net2=ip2long($net);
73 73
         
74
-        if ($ip2 === false )
74
+        if ($ip2 === false)
75 75
         {
76
-            $this->log('Invalid IP : #' . $ip.'#',WARN);
76
+            $this->log('Invalid IP : #'.$ip.'#', WARN);
77 77
             throw new Exception('Invalid IP');
78 78
         }
79 79
         if ($net2 === false)
80 80
         {
81
-            $this->log('Invalid network',WARN);
81
+            $this->log('Invalid network', WARN);
82 82
             throw new Exception('Invalid net');
83 83
         }
84
-        if ($masq<1 || $masq > 32)
84
+        if ($masq < 1 || $masq > 32)
85 85
         {
86
-            $this->log('Invalid masq',WARN);
86
+            $this->log('Invalid masq', WARN);
87 87
             throw new Exception('Invalid net masq');
88 88
         }
89 89
         // $range is in IP/CIDR format eg 127.0.0.1/24
90 90
 
91
-        $masq = pow( 2, ( 32 - $masq ) ) - 1;
92
-        $masq = ~ $masq;
93
-        return ( ( $ip2 & $masq ) == ( $net2 & $masq ) );
91
+        $masq=pow(2, (32 - $masq)) - 1;
92
+        $masq=~ $masq;
93
+        return (($ip2 & $masq) == ($net2 & $masq));
94 94
         
95 95
     }
96 96
 }
Please login to merge, or discard this patch.
application/controllers/HandlerController.php 3 patches
Indentation   +237 added lines, -238 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');  }
@@ -540,8 +539,8 @@  discard block
 block discarded – undo
540 539
 			$trapDetail=$db->fetchRow($query);
541 540
 			if ( $trapDetail == null ) 
542 541
 			{
543
-			    $trapDetail = 'NULL';
544
-			    throw new Exception('No traps was found with id = '.$trapid);
542
+				$trapDetail = 'NULL';
543
+				throw new Exception('No traps was found with id = '.$trapid);
545 544
 			}
546 545
 		}
547 546
 		catch (Exception $e)
@@ -555,9 +554,9 @@  discard block
 block discarded – undo
555 554
 	}
556 555
 
557 556
 	/** Get trap objects
558
-	*	@param integer $trapid : trap id
559
-	* 	@return array : full column in db of trap id
560
-	*/
557
+	 *	@param integer $trapid : trap id
558
+	 * 	@return array : full column in db of trap id
559
+	 */
561 560
 	protected function getTrapobjects($trapid)
562 561
 	{	
563 562
 		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
@@ -588,9 +587,9 @@  discard block
 block discarded – undo
588 587
 	}
589 588
 
590 589
 	/** Get rule detail by ruleid.
591
-	*	@param integer $ruleid int id of rule in rule table
592
-	*	@return object : column objects in db
593
-	*/
590
+	 *	@param integer $ruleid int id of rule in rule table
591
+	 *	@return object : column objects in db
592
+	 */
594 593
 	protected function getRuleDetail($ruleid) 
595 594
 	{
596 595
 		if (!preg_match('/^[0-9]+$/',$ruleid)) { throw new Exception('Invalid id');  }
@@ -617,7 +616,7 @@  discard block
 block discarded – undo
617 616
 	}
618 617
 
619 618
 	/** Setup tabs for rules 
620
-	*/
619
+	 */
621 620
 	protected function prepareTabs()
622 621
 	{
623 622
 		return $this->getTabs()->add('status', array(
Please login to merge, or discard this patch.
Spacing   +78 added lines, -78 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,19 +534,19 @@  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 ) 
541
+			if ($trapDetail == null) 
542 542
 			{
543
-			    $trapDetail = 'NULL';
543
+			    $trapDetail='NULL';
544 544
 			    throw new Exception('No traps was found with id = '.$trapid);
545 545
 			}
546 546
 		}
547 547
 		catch (Exception $e)
548 548
 		{
549
-			$this->displayExitError('Add handler : get trap detail returning : '.print_r($trapDetail,true),$e->getMessage());
549
+			$this->displayExitError('Add handler : get trap detail returning : '.print_r($trapDetail, true), $e->getMessage());
550 550
 			return;
551 551
 		}
552 552
 
@@ -560,10 +560,10 @@  discard block
 block discarded – undo
560 560
 	*/
561 561
 	protected function getTrapobjects($trapid)
562 562
 	{	
563
-		if (!preg_match('/^[0-9]+$/',$trapid)) { throw new Exception('Invalid id');  }
563
+		if (!preg_match('/^[0-9]+$/', $trapid)) { throw new Exception('Invalid id'); }
564 564
 		$queryArrayData=$this->getModuleConfig()->trapDataDetailQuery();
565 565
 		
566
-		$db = $this->getDb()->getConnection();
566
+		$db=$this->getDb()->getConnection();
567 567
 		// ***************  Get object data
568 568
 		// extract columns and titles;
569 569
 		$data_elmts=NULL;
@@ -572,15 +572,15 @@  discard block
 block discarded – undo
572 572
 		}
573 573
 		try
574 574
 		{		
575
-			$query = $db->select()
576
-				->from($this->moduleConfig->getTrapDataTableName(),$data_elmts)
577
-				->where('trap_id=?',$trapid);
575
+			$query=$db->select()
576
+				->from($this->moduleConfig->getTrapDataTableName(), $data_elmts)
577
+				->where('trap_id=?', $trapid);
578 578
 			$trapDetail=$db->fetchAll($query);
579 579
 			// if ( $trapDetail == null ) throw new Exception('No traps was found with id = '.$trapid);
580 580
 		}
581 581
 		catch (Exception $e)
582 582
 		{
583
-			$this->displayExitError('Add handler : get trap data detail : ',$e->getMessage());
583
+			$this->displayExitError('Add handler : get trap data detail : ', $e->getMessage());
584 584
 			return array();
585 585
 		}
586 586
 
@@ -593,22 +593,22 @@  discard block
 block discarded – undo
593 593
 	*/
594 594
 	protected function getRuleDetail($ruleid) 
595 595
 	{
596
-		if (!preg_match('/^[0-9]+$/',$ruleid)) { throw new Exception('Invalid id');  }
596
+		if (!preg_match('/^[0-9]+$/', $ruleid)) { throw new Exception('Invalid id'); }
597 597
 		$queryArray=$this->getModuleConfig()->ruleDetailQuery();
598 598
 		
599
-		$db = $this->getDb()->getConnection();
599
+		$db=$this->getDb()->getConnection();
600 600
 		// ***************  Get main data
601 601
 		try
602 602
 		{		
603
-			$query = $db->select()
604
-				->from($this->getModuleConfig()->getTrapRuleName(),$queryArray)
605
-				->where('id=?',$ruleid);
603
+			$query=$db->select()
604
+				->from($this->getModuleConfig()->getTrapRuleName(), $queryArray)
605
+				->where('id=?', $ruleid);
606 606
 			$ruleDetail=$db->fetchRow($query);
607
-			if ( $ruleDetail == null ) throw new Exception('No rule was found with id = '.$ruleid);
607
+			if ($ruleDetail == null) throw new Exception('No rule was found with id = '.$ruleid);
608 608
 		}
609 609
 		catch (Exception $e)
610 610
 		{
611
-			$this->displayExitError('Update handler : get rule detail',$e->getMessage());
611
+			$this->displayExitError('Update handler : get rule detail', $e->getMessage());
612 612
 			return array();
613 613
 		}
614 614
 
@@ -622,7 +622,7 @@  discard block
 block discarded – undo
622 622
 	{
623 623
 		return $this->getTabs()->add('status', array(
624 624
 			'label' => $this->translate('Traps'),
625
-			'url'   => $this->getModuleConfig()->urlPath() . '/handler')
625
+			'url'   => $this->getModuleConfig()->urlPath().'/handler')
626 626
 		);
627 627
 	} 
628 628
 	
Please login to merge, or discard this patch.
Braces   +32 added lines, -38 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;
@@ -543,8 +538,7 @@  discard block
 block discarded – undo
543 538
 			    $trapDetail = 'NULL';
544 539
 			    throw new Exception('No traps was found with id = '.$trapid);
545 540
 			}
546
-		}
547
-		catch (Exception $e)
541
+		} catch (Exception $e)
548 542
 		{
549 543
 			$this->displayExitError('Add handler : get trap detail returning : '.print_r($trapDetail,true),$e->getMessage());
550 544
 			return;
@@ -577,8 +571,7 @@  discard block
 block discarded – undo
577 571
 				->where('trap_id=?',$trapid);
578 572
 			$trapDetail=$db->fetchAll($query);
579 573
 			// if ( $trapDetail == null ) throw new Exception('No traps was found with id = '.$trapid);
580
-		}
581
-		catch (Exception $e)
574
+		} catch (Exception $e)
582 575
 		{
583 576
 			$this->displayExitError('Add handler : get trap data detail : ',$e->getMessage());
584 577
 			return array();
@@ -604,9 +597,10 @@  discard block
 block discarded – undo
604 597
 				->from($this->getModuleConfig()->getTrapRuleName(),$queryArray)
605 598
 				->where('id=?',$ruleid);
606 599
 			$ruleDetail=$db->fetchRow($query);
607
-			if ( $ruleDetail == null ) throw new Exception('No rule was found with id = '.$ruleid);
608
-		}
609
-		catch (Exception $e)
600
+			if ( $ruleDetail == null ) {
601
+				throw new Exception('No rule was found with id = '.$ruleid);
602
+			}
603
+		} catch (Exception $e)
610 604
 		{
611 605
 			$this->displayExitError('Update handler : get rule detail',$e->getMessage());
612 606
 			return array();
Please login to merge, or discard this patch.
bin/trap_in.php 3 patches
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -17,13 +17,13 @@  discard block
 block discarded – undo
17 17
 try
18 18
 {
19 19
        
20
-    $trap = new Trap($icingaweb2Etc);
21
-    //$Trap = new Trap($icingaweb2Etc,4,'display'); // For debug
22
-    //$Trap = new Trap($icingaweb2Etc,4,'syslog'); // For debug
23
-    //$Trap->setLogging(4,'syslog'); 
20
+	$trap = new Trap($icingaweb2Etc);
21
+	//$Trap = new Trap($icingaweb2Etc,4,'display'); // For debug
22
+	//$Trap = new Trap($icingaweb2Etc,4,'syslog'); // For debug
23
+	//$Trap->setLogging(4,'syslog'); 
24 24
     
25
-    // TODO : tranfer this to reset_trap cli command
26
-    $trap->eraseOldTraps();
25
+	// TODO : tranfer this to reset_trap cli command
26
+	$trap->eraseOldTraps();
27 27
 
28 28
 	$trap->read_trap('php://stdin');
29 29
 
@@ -36,15 +36,15 @@  discard block
 block discarded – undo
36 36
 }
37 37
 catch (Exception $e) 
38 38
 {
39
-    if ($trap == null)
40
-    {  // Exception in trap creation : log in display & syslog
41
-        $logging = new Logging();
42
-        $logging->log("Caught exception creating Trap class",2);
43
-    }
44
-    else
45
-    {
39
+	if ($trap == null)
40
+	{  // Exception in trap creation : log in display & syslog
41
+		$logging = new Logging();
42
+		$logging->log("Caught exception creating Trap class",2);
43
+	}
44
+	else
45
+	{
46 46
 	   $trap->trapLog("Exception : ". $e->getMessage(),2,0);
47
-    }
47
+	}
48 48
 }
49 49
 
50 50
 //end
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use Trapdirector\Trap;
5 5
 
6 6
 // start
7
-$time1 = microtime(true);
7
+$time1=microtime(true);
8 8
 
9 9
 require_once ('trap_class.php');
10 10
 
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
 try
18 18
 {
19 19
        
20
-    $trap = new Trap($icingaweb2Etc);
20
+    $trap=new Trap($icingaweb2Etc);
21 21
     //$Trap = new Trap($icingaweb2Etc,4,'display'); // For debug
22 22
     //$Trap = new Trap($icingaweb2Etc,4,'syslog'); // For debug
23 23
     //$Trap->setLogging(4,'syslog'); 
@@ -38,12 +38,12 @@  discard block
 block discarded – undo
38 38
 {
39 39
     if ($trap == null)
40 40
     {  // Exception in trap creation : log in display & syslog
41
-        $logging = new Logging();
42
-        $logging->log("Caught exception creating Trap class",2);
41
+        $logging=new Logging();
42
+        $logging->log("Caught exception creating Trap class", 2);
43 43
     }
44 44
     else
45 45
     {
46
-	   $trap->trapLog("Exception : ". $e->getMessage(),2,0);
46
+	   $trap->trapLog("Exception : ".$e->getMessage(), 2, 0);
47 47
     }
48 48
 }
49 49
 
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -33,15 +33,13 @@
 block discarded – undo
33 33
 
34 34
 	$trap->add_rule_final(microtime(true) - $time1);
35 35
 	
36
-}
37
-catch (Exception $e) 
36
+} catch (Exception $e) 
38 37
 {
39 38
     if ($trap == null)
40 39
     {  // Exception in trap creation : log in display & syslog
41 40
         $logging = new Logging();
42 41
         $logging->log("Caught exception creating Trap class",2);
43
-    }
44
-    else
42
+    } else
45 43
     {
46 44
 	   $trap->trapLog("Exception : ". $e->getMessage(),2,0);
47 45
     }
Please login to merge, or discard this patch.