Passed
Push — master ( 000f05...a0df3d )
by Patrick
02:05
created
library/Trapdirector/TrapsProcess/Mib.php 3 patches
Indentation   +455 added lines, -455 removed lines patch added patch discarded remove patch
@@ -14,57 +14,57 @@  discard block
 block discarded – undo
14 14
  */
15 15
 class Mib
16 16
 {
17
-    use \MibDatabase;
17
+	use \MibDatabase;
18 18
     
19
-    /** @var Logging $logging logging class */
20
-    protected $logging;
21
-    /** @var Database $trapsDB Database class */
22
-    protected $trapsDB;
19
+	/** @var Logging $logging logging class */
20
+	protected $logging;
21
+	/** @var Database $trapsDB Database class */
22
+	protected $trapsDB;
23 23
     
24
-    /** @var string $snmptranslate */
25
-    public $snmptranslate;
26
-    /** @var string $snmptranslateDirs */
27
-    public $snmptranslateDirs;
24
+	/** @var string $snmptranslate */
25
+	public $snmptranslate;
26
+	/** @var string $snmptranslateDirs */
27
+	public $snmptranslateDirs;
28 28
     
29
-    private $dbOidAll; //< All oid in database;
30
-    private $dbOidIndex; //< Index of oid in dbOidAll
31
-    private $objectsAll; //< output lines of snmptranslate list
32
-    private $trapObjectsIndex; //< array of traps objects (as OID)
29
+	private $dbOidAll; //< All oid in database;
30
+	private $dbOidIndex; //< Index of oid in dbOidAll
31
+	private $objectsAll; //< output lines of snmptranslate list
32
+	private $trapObjectsIndex; //< array of traps objects (as OID)
33 33
     
34
-    private $oidDesc=array(); //< $oid,$mib,$name,$type,$textConv,$dispHint,$syntax,$type_enum,$description=NULL
34
+	private $oidDesc=array(); //< $oid,$mib,$name,$type,$textConv,$dispHint,$syntax,$type_enum,$description=NULL
35 35
 
36
-    // Timing vars for update
37
-    private $timing=array();
36
+	// Timing vars for update
37
+	private $timing=array();
38 38
     
39
-    /**
40
-     * Setup Mib Class
41
-     * @param Logging $logClass : where to log
42
-     * @param Database $dbClass : Database
43
-     */
44
-    function __construct($logClass,$dbClass,$snmptrans,$snmptransdir)
45
-    {
46
-        $this->logging=$logClass;
47
-        $this->trapsDB=$dbClass;
48
-        $this->snmptranslate=$snmptrans;
49
-        $this->snmptranslateDirs=$snmptransdir;
39
+	/**
40
+	 * Setup Mib Class
41
+	 * @param Logging $logClass : where to log
42
+	 * @param Database $dbClass : Database
43
+	 */
44
+	function __construct($logClass,$dbClass,$snmptrans,$snmptransdir)
45
+	{
46
+		$this->logging=$logClass;
47
+		$this->trapsDB=$dbClass;
48
+		$this->snmptranslate=$snmptrans;
49
+		$this->snmptranslateDirs=$snmptransdir;
50 50
 
51
-    }
51
+	}
52 52
     
53
-    /**
54
-     * @return \Trapdirector\Logging
55
-     */
56
-    public function getLogging()
57
-    {
58
-        return $this->logging;
59
-    }
53
+	/**
54
+	 * @return \Trapdirector\Logging
55
+	 */
56
+	public function getLogging()
57
+	{
58
+		return $this->logging;
59
+	}
60 60
 
61
-    /**
62
-     * @return \Trapdirector\Database
63
-     */
64
-    public function getTrapsDB()
65
-    {
66
-        return $this->trapsDB;
67
-    }
61
+	/**
62
+	 * @return \Trapdirector\Database
63
+	 */
64
+	public function getTrapsDB()
65
+	{
66
+		return $this->trapsDB;
67
+	}
68 68
 
69 69
 /**
70 70
  * Get object details & mib , returns snmptranslate output
@@ -72,478 +72,478 @@  discard block
 block discarded – undo
72 72
  * @param string $trapmib : mib of trap
73 73
  * @return NULL|array : null if not found, or output of snmptranslate
74 74
  */
75
-    private function get_object_details($object,$trapmib)
76
-    {
77
-        $match=$snmptrans=array();
78
-        $retVal=0;
79
-        $this->oidDesc['mib']=$trapmib;
80
-        exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
81
-            ' -On -Td '.$this->oidDesc['mib'].'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
82
-        if ($retVal!=0)
83
-        {
84
-            // Maybe not trap mib, search with IR
85
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
86
-                ' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
87
-            if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
88
-            { // Not found -> continue with warning
89
-                $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
90
-                return null;
91
-            }
92
-            $this->oidDesc['mib']=$match[1];
75
+	private function get_object_details($object,$trapmib)
76
+	{
77
+		$match=$snmptrans=array();
78
+		$retVal=0;
79
+		$this->oidDesc['mib']=$trapmib;
80
+		exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
81
+			' -On -Td '.$this->oidDesc['mib'].'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
82
+		if ($retVal!=0)
83
+		{
84
+			// Maybe not trap mib, search with IR
85
+			exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
86
+				' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
87
+			if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
88
+			{ // Not found -> continue with warning
89
+				$this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
90
+				return null;
91
+			}
92
+			$this->oidDesc['mib']=$match[1];
93 93
             
94
-            // Do the snmptranslate again.
95
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
96
-                ' -On -Td '.$this->oidDesc['mib'].'::'.$object,$snmptrans,$retVal);
97
-            if ($retVal!=0) {
98
-                $this->logging->log('Error finding trap object : '.$this->oidDesc['mib'].'::'.$object,2,'');
99
-                return null;
100
-            }
94
+			// Do the snmptranslate again.
95
+			exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
96
+				' -On -Td '.$this->oidDesc['mib'].'::'.$object,$snmptrans,$retVal);
97
+			if ($retVal!=0) {
98
+				$this->logging->log('Error finding trap object : '.$this->oidDesc['mib'].'::'.$object,2,'');
99
+				return null;
100
+			}
101 101
             
102
-        }
103
-        return $snmptrans;
104
-    }
102
+		}
103
+		return $snmptrans;
104
+	}
105 105
 
106 106
 /**
107 107
  * Parse snmptranslate output and set  $this->oidDesc with elements 
108 108
  * @param array $snmptrans : multi line output of snmptrans
109 109
  */
110
-    private function parse_object($snmptrans)
111
-    {
112
-        $tmpdesc=''; // For multiline description
113
-        $indesc=false; // true if currently inside multiline description
114
-        $match=array();
110
+	private function parse_object($snmptrans)
111
+	{
112
+		$tmpdesc=''; // For multiline description
113
+		$indesc=false; // true if currently inside multiline description
114
+		$match=array();
115 115
         
116
-        foreach ($snmptrans as $line)
117
-        {
118
-            if ($indesc===true)
119
-            {
120
-                $line=preg_replace('/[\t ]+/',' ',$line);
121
-                if (preg_match('/(.*)"$/', $line,$match))
122
-                {
123
-                    $this->oidDesc['description'] = $tmpdesc . $match[1];
124
-                    $indesc=false;
125
-                }
126
-                $tmpdesc.=$line;
127
-                continue;
128
-            }
129
-            if (preg_match('/^\.[0-9\.]+$/', $line))
130
-            {
131
-                $this->oidDesc['oid']=$line;
132
-                continue;
133
-            }
134
-            if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
135
-            {
136
-                $this->oidDesc['syntax']=$match[1];
137
-                $this->oidDesc['type_enum']=$match[2];
138
-                continue;
139
-            }
140
-            if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
141
-            {
142
-                $this->oidDesc['syntax']=$match[1];
143
-                continue;
144
-            }
145
-            if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
146
-            {
147
-                $this->oidDesc['dispHint']=$match[1];
148
-                continue;
149
-            }
150
-            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
151
-            {
152
-                $this->oidDesc['description']=$match[1];
153
-                continue;
154
-            }
155
-            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
156
-            {
157
-                $tmpdesc=$match[1];
158
-                $indesc=true;
159
-                continue;
160
-            }
161
-            if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
162
-            {
163
-                $this->oidDesc['textconv']=$match[1];
164
-                continue;
165
-            }
166
-        }
167
-    }
116
+		foreach ($snmptrans as $line)
117
+		{
118
+			if ($indesc===true)
119
+			{
120
+				$line=preg_replace('/[\t ]+/',' ',$line);
121
+				if (preg_match('/(.*)"$/', $line,$match))
122
+				{
123
+					$this->oidDesc['description'] = $tmpdesc . $match[1];
124
+					$indesc=false;
125
+				}
126
+				$tmpdesc.=$line;
127
+				continue;
128
+			}
129
+			if (preg_match('/^\.[0-9\.]+$/', $line))
130
+			{
131
+				$this->oidDesc['oid']=$line;
132
+				continue;
133
+			}
134
+			if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
135
+			{
136
+				$this->oidDesc['syntax']=$match[1];
137
+				$this->oidDesc['type_enum']=$match[2];
138
+				continue;
139
+			}
140
+			if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
141
+			{
142
+				$this->oidDesc['syntax']=$match[1];
143
+				continue;
144
+			}
145
+			if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
146
+			{
147
+				$this->oidDesc['dispHint']=$match[1];
148
+				continue;
149
+			}
150
+			if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
151
+			{
152
+				$this->oidDesc['description']=$match[1];
153
+				continue;
154
+			}
155
+			if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
156
+			{
157
+				$tmpdesc=$match[1];
158
+				$indesc=true;
159
+				continue;
160
+			}
161
+			if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
162
+			{
163
+				$this->oidDesc['textconv']=$match[1];
164
+				continue;
165
+			}
166
+		}
167
+	}
168 168
 
169
-    /**
170
-     * create or update (with check_existing = true) objects of trap
171
-     * @param string $trapOID : trap oid
172
-     * @param string $trapmib : mib of trap
173
-     * @param array $objects : array of objects name (without MIB)
174
-     * @param bool $check_existing : check instead of create
175
-     */
176
-    public function trap_objects($trapOID,$trapmib,$objects,$check_existing)
177
-    {              
178
-        $trapId = $this->dbOidIndex[$trapOID]['id']; // Get id of trap
169
+	/**
170
+	 * create or update (with check_existing = true) objects of trap
171
+	 * @param string $trapOID : trap oid
172
+	 * @param string $trapmib : mib of trap
173
+	 * @param array $objects : array of objects name (without MIB)
174
+	 * @param bool $check_existing : check instead of create
175
+	 */
176
+	public function trap_objects($trapOID,$trapmib,$objects,$check_existing)
177
+	{              
178
+		$trapId = $this->dbOidIndex[$trapOID]['id']; // Get id of trap
179 179
         
180
-        if ($check_existing === true)
181
-        {
182
-            $dbObjects=$this->cache_db_objects($trapId);
183
-        }
180
+		if ($check_existing === true)
181
+		{
182
+			$dbObjects=$this->cache_db_objects($trapId);
183
+		}
184 184
         
185
-        foreach ($objects as $object)
186
-        {
185
+		foreach ($objects as $object)
186
+		{
187 187
             
188
-            $this->reset_oidDesc();
188
+			$this->reset_oidDesc();
189 189
             
190
-            $snmptrans=$this->get_object_details($object, $trapmib); // Get object mib & details
191
-            if ($snmptrans === null) continue; // object not found
190
+			$snmptrans=$this->get_object_details($object, $trapmib); // Get object mib & details
191
+			if ($snmptrans === null) continue; // object not found
192 192
             
193
-            $this->parse_object($snmptrans);
193
+			$this->parse_object($snmptrans);
194 194
 
195
-            $this->oidDesc['name'] = $object;
195
+			$this->oidDesc['name'] = $object;
196 196
             
197
-            $this->logging->log("Adding object ".$this->oidDesc['name']." : ".$this->oidDesc['oid']." / ".$this->oidDesc['syntax']." / ".$this->oidDesc['type_enum']." / ".$this->oidDesc['dispHint']." / ".$this->oidDesc['textconv'],DEBUG );
197
+			$this->logging->log("Adding object ".$this->oidDesc['name']." : ".$this->oidDesc['oid']." / ".$this->oidDesc['syntax']." / ".$this->oidDesc['type_enum']." / ".$this->oidDesc['dispHint']." / ".$this->oidDesc['textconv'],DEBUG );
198 198
 
199
-            // Update
200
-            $this->update_oid();
199
+			// Update
200
+			$this->update_oid();
201 201
             
202
-            if (isset($dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]))
203
-            {   // if link exists, continue
204
-                $dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]=2;
205
-                continue;
206
-            }
207
-            if ($check_existing === true)
208
-            {
209
-                // TODO : check link trap - objects exists, mark them.
210
-            }
211
-            // Associate in object table
212
-            $db_conn=$this->trapsDB->db_connect_trap();
213
-            $sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache_trap_object (trap_id,object_id) '.
214
-                'values (:trap_id, :object_id)';
215
-            $sqlQuery=$db_conn->prepare($sql);
216
-            $sqlParam=array(
217
-                ':trap_id' => $trapId,
218
-                ':object_id' => $this->dbOidIndex[$this->oidDesc['oid']]['id'],
219
-            );
202
+			if (isset($dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]))
203
+			{   // if link exists, continue
204
+				$dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]=2;
205
+				continue;
206
+			}
207
+			if ($check_existing === true)
208
+			{
209
+				// TODO : check link trap - objects exists, mark them.
210
+			}
211
+			// Associate in object table
212
+			$db_conn=$this->trapsDB->db_connect_trap();
213
+			$sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache_trap_object (trap_id,object_id) '.
214
+				'values (:trap_id, :object_id)';
215
+			$sqlQuery=$db_conn->prepare($sql);
216
+			$sqlParam=array(
217
+				':trap_id' => $trapId,
218
+				':object_id' => $this->dbOidIndex[$this->oidDesc['oid']]['id'],
219
+			);
220 220
             
221
-            if ($sqlQuery->execute($sqlParam) === false) {
222
-                $this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$this->oidDesc['oid']]['id'] ,1,'');
223
-            }
224
-        }
225
-        if ($check_existing === true)
226
-        {
227
-            // TODO : remove link trap - objects that wasn't marked.
228
-        }
221
+			if ($sqlQuery->execute($sqlParam) === false) {
222
+				$this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$this->oidDesc['oid']]['id'] ,1,'');
223
+			}
224
+		}
225
+		if ($check_existing === true)
226
+		{
227
+			// TODO : remove link trap - objects that wasn't marked.
228
+		}
229 229
         
230
-    }
230
+	}
231 231
 
232
-    private function reset_oidDesc()
233
-    {
234
-        $this->oidDesc['oid']=null;
235
-        $this->oidDesc['name']=null;
236
-        $this->oidDesc['type']=null;
237
-        $this->oidDesc['mib']=null;
238
-        $this->oidDesc['textconv']=null;
239
-        $this->oidDesc['dispHint'] =null;
240
-        $this->oidDesc['syntax']=null;
241
-        $this->oidDesc['type_enum']=null;
242
-        $this->oidDesc['description']=null;
243
-    }
232
+	private function reset_oidDesc()
233
+	{
234
+		$this->oidDesc['oid']=null;
235
+		$this->oidDesc['name']=null;
236
+		$this->oidDesc['type']=null;
237
+		$this->oidDesc['mib']=null;
238
+		$this->oidDesc['textconv']=null;
239
+		$this->oidDesc['dispHint'] =null;
240
+		$this->oidDesc['syntax']=null;
241
+		$this->oidDesc['type_enum']=null;
242
+		$this->oidDesc['description']=null;
243
+	}
244 244
     
245
-    /**
246
-     * Fills $this->objectsAll with all mibs from snmptranslate
247
-     * @return integer : number of elements 
248
-     */
249
-    private function load_mibs_snmptranslate()
250
-    {
251
-        $retVal=0;
252
-        // Get all mib objects from all mibs
253
-        $snmpCommand=$this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.' -On -Tto 2>/dev/null';
254
-        $this->logging->log('Getting all traps : '.$snmpCommand,DEBUG );
255
-        unset($this->objectsAll);
256
-        exec($snmpCommand,$this->objectsAll,$retVal);
257
-        if ($retVal!=0)
258
-        {
259
-            $this->logging->log('error executing snmptranslate',ERROR,'');
260
-        }
261
-        // Count elements to show progress
262
-        $numElements=count($this->objectsAll);
263
-        $this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements,INFO );
264
-        return $numElements;
265
-    }
245
+	/**
246
+	 * Fills $this->objectsAll with all mibs from snmptranslate
247
+	 * @return integer : number of elements 
248
+	 */
249
+	private function load_mibs_snmptranslate()
250
+	{
251
+		$retVal=0;
252
+		// Get all mib objects from all mibs
253
+		$snmpCommand=$this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.' -On -Tto 2>/dev/null';
254
+		$this->logging->log('Getting all traps : '.$snmpCommand,DEBUG );
255
+		unset($this->objectsAll);
256
+		exec($snmpCommand,$this->objectsAll,$retVal);
257
+		if ($retVal!=0)
258
+		{
259
+			$this->logging->log('error executing snmptranslate',ERROR,'');
260
+		}
261
+		// Count elements to show progress
262
+		$numElements=count($this->objectsAll);
263
+		$this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements,INFO );
264
+		return $numElements;
265
+	}
266 266
 
267
-    /**
268
-     * load all mib objects db in dbOidAll (raw) and index in dbOidIndex
269
-     */
270
-    private function load_mibs_from_db()
271
-    {
272
-        // Get all mibs from databse to have a memory index
267
+	/**
268
+	 * load all mib objects db in dbOidAll (raw) and index in dbOidIndex
269
+	 */
270
+	private function load_mibs_from_db()
271
+	{
272
+		// Get all mibs from databse to have a memory index
273 273
         
274
-        $db_conn=$this->trapsDB->db_connect_trap();
274
+		$db_conn=$this->trapsDB->db_connect_trap();
275 275
         
276
-        $sql='SELECT * from '.$this->trapsDB->dbPrefix.'mib_cache;';
277
-        $this->logging->log('SQL query : '.$sql,DEBUG );
278
-        if (($ret_code=$db_conn->query($sql)) === false) {
279
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
280
-        }
281
-        $this->dbOidAll=$ret_code->fetchAll();
282
-        $this->dbOidIndex=array();
283
-        // Create the index for db;
284
-        foreach($this->dbOidAll as $key=>$val)
285
-        {
286
-            $this->dbOidIndex[$val['oid']]['key']=$key;
287
-            $this->dbOidIndex[$val['oid']]['id']=$val['id'];
288
-        }
289
-    }
276
+		$sql='SELECT * from '.$this->trapsDB->dbPrefix.'mib_cache;';
277
+		$this->logging->log('SQL query : '.$sql,DEBUG );
278
+		if (($ret_code=$db_conn->query($sql)) === false) {
279
+			$this->logging->log('No result in query : ' . $sql,ERROR,'');
280
+		}
281
+		$this->dbOidAll=$ret_code->fetchAll();
282
+		$this->dbOidIndex=array();
283
+		// Create the index for db;
284
+		foreach($this->dbOidAll as $key=>$val)
285
+		{
286
+			$this->dbOidIndex[$val['oid']]['key']=$key;
287
+			$this->dbOidIndex[$val['oid']]['id']=$val['id'];
288
+		}
289
+	}
290 290
 
291
-    /**
292
-     * Reset all update timers & count to zero
293
-     */
294
-    private function reset_update_timers()
295
-    {
296
-        $this->timing['base_parse_time']=0;
297
-        $this->timing['base_check_time']=0;
298
-        $this->timing['type0_check_time']=0;
299
-        $this->timing['nottrap_time']=0;
300
-        $this->timing['update_time']=0;
301
-        $this->timing['objects_time']=0;
302
-        $this->timing['base_parse_num']=0;
303
-        $this->timing['base_check_num']=0;
304
-        $this->timing['type0_check_num']=0;
305
-        $this->timing['nottrap_num']=0;
306
-        $this->timing['update_num']=0;
307
-        $this->timing['objects_num']=0;
308
-        $this->timing['num_traps']=0;
309
-    }
291
+	/**
292
+	 * Reset all update timers & count to zero
293
+	 */
294
+	private function reset_update_timers()
295
+	{
296
+		$this->timing['base_parse_time']=0;
297
+		$this->timing['base_check_time']=0;
298
+		$this->timing['type0_check_time']=0;
299
+		$this->timing['nottrap_time']=0;
300
+		$this->timing['update_time']=0;
301
+		$this->timing['objects_time']=0;
302
+		$this->timing['base_parse_num']=0;
303
+		$this->timing['base_check_num']=0;
304
+		$this->timing['type0_check_num']=0;
305
+		$this->timing['nottrap_num']=0;
306
+		$this->timing['update_num']=0;
307
+		$this->timing['objects_num']=0;
308
+		$this->timing['num_traps']=0;
309
+	}
310 310
 
311
-    /**
312
-     * Detect if $this->objectsAll[$curElement] is a trap 
313
-     * @param integer $curElement
314
-     * @param bool $onlyTraps : set to false to get all and not only traps.
315
-     * @return boolean : false if it's a trap , true if not
316
-     */
317
-    private function detect_trap($curElement,$onlyTraps)
318
-    {
319
-        // Get oid or pass if not found
320
-        if (!preg_match('/^\.[0-9\.]+$/',$this->objectsAll[$curElement]))
321
-        {
322
-            $this->timing['base_parse_time'] += microtime(true) - $this->timing['base_time'];
323
-            $this->timing['base_parse_num'] ++;
324
-            return true;
325
-        }
326
-        $this->oidDesc['oid']=$this->objectsAll[$curElement];
311
+	/**
312
+	 * Detect if $this->objectsAll[$curElement] is a trap 
313
+	 * @param integer $curElement
314
+	 * @param bool $onlyTraps : set to false to get all and not only traps.
315
+	 * @return boolean : false if it's a trap , true if not
316
+	 */
317
+	private function detect_trap($curElement,$onlyTraps)
318
+	{
319
+		// Get oid or pass if not found
320
+		if (!preg_match('/^\.[0-9\.]+$/',$this->objectsAll[$curElement]))
321
+		{
322
+			$this->timing['base_parse_time'] += microtime(true) - $this->timing['base_time'];
323
+			$this->timing['base_parse_num'] ++;
324
+			return true;
325
+		}
326
+		$this->oidDesc['oid']=$this->objectsAll[$curElement];
327 327
         
328
-        // get next line
329
-        $curElement++;
330
-        $match=$snmptrans=array();
331
-        if (!preg_match('/ +([^\(]+)\(.+\) type=([0-9]+)( tc=([0-9]+))?( hint=(.+))?/',
332
-            $this->objectsAll[$curElement],$match))
333
-        {
334
-            $this->timing['base_check_time'] += microtime(true) - $this->timing['base_time'];
335
-            $this->timing['base_check_num']++;
336
-            return true;
337
-        }
328
+		// get next line
329
+		$curElement++;
330
+		$match=$snmptrans=array();
331
+		if (!preg_match('/ +([^\(]+)\(.+\) type=([0-9]+)( tc=([0-9]+))?( hint=(.+))?/',
332
+			$this->objectsAll[$curElement],$match))
333
+		{
334
+			$this->timing['base_check_time'] += microtime(true) - $this->timing['base_time'];
335
+			$this->timing['base_check_num']++;
336
+			return true;
337
+		}
338 338
         
339
-        $this->oidDesc['name']=$match[1]; // Name
340
-        $this->oidDesc['type']=$match[2]; // type (21=trap, 0: may be trap, else : not trap
339
+		$this->oidDesc['name']=$match[1]; // Name
340
+		$this->oidDesc['type']=$match[2]; // type (21=trap, 0: may be trap, else : not trap
341 341
         
342
-        if ($this->oidDesc['type']==0) // object type=0 : check if v1 trap
343
-        {
344
-            // Check if next is suboid -> in that case is cannot be a trap
345
-            if (preg_match("/^".$this->oidDesc['oid']."/",$this->objectsAll[$curElement+1]))
346
-            {
347
-                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
348
-                $this->timing['type0_check_num']++;
349
-                return true;
350
-            }
351
-            unset($snmptrans);
352
-            $retVal=0;
353
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
354
-                ' -Td '.$this->oidDesc['oid'] . ' | grep OBJECTS ',$snmptrans,$retVal);
355
-            if ($retVal!=0)
356
-            {
357
-                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
358
-                $this->timing['type0_check_num']++;
359
-                return true;
360
-            }
361
-            //echo "\n v1 trap found : $this->oidDesc['oid'] \n";
362
-            // Force as trap.
363
-            $this->oidDesc['type']=21;
364
-        }
365
-        if ($onlyTraps===true && $this->oidDesc['type']!=21) // if only traps and not a trap, continue
366
-        {
367
-            $this->timing['nottrap_time'] += microtime(true) - $this->timing['base_time'];
368
-            $this->timing['nottrap_num']++;
369
-            return true;
370
-        }
371
-        return false;
372
-    }
342
+		if ($this->oidDesc['type']==0) // object type=0 : check if v1 trap
343
+		{
344
+			// Check if next is suboid -> in that case is cannot be a trap
345
+			if (preg_match("/^".$this->oidDesc['oid']."/",$this->objectsAll[$curElement+1]))
346
+			{
347
+				$this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
348
+				$this->timing['type0_check_num']++;
349
+				return true;
350
+			}
351
+			unset($snmptrans);
352
+			$retVal=0;
353
+			exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
354
+				' -Td '.$this->oidDesc['oid'] . ' | grep OBJECTS ',$snmptrans,$retVal);
355
+			if ($retVal!=0)
356
+			{
357
+				$this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
358
+				$this->timing['type0_check_num']++;
359
+				return true;
360
+			}
361
+			//echo "\n v1 trap found : $this->oidDesc['oid'] \n";
362
+			// Force as trap.
363
+			$this->oidDesc['type']=21;
364
+		}
365
+		if ($onlyTraps===true && $this->oidDesc['type']!=21) // if only traps and not a trap, continue
366
+		{
367
+			$this->timing['nottrap_time'] += microtime(true) - $this->timing['base_time'];
368
+			$this->timing['nottrap_num']++;
369
+			return true;
370
+		}
371
+		return false;
372
+	}
373 373
    
374
-    /**
375
-     * get_trap_mib_description
376
-     * @return array|null : array of snmptranslate output or null on error
377
-    **/
378
-    private function get_trap_mib_description()
379
-    {
380
-        $retVal=0;
381
-        $match=$snmptrans=array();
382
-        exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
383
-            ' -Td '.$this->oidDesc['oid'],$snmptrans,$retVal);
384
-        if ($retVal!=0)
385
-        {
386
-            $this->logging->log('error executing snmptranslate',ERROR);
387
-            return $snmptrans;
388
-        }
374
+	/**
375
+	 * get_trap_mib_description
376
+	 * @return array|null : array of snmptranslate output or null on error
377
+	 **/
378
+	private function get_trap_mib_description()
379
+	{
380
+		$retVal=0;
381
+		$match=$snmptrans=array();
382
+		exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
383
+			' -Td '.$this->oidDesc['oid'],$snmptrans,$retVal);
384
+		if ($retVal!=0)
385
+		{
386
+			$this->logging->log('error executing snmptranslate',ERROR);
387
+			return $snmptrans;
388
+		}
389 389
         
390
-        if (!preg_match('/^(.*)::/',$snmptrans[0],$match))
391
-        {
392
-            $this->logging->log('Error getting mib from trap '.$this->oidDesc['oid'].' : ' . $snmptrans[0],ERROR);
393
-            return $snmptrans;
394
-        }
395
-        $this->oidDesc['mib']=$match[1];
390
+		if (!preg_match('/^(.*)::/',$snmptrans[0],$match))
391
+		{
392
+			$this->logging->log('Error getting mib from trap '.$this->oidDesc['oid'].' : ' . $snmptrans[0],ERROR);
393
+			return $snmptrans;
394
+		}
395
+		$this->oidDesc['mib']=$match[1];
396 396
         
397
-        $numLine=1;
398
-        while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
399
-        if (isset($snmptrans[$numLine]))
400
-        {
401
-            $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
397
+		$numLine=1;
398
+		while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
399
+		if (isset($snmptrans[$numLine]))
400
+		{
401
+			$snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
402 402
             
403
-            while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
404
-            {
405
-                $this->oidDesc['description'].=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
406
-                $numLine++;
407
-            }
408
-            if (isset($snmptrans[$numLine])) {
409
-                $this->oidDesc['description'].=preg_replace('/".*/','',$snmptrans[$numLine]);
410
-                $this->oidDesc['description']=preg_replace('/[\t ]+/',' ',$this->oidDesc['description']);
411
-            }
403
+			while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
404
+			{
405
+				$this->oidDesc['description'].=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
406
+				$numLine++;
407
+			}
408
+			if (isset($snmptrans[$numLine])) {
409
+				$this->oidDesc['description'].=preg_replace('/".*/','',$snmptrans[$numLine]);
410
+				$this->oidDesc['description']=preg_replace('/[\t ]+/',' ',$this->oidDesc['description']);
411
+			}
412 412
             
413
-        }
414
-        return $snmptrans;
415
-    }
413
+		}
414
+		return $snmptrans;
415
+	}
416 416
 
417
-    /**
418
-     * Get trap objects
419
-     * @param array $snmptrans : output of snmptranslate for TrapModuleConfig
420
-     * @return array|null : array of objects or null if not found
421
-    **/
422
-    private function get_trap_objects($snmptrans)
423
-    {
424
-        $objectName=null;
425
-        $match=array();
426
-        foreach ($snmptrans as $line)
427
-        {
428
-            if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
429
-            {
430
-                $objectName=$match[1];
431
-            }
432
-        }
433
-        if ($objectName == null)
434
-        {
435
-            $this->logging->log('No objects for ' . $this->oidDesc['oid'],DEBUG);
436
-            $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
437
-            return null;
438
-        }
417
+	/**
418
+	 * Get trap objects
419
+	 * @param array $snmptrans : output of snmptranslate for TrapModuleConfig
420
+	 * @return array|null : array of objects or null if not found
421
+	 **/
422
+	private function get_trap_objects($snmptrans)
423
+	{
424
+		$objectName=null;
425
+		$match=array();
426
+		foreach ($snmptrans as $line)
427
+		{
428
+			if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
429
+			{
430
+				$objectName=$match[1];
431
+			}
432
+		}
433
+		if ($objectName == null)
434
+		{
435
+			$this->logging->log('No objects for ' . $this->oidDesc['oid'],DEBUG);
436
+			$this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
437
+			return null;
438
+		}
439 439
         
440
-        $trapObjects=array();
441
-        while (preg_match('/ *([^ ,]+) *,* */',$objectName,$match))
442
-        {
443
-            array_push($trapObjects,$match[1]);
444
-            $objectName=preg_replace('/'.$match[0].'/','',$objectName);
445
-        }
446
-        return $trapObjects;
447
-    }
440
+		$trapObjects=array();
441
+		while (preg_match('/ *([^ ,]+) *,* */',$objectName,$match))
442
+		{
443
+			array_push($trapObjects,$match[1]);
444
+			$objectName=preg_replace('/'.$match[0].'/','',$objectName);
445
+		}
446
+		return $trapObjects;
447
+	}
448 448
     
449
-    /**
450
-     * Cache mib in database
451
-     * @param boolean $display_progress : Display progress on standard output
452
-     * @param boolean $check_change : Force check of trap params & objects
453
-     * @param boolean $onlyTraps : only cache traps and objects (true) or all (false)
454
-     * @param string $startOID : only cache under startOID (NOT IMPLEMENTED)
455
-     */
456
-    public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,$startOID='.1')
457
-    {
458
-        // Global Timing
459
-        $timeTaken = microtime(true);
449
+	/**
450
+	 * Cache mib in database
451
+	 * @param boolean $display_progress : Display progress on standard output
452
+	 * @param boolean $check_change : Force check of trap params & objects
453
+	 * @param boolean $onlyTraps : only cache traps and objects (true) or all (false)
454
+	 * @param string $startOID : only cache under startOID (NOT IMPLEMENTED)
455
+	 */
456
+	public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,$startOID='.1')
457
+	{
458
+		// Global Timing
459
+		$timeTaken = microtime(true);
460 460
         
461
-        $numElements=$this->load_mibs_snmptranslate(); // Load objectsAll
461
+		$numElements=$this->load_mibs_snmptranslate(); // Load objectsAll
462 462
         
463
-        $this->load_mibs_from_db(); // Load from db dbOidAll & dbOidIndex
463
+		$this->load_mibs_from_db(); // Load from db dbOidAll & dbOidIndex
464 464
         
465
-        $step=$basestep=$numElements/10; // output display of % done
466
-        $num_step=0;
467
-        $timeFiveSec = microtime(true); // Used for display a '.' every <n> seconds
465
+		$step=$basestep=$numElements/10; // output display of % done
466
+		$num_step=0;
467
+		$timeFiveSec = microtime(true); // Used for display a '.' every <n> seconds
468 468
         
469
-        // Create index for trap objects
470
-        $this->trapObjectsIndex=array();
469
+		// Create index for trap objects
470
+		$this->trapObjectsIndex=array();
471 471
         
472
-        // detailed timing (time_* vars)
473
-        $this->reset_update_timers();
472
+		// detailed timing (time_* vars)
473
+		$this->reset_update_timers();
474 474
         
475
-        for ($curElement=0;$curElement < $numElements;$curElement++)
476
-        {
477
-            $this->timing['base_time']= microtime(true);
478
-            if ($display_progress)
479
-            {
480
-                if ((microtime(true)-$timeFiveSec) > 2)
481
-                { // echo a . every 2 sec
482
-                    echo '.';
483
-                    $timeFiveSec = microtime(true);
484
-                }
485
-                if ($curElement>$step)
486
-                { // display progress
487
-                    $num_step++;
488
-                    $step+=$basestep;   
489
-                    echo "\n" . ($num_step*10). '% : ';
490
-                }
491
-            }
475
+		for ($curElement=0;$curElement < $numElements;$curElement++)
476
+		{
477
+			$this->timing['base_time']= microtime(true);
478
+			if ($display_progress)
479
+			{
480
+				if ((microtime(true)-$timeFiveSec) > 2)
481
+				{ // echo a . every 2 sec
482
+					echo '.';
483
+					$timeFiveSec = microtime(true);
484
+				}
485
+				if ($curElement>$step)
486
+				{ // display progress
487
+					$num_step++;
488
+					$step+=$basestep;   
489
+					echo "\n" . ($num_step*10). '% : ';
490
+				}
491
+			}
492 492
             
493
-            $this->reset_oidDesc();
494
-            if ($this->detect_trap($curElement,$onlyTraps)===true)
495
-            {
496
-                continue;
497
-            }
493
+			$this->reset_oidDesc();
494
+			if ($this->detect_trap($curElement,$onlyTraps)===true)
495
+			{
496
+				continue;
497
+			}
498 498
             
499
-            $this->timing['num_traps']++;
499
+			$this->timing['num_traps']++;
500 500
             
501
-            $this->logging->log('Found trap : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],INFO );
502
-            if ($display_progress) echo '#'; // echo a # when trap found
501
+			$this->logging->log('Found trap : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],INFO );
502
+			if ($display_progress) echo '#'; // echo a # when trap found
503 503
 
504
-            // get trap objects & source MIB
504
+			// get trap objects & source MIB
505 505
             
506
-            $snmptrans=$this->get_trap_mib_description(); // get MIB & description
506
+			$snmptrans=$this->get_trap_mib_description(); // get MIB & description
507 507
 
508 508
 
509
-            $update=$this->update_oid(); // Do update of trap.
509
+			$update=$this->update_oid(); // Do update of trap.
510 510
             
511
-            $this->timing['update_time'] += microtime(true) - $this->timing['base_time'];
512
-            $this->timing['update_num']++;
511
+			$this->timing['update_time'] += microtime(true) - $this->timing['base_time'];
512
+			$this->timing['update_num']++;
513 513
             
514
-            $this->timing['base_time']= microtime(true); // Reset to check object time
514
+			$this->timing['base_time']= microtime(true); // Reset to check object time
515 515
             
516
-            if (($update==0) && ($check_change===false))
517
-            { // Trapd didn't change & force check disabled
518
-                $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
519
-                if ($display_progress) echo "C";
520
-                continue;
521
-            }
516
+			if (($update==0) && ($check_change===false))
517
+			{ // Trapd didn't change & force check disabled
518
+				$this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
519
+				if ($display_progress) echo "C";
520
+				continue;
521
+			}
522 522
             
523
-            $trapObjects=$this->get_trap_objects($snmptrans); // Get trap objects from snmptranslate output            
524
-            if ($trapObjects == null)
525
-            {
526
-                continue;
527
-            }
523
+			$trapObjects=$this->get_trap_objects($snmptrans); // Get trap objects from snmptranslate output            
524
+			if ($trapObjects == null)
525
+			{
526
+				continue;
527
+			}
528 528
            
529
-            $this->trap_objects($this->oidDesc['oid'], $this->oidDesc['mib'], $trapObjects, false);
529
+			$this->trap_objects($this->oidDesc['oid'], $this->oidDesc['mib'], $trapObjects, false);
530 530
             
531
-            $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
532
-            $this->timing['objects_num']++;
533
-        }
531
+			$this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
532
+			$this->timing['objects_num']++;
533
+		}
534 534
         
535
-        if ($display_progress)
536
-        {
537
-            echo "\nNumber of processed traps :  ". $this->timing['num_traps'] ."\n";
538
-            echo "\nParsing : " . number_format($this->timing['base_parse_time']+$this->timing['base_check_time'],1) ." sec / " . ($this->timing['base_parse_num']+ $this->timing['base_check_num'])  . " occurences\n";
539
-            echo "Detecting traps : " . number_format($this->timing['type0_check_time']+$this->timing['nottrap_time'],1) . " sec / " . ($this->timing['type0_check_num']+$this->timing['nottrap_num']) ." occurences\n";
540
-            echo "Trap processing (".$this->timing['update_num']."): ".number_format($this->timing['update_time'],1)." sec , ";
541
-            echo "Objects processing (".$this->timing['objects_num'].") : ".number_format($this->timing['objects_time'],1)." sec \n";
535
+		if ($display_progress)
536
+		{
537
+			echo "\nNumber of processed traps :  ". $this->timing['num_traps'] ."\n";
538
+			echo "\nParsing : " . number_format($this->timing['base_parse_time']+$this->timing['base_check_time'],1) ." sec / " . ($this->timing['base_parse_num']+ $this->timing['base_check_num'])  . " occurences\n";
539
+			echo "Detecting traps : " . number_format($this->timing['type0_check_time']+$this->timing['nottrap_time'],1) . " sec / " . ($this->timing['type0_check_num']+$this->timing['nottrap_num']) ." occurences\n";
540
+			echo "Trap processing (".$this->timing['update_num']."): ".number_format($this->timing['update_time'],1)." sec , ";
541
+			echo "Objects processing (".$this->timing['objects_num'].") : ".number_format($this->timing['objects_time'],1)." sec \n";
542 542
             
543
-            $timeTaken=microtime(true) - $timeTaken;
544
-            echo "Global time : ".round($timeTaken)." seconds\n";
545
-        }
546
-    }
543
+			$timeTaken=microtime(true) - $timeTaken;
544
+			echo "Global time : ".round($timeTaken)." seconds\n";
545
+		}
546
+	}
547 547
     
548 548
     
549 549
 }
550 550
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
      * @param Logging $logClass : where to log
42 42
      * @param Database $dbClass : Database
43 43
      */
44
-    function __construct($logClass,$dbClass,$snmptrans,$snmptransdir)
44
+    function __construct($logClass, $dbClass, $snmptrans, $snmptransdir)
45 45
     {
46 46
         $this->logging=$logClass;
47 47
         $this->trapsDB=$dbClass;
@@ -72,30 +72,30 @@  discard block
 block discarded – undo
72 72
  * @param string $trapmib : mib of trap
73 73
  * @return NULL|array : null if not found, or output of snmptranslate
74 74
  */
75
-    private function get_object_details($object,$trapmib)
75
+    private function get_object_details($object, $trapmib)
76 76
     {
77 77
         $match=$snmptrans=array();
78 78
         $retVal=0;
79 79
         $this->oidDesc['mib']=$trapmib;
80
-        exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
81
-            ' -On -Td '.$this->oidDesc['mib'].'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
82
-        if ($retVal!=0)
80
+        exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslateDirs.
81
+            ' -On -Td '.$this->oidDesc['mib'].'::'.$object.' 2>/dev/null', $snmptrans, $retVal);
82
+        if ($retVal != 0)
83 83
         {
84 84
             // Maybe not trap mib, search with IR
85
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
86
-                ' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
87
-            if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
85
+            exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslateDirs.
86
+                ' -IR '.$object.' 2>/dev/null', $snmptrans, $retVal);
87
+            if ($retVal != 0 || !preg_match('/(.*)::(.*)/', $snmptrans[0], $match))
88 88
             { // Not found -> continue with warning
89
-                $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
89
+                $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object, 2, '');
90 90
                 return null;
91 91
             }
92 92
             $this->oidDesc['mib']=$match[1];
93 93
             
94 94
             // Do the snmptranslate again.
95
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
96
-                ' -On -Td '.$this->oidDesc['mib'].'::'.$object,$snmptrans,$retVal);
97
-            if ($retVal!=0) {
98
-                $this->logging->log('Error finding trap object : '.$this->oidDesc['mib'].'::'.$object,2,'');
95
+            exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslateDirs.
96
+                ' -On -Td '.$this->oidDesc['mib'].'::'.$object, $snmptrans, $retVal);
97
+            if ($retVal != 0) {
98
+                $this->logging->log('Error finding trap object : '.$this->oidDesc['mib'].'::'.$object, 2, '');
99 99
                 return null;
100 100
             }
101 101
             
@@ -115,12 +115,12 @@  discard block
 block discarded – undo
115 115
         
116 116
         foreach ($snmptrans as $line)
117 117
         {
118
-            if ($indesc===true)
118
+            if ($indesc === true)
119 119
             {
120
-                $line=preg_replace('/[\t ]+/',' ',$line);
121
-                if (preg_match('/(.*)"$/', $line,$match))
120
+                $line=preg_replace('/[\t ]+/', ' ', $line);
121
+                if (preg_match('/(.*)"$/', $line, $match))
122 122
                 {
123
-                    $this->oidDesc['description'] = $tmpdesc . $match[1];
123
+                    $this->oidDesc['description']=$tmpdesc.$match[1];
124 124
                     $indesc=false;
125 125
                 }
126 126
                 $tmpdesc.=$line;
@@ -131,34 +131,34 @@  discard block
 block discarded – undo
131 131
                 $this->oidDesc['oid']=$line;
132 132
                 continue;
133 133
             }
134
-            if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
134
+            if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/', $line, $match))
135 135
             {
136 136
                 $this->oidDesc['syntax']=$match[1];
137 137
                 $this->oidDesc['type_enum']=$match[2];
138 138
                 continue;
139 139
             }
140
-            if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
140
+            if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/', $line, $match))
141 141
             {
142 142
                 $this->oidDesc['syntax']=$match[1];
143 143
                 continue;
144 144
             }
145
-            if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
145
+            if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/', $line, $match))
146 146
             {
147 147
                 $this->oidDesc['dispHint']=$match[1];
148 148
                 continue;
149 149
             }
150
-            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
150
+            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/', $line, $match))
151 151
             {
152 152
                 $this->oidDesc['description']=$match[1];
153 153
                 continue;
154 154
             }
155
-            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
155
+            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/', $line, $match))
156 156
             {
157 157
                 $tmpdesc=$match[1];
158 158
                 $indesc=true;
159 159
                 continue;
160 160
             }
161
-            if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
161
+            if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/', $line, $match))
162 162
             {
163 163
                 $this->oidDesc['textconv']=$match[1];
164 164
                 continue;
@@ -173,9 +173,9 @@  discard block
 block discarded – undo
173 173
      * @param array $objects : array of objects name (without MIB)
174 174
      * @param bool $check_existing : check instead of create
175 175
      */
176
-    public function trap_objects($trapOID,$trapmib,$objects,$check_existing)
176
+    public function trap_objects($trapOID, $trapmib, $objects, $check_existing)
177 177
     {              
178
-        $trapId = $this->dbOidIndex[$trapOID]['id']; // Get id of trap
178
+        $trapId=$this->dbOidIndex[$trapOID]['id']; // Get id of trap
179 179
         
180 180
         if ($check_existing === true)
181 181
         {
@@ -192,9 +192,9 @@  discard block
 block discarded – undo
192 192
             
193 193
             $this->parse_object($snmptrans);
194 194
 
195
-            $this->oidDesc['name'] = $object;
195
+            $this->oidDesc['name']=$object;
196 196
             
197
-            $this->logging->log("Adding object ".$this->oidDesc['name']." : ".$this->oidDesc['oid']." / ".$this->oidDesc['syntax']." / ".$this->oidDesc['type_enum']." / ".$this->oidDesc['dispHint']." / ".$this->oidDesc['textconv'],DEBUG );
197
+            $this->logging->log("Adding object ".$this->oidDesc['name']." : ".$this->oidDesc['oid']." / ".$this->oidDesc['syntax']." / ".$this->oidDesc['type_enum']." / ".$this->oidDesc['dispHint']." / ".$this->oidDesc['textconv'], DEBUG);
198 198
 
199 199
             // Update
200 200
             $this->update_oid();
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
             );
220 220
             
221 221
             if ($sqlQuery->execute($sqlParam) === false) {
222
-                $this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$this->oidDesc['oid']]['id'] ,1,'');
222
+                $this->logging->log('Error adding trap object : '.$sql.' / '.$trapId.'/'.$this->dbOidIndex[$this->oidDesc['oid']]['id'], 1, '');
223 223
             }
224 224
         }
225 225
         if ($check_existing === true)
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
         $this->oidDesc['type']=null;
237 237
         $this->oidDesc['mib']=null;
238 238
         $this->oidDesc['textconv']=null;
239
-        $this->oidDesc['dispHint'] =null;
239
+        $this->oidDesc['dispHint']=null;
240 240
         $this->oidDesc['syntax']=null;
241 241
         $this->oidDesc['type_enum']=null;
242 242
         $this->oidDesc['description']=null;
@@ -250,17 +250,17 @@  discard block
 block discarded – undo
250 250
     {
251 251
         $retVal=0;
252 252
         // Get all mib objects from all mibs
253
-        $snmpCommand=$this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.' -On -Tto 2>/dev/null';
254
-        $this->logging->log('Getting all traps : '.$snmpCommand,DEBUG );
253
+        $snmpCommand=$this->snmptranslate.' -m ALL -M +'.$this->snmptranslateDirs.' -On -Tto 2>/dev/null';
254
+        $this->logging->log('Getting all traps : '.$snmpCommand, DEBUG);
255 255
         unset($this->objectsAll);
256
-        exec($snmpCommand,$this->objectsAll,$retVal);
257
-        if ($retVal!=0)
256
+        exec($snmpCommand, $this->objectsAll, $retVal);
257
+        if ($retVal != 0)
258 258
         {
259
-            $this->logging->log('error executing snmptranslate',ERROR,'');
259
+            $this->logging->log('error executing snmptranslate', ERROR, '');
260 260
         }
261 261
         // Count elements to show progress
262 262
         $numElements=count($this->objectsAll);
263
-        $this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements,INFO );
263
+        $this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements, INFO);
264 264
         return $numElements;
265 265
     }
266 266
 
@@ -274,14 +274,14 @@  discard block
 block discarded – undo
274 274
         $db_conn=$this->trapsDB->db_connect_trap();
275 275
         
276 276
         $sql='SELECT * from '.$this->trapsDB->dbPrefix.'mib_cache;';
277
-        $this->logging->log('SQL query : '.$sql,DEBUG );
277
+        $this->logging->log('SQL query : '.$sql, DEBUG);
278 278
         if (($ret_code=$db_conn->query($sql)) === false) {
279
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
279
+            $this->logging->log('No result in query : '.$sql, ERROR, '');
280 280
         }
281 281
         $this->dbOidAll=$ret_code->fetchAll();
282 282
         $this->dbOidIndex=array();
283 283
         // Create the index for db;
284
-        foreach($this->dbOidAll as $key=>$val)
284
+        foreach ($this->dbOidAll as $key=>$val)
285 285
         {
286 286
             $this->dbOidIndex[$val['oid']]['key']=$key;
287 287
             $this->dbOidIndex[$val['oid']]['id']=$val['id'];
@@ -314,13 +314,13 @@  discard block
 block discarded – undo
314 314
      * @param bool $onlyTraps : set to false to get all and not only traps.
315 315
      * @return boolean : false if it's a trap , true if not
316 316
      */
317
-    private function detect_trap($curElement,$onlyTraps)
317
+    private function detect_trap($curElement, $onlyTraps)
318 318
     {
319 319
         // Get oid or pass if not found
320
-        if (!preg_match('/^\.[0-9\.]+$/',$this->objectsAll[$curElement]))
320
+        if (!preg_match('/^\.[0-9\.]+$/', $this->objectsAll[$curElement]))
321 321
         {
322
-            $this->timing['base_parse_time'] += microtime(true) - $this->timing['base_time'];
323
-            $this->timing['base_parse_num'] ++;
322
+            $this->timing['base_parse_time']+=microtime(true) - $this->timing['base_time'];
323
+            $this->timing['base_parse_num']++;
324 324
             return true;
325 325
         }
326 326
         $this->oidDesc['oid']=$this->objectsAll[$curElement];
@@ -329,9 +329,9 @@  discard block
 block discarded – undo
329 329
         $curElement++;
330 330
         $match=$snmptrans=array();
331 331
         if (!preg_match('/ +([^\(]+)\(.+\) type=([0-9]+)( tc=([0-9]+))?( hint=(.+))?/',
332
-            $this->objectsAll[$curElement],$match))
332
+            $this->objectsAll[$curElement], $match))
333 333
         {
334
-            $this->timing['base_check_time'] += microtime(true) - $this->timing['base_time'];
334
+            $this->timing['base_check_time']+=microtime(true) - $this->timing['base_time'];
335 335
             $this->timing['base_check_num']++;
336 336
             return true;
337 337
         }
@@ -339,22 +339,22 @@  discard block
 block discarded – undo
339 339
         $this->oidDesc['name']=$match[1]; // Name
340 340
         $this->oidDesc['type']=$match[2]; // type (21=trap, 0: may be trap, else : not trap
341 341
         
342
-        if ($this->oidDesc['type']==0) // object type=0 : check if v1 trap
342
+        if ($this->oidDesc['type'] == 0) // object type=0 : check if v1 trap
343 343
         {
344 344
             // Check if next is suboid -> in that case is cannot be a trap
345
-            if (preg_match("/^".$this->oidDesc['oid']."/",$this->objectsAll[$curElement+1]))
345
+            if (preg_match("/^".$this->oidDesc['oid']."/", $this->objectsAll[$curElement + 1]))
346 346
             {
347
-                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
347
+                $this->timing['type0_check_time']+=microtime(true) - $this->timing['base_time'];
348 348
                 $this->timing['type0_check_num']++;
349 349
                 return true;
350 350
             }
351 351
             unset($snmptrans);
352 352
             $retVal=0;
353
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
354
-                ' -Td '.$this->oidDesc['oid'] . ' | grep OBJECTS ',$snmptrans,$retVal);
355
-            if ($retVal!=0)
353
+            exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslateDirs.
354
+                ' -Td '.$this->oidDesc['oid'].' | grep OBJECTS ', $snmptrans, $retVal);
355
+            if ($retVal != 0)
356 356
             {
357
-                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
357
+                $this->timing['type0_check_time']+=microtime(true) - $this->timing['base_time'];
358 358
                 $this->timing['type0_check_num']++;
359 359
                 return true;
360 360
             }
@@ -362,9 +362,9 @@  discard block
 block discarded – undo
362 362
             // Force as trap.
363 363
             $this->oidDesc['type']=21;
364 364
         }
365
-        if ($onlyTraps===true && $this->oidDesc['type']!=21) // if only traps and not a trap, continue
365
+        if ($onlyTraps === true && $this->oidDesc['type'] != 21) // if only traps and not a trap, continue
366 366
         {
367
-            $this->timing['nottrap_time'] += microtime(true) - $this->timing['base_time'];
367
+            $this->timing['nottrap_time']+=microtime(true) - $this->timing['base_time'];
368 368
             $this->timing['nottrap_num']++;
369 369
             return true;
370 370
         }
@@ -379,35 +379,35 @@  discard block
 block discarded – undo
379 379
     {
380 380
         $retVal=0;
381 381
         $match=$snmptrans=array();
382
-        exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
383
-            ' -Td '.$this->oidDesc['oid'],$snmptrans,$retVal);
384
-        if ($retVal!=0)
382
+        exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslateDirs.
383
+            ' -Td '.$this->oidDesc['oid'], $snmptrans, $retVal);
384
+        if ($retVal != 0)
385 385
         {
386
-            $this->logging->log('error executing snmptranslate',ERROR);
386
+            $this->logging->log('error executing snmptranslate', ERROR);
387 387
             return $snmptrans;
388 388
         }
389 389
         
390
-        if (!preg_match('/^(.*)::/',$snmptrans[0],$match))
390
+        if (!preg_match('/^(.*)::/', $snmptrans[0], $match))
391 391
         {
392
-            $this->logging->log('Error getting mib from trap '.$this->oidDesc['oid'].' : ' . $snmptrans[0],ERROR);
392
+            $this->logging->log('Error getting mib from trap '.$this->oidDesc['oid'].' : '.$snmptrans[0], ERROR);
393 393
             return $snmptrans;
394 394
         }
395 395
         $this->oidDesc['mib']=$match[1];
396 396
         
397 397
         $numLine=1;
398
-        while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
398
+        while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/', $snmptrans[$numLine], $match)) $numLine++;
399 399
         if (isset($snmptrans[$numLine]))
400 400
         {
401
-            $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
401
+            $snmptrans[$numLine]=preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/', '', $snmptrans[$numLine]);
402 402
             
403
-            while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
403
+            while (isset($snmptrans[$numLine]) && !preg_match('/"/', $snmptrans[$numLine]))
404 404
             {
405
-                $this->oidDesc['description'].=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
405
+                $this->oidDesc['description'].=preg_replace('/[\t ]+/', ' ', $snmptrans[$numLine]);
406 406
                 $numLine++;
407 407
             }
408 408
             if (isset($snmptrans[$numLine])) {
409
-                $this->oidDesc['description'].=preg_replace('/".*/','',$snmptrans[$numLine]);
410
-                $this->oidDesc['description']=preg_replace('/[\t ]+/',' ',$this->oidDesc['description']);
409
+                $this->oidDesc['description'].=preg_replace('/".*/', '', $snmptrans[$numLine]);
410
+                $this->oidDesc['description']=preg_replace('/[\t ]+/', ' ', $this->oidDesc['description']);
411 411
             }
412 412
             
413 413
         }
@@ -425,23 +425,23 @@  discard block
 block discarded – undo
425 425
         $match=array();
426 426
         foreach ($snmptrans as $line)
427 427
         {
428
-            if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
428
+            if (preg_match('/OBJECTS.*\{([^\}]+)\}/', $line, $match))
429 429
             {
430 430
                 $objectName=$match[1];
431 431
             }
432 432
         }
433 433
         if ($objectName == null)
434 434
         {
435
-            $this->logging->log('No objects for ' . $this->oidDesc['oid'],DEBUG);
436
-            $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
435
+            $this->logging->log('No objects for '.$this->oidDesc['oid'], DEBUG);
436
+            $this->timing['objects_time']+=microtime(true) - $this->timing['base_time'];
437 437
             return null;
438 438
         }
439 439
         
440 440
         $trapObjects=array();
441
-        while (preg_match('/ *([^ ,]+) *,* */',$objectName,$match))
441
+        while (preg_match('/ *([^ ,]+) *,* */', $objectName, $match))
442 442
         {
443
-            array_push($trapObjects,$match[1]);
444
-            $objectName=preg_replace('/'.$match[0].'/','',$objectName);
443
+            array_push($trapObjects, $match[1]);
444
+            $objectName=preg_replace('/'.$match[0].'/', '', $objectName);
445 445
         }
446 446
         return $trapObjects;
447 447
     }
@@ -453,18 +453,18 @@  discard block
 block discarded – undo
453 453
      * @param boolean $onlyTraps : only cache traps and objects (true) or all (false)
454 454
      * @param string $startOID : only cache under startOID (NOT IMPLEMENTED)
455 455
      */
456
-    public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,$startOID='.1')
456
+    public function update_mib_database($display_progress=false, $check_change=false, $onlyTraps=true, $startOID='.1')
457 457
     {
458 458
         // Global Timing
459
-        $timeTaken = microtime(true);
459
+        $timeTaken=microtime(true);
460 460
         
461 461
         $numElements=$this->load_mibs_snmptranslate(); // Load objectsAll
462 462
         
463 463
         $this->load_mibs_from_db(); // Load from db dbOidAll & dbOidIndex
464 464
         
465
-        $step=$basestep=$numElements/10; // output display of % done
465
+        $step=$basestep=$numElements / 10; // output display of % done
466 466
         $num_step=0;
467
-        $timeFiveSec = microtime(true); // Used for display a '.' every <n> seconds
467
+        $timeFiveSec=microtime(true); // Used for display a '.' every <n> seconds
468 468
         
469 469
         // Create index for trap objects
470 470
         $this->trapObjectsIndex=array();
@@ -472,33 +472,33 @@  discard block
 block discarded – undo
472 472
         // detailed timing (time_* vars)
473 473
         $this->reset_update_timers();
474 474
         
475
-        for ($curElement=0;$curElement < $numElements;$curElement++)
475
+        for ($curElement=0; $curElement < $numElements; $curElement++)
476 476
         {
477
-            $this->timing['base_time']= microtime(true);
477
+            $this->timing['base_time']=microtime(true);
478 478
             if ($display_progress)
479 479
             {
480
-                if ((microtime(true)-$timeFiveSec) > 2)
480
+                if ((microtime(true) - $timeFiveSec) > 2)
481 481
                 { // echo a . every 2 sec
482 482
                     echo '.';
483
-                    $timeFiveSec = microtime(true);
483
+                    $timeFiveSec=microtime(true);
484 484
                 }
485
-                if ($curElement>$step)
485
+                if ($curElement > $step)
486 486
                 { // display progress
487 487
                     $num_step++;
488 488
                     $step+=$basestep;   
489
-                    echo "\n" . ($num_step*10). '% : ';
489
+                    echo "\n".($num_step * 10).'% : ';
490 490
                 }
491 491
             }
492 492
             
493 493
             $this->reset_oidDesc();
494
-            if ($this->detect_trap($curElement,$onlyTraps)===true)
494
+            if ($this->detect_trap($curElement, $onlyTraps) === true)
495 495
             {
496 496
                 continue;
497 497
             }
498 498
             
499 499
             $this->timing['num_traps']++;
500 500
             
501
-            $this->logging->log('Found trap : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],INFO );
501
+            $this->logging->log('Found trap : '.$this->oidDesc['name'].' / OID : '.$this->oidDesc['oid'], INFO);
502 502
             if ($display_progress) echo '#'; // echo a # when trap found
503 503
 
504 504
             // get trap objects & source MIB
@@ -508,14 +508,14 @@  discard block
 block discarded – undo
508 508
 
509 509
             $update=$this->update_oid(); // Do update of trap.
510 510
             
511
-            $this->timing['update_time'] += microtime(true) - $this->timing['base_time'];
511
+            $this->timing['update_time']+=microtime(true) - $this->timing['base_time'];
512 512
             $this->timing['update_num']++;
513 513
             
514
-            $this->timing['base_time']= microtime(true); // Reset to check object time
514
+            $this->timing['base_time']=microtime(true); // Reset to check object time
515 515
             
516
-            if (($update==0) && ($check_change===false))
516
+            if (($update == 0) && ($check_change === false))
517 517
             { // Trapd didn't change & force check disabled
518
-                $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
518
+                $this->timing['objects_time']+=microtime(true) - $this->timing['base_time'];
519 519
                 if ($display_progress) echo "C";
520 520
                 continue;
521 521
             }
@@ -528,17 +528,17 @@  discard block
 block discarded – undo
528 528
            
529 529
             $this->trap_objects($this->oidDesc['oid'], $this->oidDesc['mib'], $trapObjects, false);
530 530
             
531
-            $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
531
+            $this->timing['objects_time']+=microtime(true) - $this->timing['base_time'];
532 532
             $this->timing['objects_num']++;
533 533
         }
534 534
         
535 535
         if ($display_progress)
536 536
         {
537
-            echo "\nNumber of processed traps :  ". $this->timing['num_traps'] ."\n";
538
-            echo "\nParsing : " . number_format($this->timing['base_parse_time']+$this->timing['base_check_time'],1) ." sec / " . ($this->timing['base_parse_num']+ $this->timing['base_check_num'])  . " occurences\n";
539
-            echo "Detecting traps : " . number_format($this->timing['type0_check_time']+$this->timing['nottrap_time'],1) . " sec / " . ($this->timing['type0_check_num']+$this->timing['nottrap_num']) ." occurences\n";
540
-            echo "Trap processing (".$this->timing['update_num']."): ".number_format($this->timing['update_time'],1)." sec , ";
541
-            echo "Objects processing (".$this->timing['objects_num'].") : ".number_format($this->timing['objects_time'],1)." sec \n";
537
+            echo "\nNumber of processed traps :  ".$this->timing['num_traps']."\n";
538
+            echo "\nParsing : ".number_format($this->timing['base_parse_time'] + $this->timing['base_check_time'], 1)." sec / ".($this->timing['base_parse_num'] + $this->timing['base_check_num'])." occurences\n";
539
+            echo "Detecting traps : ".number_format($this->timing['type0_check_time'] + $this->timing['nottrap_time'], 1)." sec / ".($this->timing['type0_check_num'] + $this->timing['nottrap_num'])." occurences\n";
540
+            echo "Trap processing (".$this->timing['update_num']."): ".number_format($this->timing['update_time'], 1)." sec , ";
541
+            echo "Objects processing (".$this->timing['objects_num'].") : ".number_format($this->timing['objects_time'], 1)." sec \n";
542 542
             
543 543
             $timeTaken=microtime(true) - $timeTaken;
544 544
             echo "Global time : ".round($timeTaken)." seconds\n";
Please login to merge, or discard this patch.
Braces   +20 added lines, -6 removed lines patch added patch discarded remove patch
@@ -188,7 +188,10 @@  discard block
 block discarded – undo
188 188
             $this->reset_oidDesc();
189 189
             
190 190
             $snmptrans=$this->get_object_details($object, $trapmib); // Get object mib & details
191
-            if ($snmptrans === null) continue; // object not found
191
+            if ($snmptrans === null) {
192
+            	continue;
193
+            }
194
+            // object not found
192 195
             
193 196
             $this->parse_object($snmptrans);
194 197
 
@@ -339,12 +342,14 @@  discard block
 block discarded – undo
339 342
         $this->oidDesc['name']=$match[1]; // Name
340 343
         $this->oidDesc['type']=$match[2]; // type (21=trap, 0: may be trap, else : not trap
341 344
         
342
-        if ($this->oidDesc['type']==0) // object type=0 : check if v1 trap
345
+        if ($this->oidDesc['type']==0) {
346
+        	// object type=0 : check if v1 trap
343 347
         {
344 348
             // Check if next is suboid -> in that case is cannot be a trap
345 349
             if (preg_match("/^".$this->oidDesc['oid']."/",$this->objectsAll[$curElement+1]))
346 350
             {
347 351
                 $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
352
+        }
348 353
                 $this->timing['type0_check_num']++;
349 354
                 return true;
350 355
             }
@@ -362,9 +367,11 @@  discard block
 block discarded – undo
362 367
             // Force as trap.
363 368
             $this->oidDesc['type']=21;
364 369
         }
365
-        if ($onlyTraps===true && $this->oidDesc['type']!=21) // if only traps and not a trap, continue
370
+        if ($onlyTraps===true && $this->oidDesc['type']!=21) {
371
+        	// if only traps and not a trap, continue
366 372
         {
367 373
             $this->timing['nottrap_time'] += microtime(true) - $this->timing['base_time'];
374
+        }
368 375
             $this->timing['nottrap_num']++;
369 376
             return true;
370 377
         }
@@ -395,7 +402,9 @@  discard block
 block discarded – undo
395 402
         $this->oidDesc['mib']=$match[1];
396 403
         
397 404
         $numLine=1;
398
-        while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
405
+        while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) {
406
+        	$numLine++;
407
+        }
399 408
         if (isset($snmptrans[$numLine]))
400 409
         {
401 410
             $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
@@ -499,7 +508,10 @@  discard block
 block discarded – undo
499 508
             $this->timing['num_traps']++;
500 509
             
501 510
             $this->logging->log('Found trap : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],INFO );
502
-            if ($display_progress) echo '#'; // echo a # when trap found
511
+            if ($display_progress) {
512
+            	echo '#';
513
+            }
514
+            // echo a # when trap found
503 515
 
504 516
             // get trap objects & source MIB
505 517
             
@@ -516,7 +528,9 @@  discard block
 block discarded – undo
516 528
             if (($update==0) && ($check_change===false))
517 529
             { // Trapd didn't change & force check disabled
518 530
                 $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
519
-                if ($display_progress) echo "C";
531
+                if ($display_progress) {
532
+                	echo "C";
533
+                }
520 534
                 continue;
521 535
             }
522 536
             
Please login to merge, or discard this patch.
tests/expr_test.php 3 patches
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@
 block discarded – undo
20 20
   $inputStream=fopen('php://stdin', 'r');
21 21
   if ($inputStream === false)
22 22
   {
23
-      exit(1);
23
+	  exit(1);
24 24
   }
25 25
   $rule=chop(fgets($inputStream));
26 26
 } else
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -5,18 +5,18 @@  discard block
 block discarded – undo
5 5
 
6 6
 require_once 'bin/trap_class.php';
7 7
 
8
-$options = getopt("r:d:");
8
+$options=getopt("r:d:");
9 9
 
10
-$icingaweb2Etc=(array_key_exists('d',$options))?$options['d']:"/etc/icingaweb2";
10
+$icingaweb2Etc=(array_key_exists('d', $options)) ? $options['d'] : "/etc/icingaweb2";
11 11
 
12
-$debugLevel=4;// 0=No output 1=critical 2=warning 3=trace 4=ALL
12
+$debugLevel=4; // 0=No output 1=critical 2=warning 3=trace 4=ALL
13 13
 
14
-$trap = new trap($icingaweb2Etc);
15
-$trap->setLogging($debugLevel,'display');
14
+$trap=new trap($icingaweb2Etc);
15
+$trap->setLogging($debugLevel, 'display');
16 16
 
17
-$input=array_key_exists('r',$options);
17
+$input=array_key_exists('r', $options);
18 18
 
19
-if (! $input) {
19
+if (!$input) {
20 20
   $inputStream=fopen('php://stdin', 'r');
21 21
   if ($inputStream === false)
22 22
   {
@@ -31,10 +31,10 @@  discard block
 block discarded – undo
31 31
   $rule=$trap->ruleClass->eval_cleanup($rule);
32 32
   //echo 'After cleanup : #'.$rule."#\n";
33 33
   $item=0;
34
-  $val = $trap->ruleClass->evaluation($rule,$item);
35
-  if ($val==true) { printf( "true"); } else { printf( "false");}
34
+  $val=$trap->ruleClass->evaluation($rule, $item);
35
+  if ($val == true) { printf("true"); } else { printf("false"); }
36 36
   printf("\n");
37 37
 }
38
-catch (Exception $e) { printf("%s\n",$e->getMessage()); exit(1);}
38
+catch (Exception $e) { printf("%s\n", $e->getMessage()); exit(1); }
39 39
 
40 40
 exit(0);
Please login to merge, or discard this patch.
Braces   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -23,8 +23,9 @@  discard block
 block discarded – undo
23 23
       exit(1);
24 24
   }
25 25
   $rule=chop(fgets($inputStream));
26
-} else
26
+} else {
27 27
   $rule=$options['r'];
28
+}
28 29
 
29 30
 try
30 31
 {
@@ -34,7 +35,6 @@  discard block
 block discarded – undo
34 35
   $val = $trap->ruleClass->evaluation($rule,$item);
35 36
   if ($val==true) { printf( "true"); } else { printf( "false");}
36 37
   printf("\n");
37
-}
38
-catch (Exception $e) { printf("%s\n",$e->getMessage()); exit(1);}
38
+} catch (Exception $e) { printf("%s\n",$e->getMessage()); exit(1);}
39 39
 
40 40
 exit(0);
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/RuleUtils.php 3 patches
Braces   +13 added lines, -6 removed lines patch added patch discarded remove patch
@@ -71,11 +71,13 @@  discard block
 block discarded – undo
71 71
         $start=$item;
72 72
         $parenthesisCount=0;
73 73
         while (($item < strlen($rule)) // Not end of string AND
74
-            && ( ($rule[$item] != ')' ) || $parenthesisCount > 0) ) // Closing ')' or embeded ()
74
+            && ( ($rule[$item] != ')' ) || $parenthesisCount > 0) ) {
75
+        	// Closing ')' or embeded ()
75 76
         {
76 77
             if ($rule[$item] == '"' )
77 78
             { // pass through string
78 79
                 $item++;
80
+        }
79 81
                 $item=$this->eval_getNext($rule,$item,'"');
80 82
                 continue;
81 83
             }
@@ -121,10 +123,12 @@  discard block
 block discarded – undo
121 123
     {
122 124
         // function is : __function(param1,param2...)
123 125
         $start=$item;
124
-        while (($item < strlen($rule)) && ($rule[$item] != '(' )) // Not end of string AND not opening '('
126
+        while (($item < strlen($rule)) && ($rule[$item] != '(' )) {
127
+        	// Not end of string AND not opening '('
125 128
         {
126 129
             $item++;
127 130
         }
131
+        }
128 132
         if ($item==strlen($rule)) {throw new Exception("no opening () for function in ".$rule ." at " .$item);}
129 133
         
130 134
         // get parameters between parenthesis
@@ -167,12 +171,13 @@  discard block
 block discarded – undo
167 171
      */
168 172
     private function check_negate_first(string $rule,int &$item)
169 173
     {
170
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
174
+        if ( $rule[$item] == '!') {
175
+        	// If '!' found, negate next expression.
171 176
         {
172 177
             $item++;
173
-            return true;
174 178
         }
175
-        else
179
+            return true;
180
+        } else
176 181
         {
177 182
             return false;
178 183
         }
@@ -199,7 +204,9 @@  discard block
 block discarded – undo
199 204
                     $rule2.=$rule[$item];
200 205
                     $item++;
201 206
                 }
202
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
207
+                if ($item == strlen ($rule)) {
208
+                	throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
209
+                }
203 210
                 $rule2.=$rule[$item];
204 211
                 $item++;
205 212
                 continue;
Please login to merge, or discard this patch.
Indentation   +180 added lines, -180 removed lines patch added patch discarded remove patch
@@ -12,204 +12,204 @@
 block discarded – undo
12 12
 trait RuleUtils
13 13
 {
14 14
     
15
-    /** rule eval starting from $token
16
-     * @param string $rule
17
-     * @param int $item
18
-     */
19
-    abstract public function evaluation($rule,&$item);
15
+	/** rule eval starting from $token
16
+	 * @param string $rule
17
+	 * @param int $item
18
+	 */
19
+	abstract public function evaluation($rule,&$item);
20 20
 
21
-    /**
22
-     * Get full number
23
-     * @param string $rule Rule as string
24
-     * @param int $item current eval position
25
-     * @return array<int,string>
26
-     */
27
-    private function get_number(string $rule,int &$item)
28
-    {
29
-        $item2=$item+1;
30
-        while (
31
-            ($item2!=strlen($rule))
32
-            && (preg_match('/[\-0-9\.]/',$rule[$item2])))
33
-        {
34
-            $item2++ ;
35
-        }
36
-        $val=substr($rule,$item,$item2-$item);
37
-        $item=$item2;
38
-        //echo "number ".$val."\n";
21
+	/**
22
+	 * Get full number
23
+	 * @param string $rule Rule as string
24
+	 * @param int $item current eval position
25
+	 * @return array<int,string>
26
+	 */
27
+	private function get_number(string $rule,int &$item)
28
+	{
29
+		$item2=$item+1;
30
+		while (
31
+			($item2!=strlen($rule))
32
+			&& (preg_match('/[\-0-9\.]/',$rule[$item2])))
33
+		{
34
+			$item2++ ;
35
+		}
36
+		$val=substr($rule,$item,$item2-$item);
37
+		$item=$item2;
38
+		//echo "number ".$val."\n";
39 39
         
40
-        return array(0,$val);
41
-    }
40
+		return array(0,$val);
41
+	}
42 42
 
43
-    /**
44
-     * Get a string (between ") 
45
-     * @param string $rule Rule as string
46
-     * @param int $item current eval position
47
-     * @return array<int,string>
48
-     */
49
-    private function get_string(string $rule,int &$item)
50
-    {
51
-        $item++;
52
-        $item2=$this->eval_getNext($rule,$item,'"');
53
-        $val=substr($rule,$item,$item2-$item-1);
54
-        $item=$item2;
55
-        //echo "string : ".$val."\n";
56
-        return array(1,$val);
43
+	/**
44
+	 * Get a string (between ") 
45
+	 * @param string $rule Rule as string
46
+	 * @param int $item current eval position
47
+	 * @return array<int,string>
48
+	 */
49
+	private function get_string(string $rule,int &$item)
50
+	{
51
+		$item++;
52
+		$item2=$this->eval_getNext($rule,$item,'"');
53
+		$val=substr($rule,$item,$item2-$item-1);
54
+		$item=$item2;
55
+		//echo "string : ".$val."\n";
56
+		return array(1,$val);
57 57
         
58
-    }
58
+	}
59 59
     
60
-    /**
61
-     * Parse elements inside () : jumps over "" and count parenthesis.
62
-     * Ex : ( "test" != ")test" & (1==2) ) will return "test" != ")test" & (1==2)
63
-     * @param string $rule : the current rule
64
-     * @param int $item : actual position in rule
65
-     * @throws Exception
66
-     * @return string : everything inside parenthesis
67
-     */
68
-    private function parse_parenthesis(string $rule,int &$item) : string
69
-    {
70
-        $item++;
71
-        $start=$item;
72
-        $parenthesisCount=0;
73
-        while (($item < strlen($rule)) // Not end of string AND
74
-            && ( ($rule[$item] != ')' ) || $parenthesisCount > 0) ) // Closing ')' or embeded ()
75
-        {
76
-            if ($rule[$item] == '"' )
77
-            { // pass through string
78
-                $item++;
79
-                $item=$this->eval_getNext($rule,$item,'"');
80
-                continue;
81
-            }
82
-            if ($rule[$item] == '(')
83
-            {
84
-                $parenthesisCount++;
85
-            }
86
-            if ($rule[$item] == ')')
87
-            {
88
-                $parenthesisCount--;
89
-            }
90
-            $item++;
91
-        }
60
+	/**
61
+	 * Parse elements inside () : jumps over "" and count parenthesis.
62
+	 * Ex : ( "test" != ")test" & (1==2) ) will return "test" != ")test" & (1==2)
63
+	 * @param string $rule : the current rule
64
+	 * @param int $item : actual position in rule
65
+	 * @throws Exception
66
+	 * @return string : everything inside parenthesis
67
+	 */
68
+	private function parse_parenthesis(string $rule,int &$item) : string
69
+	{
70
+		$item++;
71
+		$start=$item;
72
+		$parenthesisCount=0;
73
+		while (($item < strlen($rule)) // Not end of string AND
74
+			&& ( ($rule[$item] != ')' ) || $parenthesisCount > 0) ) // Closing ')' or embeded ()
75
+		{
76
+			if ($rule[$item] == '"' )
77
+			{ // pass through string
78
+				$item++;
79
+				$item=$this->eval_getNext($rule,$item,'"');
80
+				continue;
81
+			}
82
+			if ($rule[$item] == '(')
83
+			{
84
+				$parenthesisCount++;
85
+			}
86
+			if ($rule[$item] == ')')
87
+			{
88
+				$parenthesisCount--;
89
+			}
90
+			$item++;
91
+		}
92 92
         
93
-        if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
94
-        $val=substr($rule,$start,$item-$start);
95
-        $item++;
96
-        return $val;
97
-    }
93
+		if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
94
+		$val=substr($rule,$start,$item-$start);
95
+		$item++;
96
+		return $val;
97
+	}
98 98
 
99
-    /**
100
-     * Get and eval a grouped condition - ex : (1==1)
101
-     * @param string $rule
102
-     * @param int $item
103
-     * @return array<int,string>
104
-     */
105
-    private function get_group(string $rule,int &$item) : array
106
-    {
107
-        // gets eveything inside parenthesis
108
-        $val=$this->parse_parenthesis($rule, $item);
109
-        // Returns boolean with evaluation of all inside parenthesis
110
-        $start=0;
111
-        return array(2,$this->evaluation($val,$start));
112
-    }
99
+	/**
100
+	 * Get and eval a grouped condition - ex : (1==1)
101
+	 * @param string $rule
102
+	 * @param int $item
103
+	 * @return array<int,string>
104
+	 */
105
+	private function get_group(string $rule,int &$item) : array
106
+	{
107
+		// gets eveything inside parenthesis
108
+		$val=$this->parse_parenthesis($rule, $item);
109
+		// Returns boolean with evaluation of all inside parenthesis
110
+		$start=0;
111
+		return array(2,$this->evaluation($val,$start));
112
+	}
113 113
     
114
-    /**
115
-     * @param string $rule
116
-     * @param int $item
117
-     * @throws Exception
118
-     * @return array<int,string>
119
-     */
120
-    private function get_function(string $rule,int &$item) : array
121
-    {
122
-        // function is : __function(param1,param2...)
123
-        $start=$item;
124
-        while (($item < strlen($rule)) && ($rule[$item] != '(' )) // Not end of string AND not opening '('
125
-        {
126
-            $item++;
127
-        }
128
-        if ($item==strlen($rule)) {throw new Exception("no opening () for function in ".$rule ." at " .$item);}
114
+	/**
115
+	 * @param string $rule
116
+	 * @param int $item
117
+	 * @throws Exception
118
+	 * @return array<int,string>
119
+	 */
120
+	private function get_function(string $rule,int &$item) : array
121
+	{
122
+		// function is : __function(param1,param2...)
123
+		$start=$item;
124
+		while (($item < strlen($rule)) && ($rule[$item] != '(' )) // Not end of string AND not opening '('
125
+		{
126
+			$item++;
127
+		}
128
+		if ($item==strlen($rule)) {throw new Exception("no opening () for function in ".$rule ." at " .$item);}
129 129
         
130
-        // get parameters between parenthesis
130
+		// get parameters between parenthesis
131 131
         
132
-        $this->parse_parenthesis($rule, $item);
132
+		$this->parse_parenthesis($rule, $item);
133 133
         
134
-        $val=substr($rule,$start,$item-$start);
134
+		$val=substr($rule,$start,$item-$start);
135 135
         
136
-        $this->logging->log('got function ' . $val,DEBUG);
136
+		$this->logging->log('got function ' . $val,DEBUG);
137 137
         
138
-        return array(2,$this->trapClass->pluginClass->evaluateFunctionString($val));
138
+		return array(2,$this->trapClass->pluginClass->evaluateFunctionString($val));
139 139
         
140
-    }
140
+	}
141 141
 
142
-    /** Find next token $tok in $rule starting at $item 
143
-     * @param string $rule
144
-     * @param int $item
145
-     * @param string $tok : token to search for
146
-     * @throws Exception
147
-     * @return int Position after next token
148
-     */
149
-    protected function eval_getNext(string $rule,int $item,string $tok)
150
-    {
151
-        while (
152
-            ($rule[$item] != $tok )
153
-            && ($item < strlen($rule)))
154
-        {
155
-            $item++;
156
-        }
157
-        if ($item==strlen($rule)) {
158
-            throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
159
-        }
160
-        return $item+1;
161
-    }
142
+	/** Find next token $tok in $rule starting at $item 
143
+	 * @param string $rule
144
+	 * @param int $item
145
+	 * @param string $tok : token to search for
146
+	 * @throws Exception
147
+	 * @return int Position after next token
148
+	 */
149
+	protected function eval_getNext(string $rule,int $item,string $tok)
150
+	{
151
+		while (
152
+			($rule[$item] != $tok )
153
+			&& ($item < strlen($rule)))
154
+		{
155
+			$item++;
156
+		}
157
+		if ($item==strlen($rule)) {
158
+			throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
159
+		}
160
+		return $item+1;
161
+	}
162 162
 
163
-    /** get negate (!) and return true if found - and pass it with item++ - 
164
-     * @param string $rule
165
-     * @param int $item
166
-     * @return boolean
167
-     */
168
-    private function check_negate_first(string $rule,int &$item)
169
-    {
170
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
171
-        {
172
-            $item++;
173
-            return true;
174
-        }
175
-        else
176
-        {
177
-            return false;
178
-        }
179
-    }
163
+	/** get negate (!) and return true if found - and pass it with item++ - 
164
+	 * @param string $rule
165
+	 * @param int $item
166
+	 * @return boolean
167
+	 */
168
+	private function check_negate_first(string $rule,int &$item)
169
+	{
170
+		if ( $rule[$item] == '!') // If '!' found, negate next expression.
171
+		{
172
+			$item++;
173
+			return true;
174
+		}
175
+		else
176
+		{
177
+			return false;
178
+		}
179
+	}
180 180
 
181
-    /** Remove all whitespaces (when not quoted)
182
-     * @param string $rule
183
-     * @throws Exception
184
-     * @return string
185
-     */
186
-    public function eval_cleanup($rule)
187
-    {
188
-        $item=0;
189
-        $rule2='';
190
-        while ($item < strlen($rule))
191
-        {
192
-            if ($rule[$item]==' ') { $item++; continue; }
193
-            if ($rule[$item]=='"')
194
-            {
195
-                $rule2.=$rule[$item];
196
-                $item++;
197
-                while (($item < strlen($rule)) && ($rule[$item]!='"') )
198
-                {
199
-                    $rule2.=$rule[$item];
200
-                    $item++;
201
-                }
202
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
203
-                $rule2.=$rule[$item];
204
-                $item++;
205
-                continue;
206
-            }
181
+	/** Remove all whitespaces (when not quoted)
182
+	 * @param string $rule
183
+	 * @throws Exception
184
+	 * @return string
185
+	 */
186
+	public function eval_cleanup($rule)
187
+	{
188
+		$item=0;
189
+		$rule2='';
190
+		while ($item < strlen($rule))
191
+		{
192
+			if ($rule[$item]==' ') { $item++; continue; }
193
+			if ($rule[$item]=='"')
194
+			{
195
+				$rule2.=$rule[$item];
196
+				$item++;
197
+				while (($item < strlen($rule)) && ($rule[$item]!='"') )
198
+				{
199
+					$rule2.=$rule[$item];
200
+					$item++;
201
+				}
202
+				if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
203
+				$rule2.=$rule[$item];
204
+				$item++;
205
+				continue;
206
+			}
207 207
             
208
-            $rule2.=$rule[$item];
209
-            $item++;
210
-        }
208
+			$rule2.=$rule[$item];
209
+			$item++;
210
+		}
211 211
         
212
-        return $rule2;
213
-    }
212
+		return $rule2;
213
+	}
214 214
     
215 215
 }
216 216
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
      * @param string $rule
17 17
      * @param int $item
18 18
      */
19
-    abstract public function evaluation($rule,&$item);
19
+    abstract public function evaluation($rule, &$item);
20 20
 
21 21
     /**
22 22
      * Get full number
@@ -24,20 +24,20 @@  discard block
 block discarded – undo
24 24
      * @param int $item current eval position
25 25
      * @return array<int,string>
26 26
      */
27
-    private function get_number(string $rule,int &$item)
27
+    private function get_number(string $rule, int &$item)
28 28
     {
29
-        $item2=$item+1;
29
+        $item2=$item + 1;
30 30
         while (
31
-            ($item2!=strlen($rule))
32
-            && (preg_match('/[\-0-9\.]/',$rule[$item2])))
31
+            ($item2 != strlen($rule))
32
+            && (preg_match('/[\-0-9\.]/', $rule[$item2])))
33 33
         {
34
-            $item2++ ;
34
+            $item2++;
35 35
         }
36
-        $val=substr($rule,$item,$item2-$item);
36
+        $val=substr($rule, $item, $item2 - $item);
37 37
         $item=$item2;
38 38
         //echo "number ".$val."\n";
39 39
         
40
-        return array(0,$val);
40
+        return array(0, $val);
41 41
     }
42 42
 
43 43
     /**
@@ -46,14 +46,14 @@  discard block
 block discarded – undo
46 46
      * @param int $item current eval position
47 47
      * @return array<int,string>
48 48
      */
49
-    private function get_string(string $rule,int &$item)
49
+    private function get_string(string $rule, int &$item)
50 50
     {
51 51
         $item++;
52
-        $item2=$this->eval_getNext($rule,$item,'"');
53
-        $val=substr($rule,$item,$item2-$item-1);
52
+        $item2=$this->eval_getNext($rule, $item, '"');
53
+        $val=substr($rule, $item, $item2 - $item - 1);
54 54
         $item=$item2;
55 55
         //echo "string : ".$val."\n";
56
-        return array(1,$val);
56
+        return array(1, $val);
57 57
         
58 58
     }
59 59
     
@@ -65,18 +65,18 @@  discard block
 block discarded – undo
65 65
      * @throws Exception
66 66
      * @return string : everything inside parenthesis
67 67
      */
68
-    private function parse_parenthesis(string $rule,int &$item) : string
68
+    private function parse_parenthesis(string $rule, int &$item) : string
69 69
     {
70 70
         $item++;
71 71
         $start=$item;
72 72
         $parenthesisCount=0;
73 73
         while (($item < strlen($rule)) // Not end of string AND
74
-            && ( ($rule[$item] != ')' ) || $parenthesisCount > 0) ) // Closing ')' or embeded ()
74
+            && (($rule[$item] != ')') || $parenthesisCount > 0)) // Closing ')' or embeded ()
75 75
         {
76
-            if ($rule[$item] == '"' )
76
+            if ($rule[$item] == '"')
77 77
             { // pass through string
78 78
                 $item++;
79
-                $item=$this->eval_getNext($rule,$item,'"');
79
+                $item=$this->eval_getNext($rule, $item, '"');
80 80
                 continue;
81 81
             }
82 82
             if ($rule[$item] == '(')
@@ -90,8 +90,8 @@  discard block
 block discarded – undo
90 90
             $item++;
91 91
         }
92 92
         
93
-        if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
94
-        $val=substr($rule,$start,$item-$start);
93
+        if ($item == strlen($rule)) {throw new Exception("no closing () in ".$rule." at ".$item); }
94
+        $val=substr($rule, $start, $item - $start);
95 95
         $item++;
96 96
         return $val;
97 97
     }
@@ -102,13 +102,13 @@  discard block
 block discarded – undo
102 102
      * @param int $item
103 103
      * @return array<int,string>
104 104
      */
105
-    private function get_group(string $rule,int &$item) : array
105
+    private function get_group(string $rule, int &$item) : array
106 106
     {
107 107
         // gets eveything inside parenthesis
108 108
         $val=$this->parse_parenthesis($rule, $item);
109 109
         // Returns boolean with evaluation of all inside parenthesis
110 110
         $start=0;
111
-        return array(2,$this->evaluation($val,$start));
111
+        return array(2, $this->evaluation($val, $start));
112 112
     }
113 113
     
114 114
     /**
@@ -117,25 +117,25 @@  discard block
 block discarded – undo
117 117
      * @throws Exception
118 118
      * @return array<int,string>
119 119
      */
120
-    private function get_function(string $rule,int &$item) : array
120
+    private function get_function(string $rule, int &$item) : array
121 121
     {
122 122
         // function is : __function(param1,param2...)
123 123
         $start=$item;
124
-        while (($item < strlen($rule)) && ($rule[$item] != '(' )) // Not end of string AND not opening '('
124
+        while (($item < strlen($rule)) && ($rule[$item] != '(')) // Not end of string AND not opening '('
125 125
         {
126 126
             $item++;
127 127
         }
128
-        if ($item==strlen($rule)) {throw new Exception("no opening () for function in ".$rule ." at " .$item);}
128
+        if ($item == strlen($rule)) {throw new Exception("no opening () for function in ".$rule." at ".$item); }
129 129
         
130 130
         // get parameters between parenthesis
131 131
         
132 132
         $this->parse_parenthesis($rule, $item);
133 133
         
134
-        $val=substr($rule,$start,$item-$start);
134
+        $val=substr($rule, $start, $item - $start);
135 135
         
136
-        $this->logging->log('got function ' . $val,DEBUG);
136
+        $this->logging->log('got function '.$val, DEBUG);
137 137
         
138
-        return array(2,$this->trapClass->pluginClass->evaluateFunctionString($val));
138
+        return array(2, $this->trapClass->pluginClass->evaluateFunctionString($val));
139 139
         
140 140
     }
141 141
 
@@ -146,18 +146,18 @@  discard block
 block discarded – undo
146 146
      * @throws Exception
147 147
      * @return int Position after next token
148 148
      */
149
-    protected function eval_getNext(string $rule,int $item,string $tok)
149
+    protected function eval_getNext(string $rule, int $item, string $tok)
150 150
     {
151 151
         while (
152
-            ($rule[$item] != $tok )
152
+            ($rule[$item] != $tok)
153 153
             && ($item < strlen($rule)))
154 154
         {
155 155
             $item++;
156 156
         }
157
-        if ($item==strlen($rule)) {
158
-            throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
157
+        if ($item == strlen($rule)) {
158
+            throw new Exception("closing '".$tok."' not found in ".$rule." at ".$item);
159 159
         }
160
-        return $item+1;
160
+        return $item + 1;
161 161
     }
162 162
 
163 163
     /** get negate (!) and return true if found - and pass it with item++ - 
@@ -165,9 +165,9 @@  discard block
 block discarded – undo
165 165
      * @param int $item
166 166
      * @return boolean
167 167
      */
168
-    private function check_negate_first(string $rule,int &$item)
168
+    private function check_negate_first(string $rule, int &$item)
169 169
     {
170
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
170
+        if ($rule[$item] == '!') // If '!' found, negate next expression.
171 171
         {
172 172
             $item++;
173 173
             return true;
@@ -189,17 +189,17 @@  discard block
 block discarded – undo
189 189
         $rule2='';
190 190
         while ($item < strlen($rule))
191 191
         {
192
-            if ($rule[$item]==' ') { $item++; continue; }
193
-            if ($rule[$item]=='"')
192
+            if ($rule[$item] == ' ') { $item++; continue; }
193
+            if ($rule[$item] == '"')
194 194
             {
195 195
                 $rule2.=$rule[$item];
196 196
                 $item++;
197
-                while (($item < strlen($rule)) && ($rule[$item]!='"') )
197
+                while (($item < strlen($rule)) && ($rule[$item] != '"'))
198 198
                 {
199 199
                     $rule2.=$rule[$item];
200 200
                     $item++;
201 201
                 }
202
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
202
+                if ($item == strlen($rule)) throw new Exception("closing '\"' not found in ".$rule." at ".$item);
203 203
                 $rule2.=$rule[$item];
204 204
                 $item++;
205 205
                 continue;
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Rule.php 3 patches
Indentation   +201 added lines, -201 removed lines patch added patch discarded remove patch
@@ -6,233 +6,233 @@
 block discarded – undo
6 6
 
7 7
 class Rule
8 8
 {
9
-    use \RuleUtils;
9
+	use \RuleUtils;
10 10
     
11
-    /** @var Logging $logging logging class*/
12
-    protected $logging;
11
+	/** @var Logging $logging logging class*/
12
+	protected $logging;
13 13
     
14
-    /** @var Trap $trapClass */
15
-    protected $trapClass;
14
+	/** @var Trap $trapClass */
15
+	protected $trapClass;
16 16
     
17 17
 
18
-    /**
19
-     * Setup Rule Class
20
-     * @param Trap $trapClass : To get logging class & plugin class
21
-     */
22
-    function __construct($trapClass)
23
-    {
24
-        $this->trapClass=$trapClass;
25
-        $this->logging=$trapClass->logging;
26
-    }
18
+	/**
19
+	 * Setup Rule Class
20
+	 * @param Trap $trapClass : To get logging class & plugin class
21
+	 */
22
+	function __construct($trapClass)
23
+	{
24
+		$this->trapClass=$trapClass;
25
+		$this->logging=$trapClass->logging;
26
+	}
27 27
     
28 28
     
29
-    protected function eval_getElement($rule,&$item)
30
-    {
31
-        if ($item >= strlen($rule))
32
-        {
33
-            throw new Exception("Early end of string ".$rule ." at " .$item );
34
-        }
35
-        while ($rule[$item]==' ') $item++;
36
-        if (preg_match('/[\-0-9\.]/',$rule[$item]))
37
-        { // number
38
-            return $this->get_number($rule, $item);
39
-        }
40
-        if ($rule[$item] == '"')
41
-        { // string
42
-            return $this->get_string($rule, $item);
43
-        }
29
+	protected function eval_getElement($rule,&$item)
30
+	{
31
+		if ($item >= strlen($rule))
32
+		{
33
+			throw new Exception("Early end of string ".$rule ." at " .$item );
34
+		}
35
+		while ($rule[$item]==' ') $item++;
36
+		if (preg_match('/[\-0-9\.]/',$rule[$item]))
37
+		{ // number
38
+			return $this->get_number($rule, $item);
39
+		}
40
+		if ($rule[$item] == '"')
41
+		{ // string
42
+			return $this->get_string($rule, $item);
43
+		}
44 44
         
45
-        if ($rule[$item] == '(')
46
-        { // grouping
47
-            return $this->get_group($rule, $item);
48
-        }
49
-        if ($rule[$item] == '_')
50
-        { // function
51
-            return $this->get_function($rule, $item);
52
-        }
53
-        throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
45
+		if ($rule[$item] == '(')
46
+		{ // grouping
47
+			return $this->get_group($rule, $item);
48
+		}
49
+		if ($rule[$item] == '_')
50
+		{ // function
51
+			return $this->get_function($rule, $item);
52
+		}
53
+		throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
54 54
         
55
-    }
55
+	}
56 56
     
57
-    protected function eval_getOper($rule,&$item)
58
-    {
59
-        while ($rule[$item]==' ') $item++;
60
-        switch ($rule[$item])
61
-        {
62
-            case '<':
63
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
64
-                $item++; return array(0,"<");
65
-            case '>':
66
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
67
-                $item++; return array(0,">");
68
-            case '=':
69
-                $item++; return array(0,"=");
70
-            case '!':
71
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
72
-                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
73
-            case '~':
74
-                $item++; return array(0,"~");
75
-            case '|':
76
-                $item++; return array(1,"|");
77
-            case '&':
78
-                $item++; return array(1,"&");
79
-            default	:
80
-                throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
81
-        }
82
-    }
57
+	protected function eval_getOper($rule,&$item)
58
+	{
59
+		while ($rule[$item]==' ') $item++;
60
+		switch ($rule[$item])
61
+		{
62
+			case '<':
63
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
64
+				$item++; return array(0,"<");
65
+			case '>':
66
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
67
+				$item++; return array(0,">");
68
+			case '=':
69
+				$item++; return array(0,"=");
70
+			case '!':
71
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
72
+				throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
73
+			case '~':
74
+				$item++; return array(0,"~");
75
+			case '|':
76
+				$item++; return array(1,"|");
77
+			case '&':
78
+				$item++; return array(1,"&");
79
+			default	:
80
+				throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
81
+		}
82
+	}
83 83
     
84
-    private function do_compare($val1,$val2,$comp,$negate)
85
-    {
86
-        switch ($comp){
87
-            case '<':	$retVal= ($val1 < $val2); break;
88
-            case '<=':	$retVal= ($val1 <= $val2); break;
89
-            case '>':	$retVal= ($val1 > $val2); break;
90
-            case '>=':	$retVal= ($val1 >= $val2); break;
91
-            case '=':	$retVal= ($val1 == $val2); break;
92
-            case '!=':	$retVal= ($val1 != $val2); break;
93
-            case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
94
-            case '|':	$retVal= ($val1 || $val2); break;
95
-            case '&':	$retVal= ($val1 && $val2); break;
96
-            default:  throw new Exception("Error in expression - unknown comp : ".$comp);
97
-        }
98
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
84
+	private function do_compare($val1,$val2,$comp,$negate)
85
+	{
86
+		switch ($comp){
87
+			case '<':	$retVal= ($val1 < $val2); break;
88
+			case '<=':	$retVal= ($val1 <= $val2); break;
89
+			case '>':	$retVal= ($val1 > $val2); break;
90
+			case '>=':	$retVal= ($val1 >= $val2); break;
91
+			case '=':	$retVal= ($val1 == $val2); break;
92
+			case '!=':	$retVal= ($val1 != $val2); break;
93
+			case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
94
+			case '|':	$retVal= ($val1 || $val2); break;
95
+			case '&':	$retVal= ($val1 && $val2); break;
96
+			default:  throw new Exception("Error in expression - unknown comp : ".$comp);
97
+		}
98
+		if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
99 99
         
100
-        return $retVal;
101
-    }
100
+		return $retVal;
101
+	}
102 102
     
103
-    /** Evaluation : makes token and evaluate.
104
-     *	Public function for expressions testing
105
-     *	accepts : < > = <= >= !=  (typec = 0)
106
-     *	operators : & | (typec=1)
107
-     *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
108
-     *   comparison int vs strings will return null (error)
109
-     *	return : bool or null on error
110
-     */
111
-    public function evaluation($rule,&$item)
112
-    {
113
-        //echo "Evaluation of ".substr($rule,$item)."\n";
114
-        $negate=$this->check_negate_first($rule, $item);
115
-        // First element : number, string or ()
116
-        list($type1,$val1) = $this->eval_getElement($rule,$item);
117
-        //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
103
+	/** Evaluation : makes token and evaluate.
104
+	 *	Public function for expressions testing
105
+	 *	accepts : < > = <= >= !=  (typec = 0)
106
+	 *	operators : & | (typec=1)
107
+	 *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
108
+	 *   comparison int vs strings will return null (error)
109
+	 *	return : bool or null on error
110
+	 */
111
+	public function evaluation($rule,&$item)
112
+	{
113
+		//echo "Evaluation of ".substr($rule,$item)."\n";
114
+		$negate=$this->check_negate_first($rule, $item);
115
+		// First element : number, string or ()
116
+		list($type1,$val1) = $this->eval_getElement($rule,$item);
117
+		//echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
118 118
         
119
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
120
-        {
121
-            if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
122
-            if ($negate === true) $val1= ! $val1;
123
-            return $val1;
124
-        }
119
+		if ($item==strlen($rule)) // If only element, return value, but only boolean
120
+		{
121
+			if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
122
+			if ($negate === true) $val1= ! $val1;
123
+			return $val1;
124
+		}
125 125
         
126
-        // Second element : operator
127
-        list($typec,$comp) = $this->eval_getOper($rule,$item);
128
-        //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
126
+		// Second element : operator
127
+		list($typec,$comp) = $this->eval_getOper($rule,$item);
128
+		//echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
129 129
         
130
-        // Third element : number, string or ()
131
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
132
-        {
133
-            $item++;
134
-            if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
135
-            $val2= ! $this->evaluation($rule,$item);
136
-            $type2=2; // result is a boolean
137
-        }
138
-        else
139
-        {
140
-            list($type2,$val2) = $this->eval_getElement($rule,$item);
141
-        }
142
-        //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
130
+		// Third element : number, string or ()
131
+		if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
132
+		{
133
+			$item++;
134
+			if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
135
+			$val2= ! $this->evaluation($rule,$item);
136
+			$type2=2; // result is a boolean
137
+		}
138
+		else
139
+		{
140
+			list($type2,$val2) = $this->eval_getElement($rule,$item);
141
+		}
142
+		//echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
143 143
         
144
-        if ($type1!=$type2)  // cannot compare different types
145
-        {
146
-            throw new Exception("Cannot compare string & number : ".$rule);
147
-        }
148
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
149
-        {
150
-            throw new Exception("Cannot use boolean operators with string & number : ".$rule);
151
-        }
144
+		if ($type1!=$type2)  // cannot compare different types
145
+		{
146
+			throw new Exception("Cannot compare string & number : ".$rule);
147
+		}
148
+		if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
149
+		{
150
+			throw new Exception("Cannot use boolean operators with string & number : ".$rule);
151
+		}
152 152
         
153
-        $retVal = $this->do_compare($val1, $val2, $comp, $negate);
153
+		$retVal = $this->do_compare($val1, $val2, $comp, $negate);
154 154
         
155
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
156
-        // check for logical operator :
157
-        switch ($rule[$item])
158
-        {
159
-            case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
160
-            case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
155
+		if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
156
+		// check for logical operator :
157
+		switch ($rule[$item])
158
+		{
159
+			case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
160
+			case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
161 161
             
162
-            default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
163
-        }
164
-    }
162
+			default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
163
+		}
164
+	}
165 165
     
166
-    /**
167
-     * Get '*' or '**' and transform in [0-9]+ or .* in return string
168
-     * @param string $oid OID in normal or regexp format. '*' will be escaped ('\*')
169
-     * @return string correct regexp format
170
-     */
171
-    public function regexp_eval(string &$oid)
172
-    {
173
-        // ** replaced by .*
174
-        $oidR=preg_replace('/\*\*/', '.*', $oid);
175
-        // * replaced by [0-9]+
176
-        $oidR=preg_replace('/\*/', '[0-9]+', $oidR);
166
+	/**
167
+	 * Get '*' or '**' and transform in [0-9]+ or .* in return string
168
+	 * @param string $oid OID in normal or regexp format. '*' will be escaped ('\*')
169
+	 * @return string correct regexp format
170
+	 */
171
+	public function regexp_eval(string &$oid)
172
+	{
173
+		// ** replaced by .*
174
+		$oidR=preg_replace('/\*\*/', '.*', $oid);
175
+		// * replaced by [0-9]+
176
+		$oidR=preg_replace('/\*/', '[0-9]+', $oidR);
177 177
         
178
-        // replace * with \* in oid for preg_replace
179
-        $oid=preg_replace('/\*/', '\*', $oid);
178
+		// replace * with \* in oid for preg_replace
179
+		$oid=preg_replace('/\*/', '\*', $oid);
180 180
         
181
-        $this->logging->log('Regexp eval : '.$oid.' / '.$oidR,DEBUG );
181
+		$this->logging->log('Regexp eval : '.$oid.' / '.$oidR,DEBUG );
182 182
         
183
-        return $oidR;
184
-    }
183
+		return $oidR;
184
+	}
185 185
     
186 186
     
187
-    /** Evaluation rule (uses eval_* functions recursively)
188
-     *	@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) )
189
-     *  @param array $oidList : OIDs values to sustitute.
190
-     *	@return bool : true : rule match, false : rule don't match , throw exception on error.
191
-     */   
192
-    public function eval_rule($rule,$oidList)
193
-    {
194
-        if ($rule==null || $rule == '') // Empty rule is always true
195
-        {
196
-            return true;
197
-        }
198
-        $matches=array();
199
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
200
-        {
201
-            $oid=$matches[1];
202
-            $found=0;
203
-            // Test and transform regexp
204
-            $oidR = $this->regexp_eval($oid);
187
+	/** Evaluation rule (uses eval_* functions recursively)
188
+	 *	@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) )
189
+	 *  @param array $oidList : OIDs values to sustitute.
190
+	 *	@return bool : true : rule match, false : rule don't match , throw exception on error.
191
+	 */   
192
+	public function eval_rule($rule,$oidList)
193
+	{
194
+		if ($rule==null || $rule == '') // Empty rule is always true
195
+		{
196
+			return true;
197
+		}
198
+		$matches=array();
199
+		while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
200
+		{
201
+			$oid=$matches[1];
202
+			$found=0;
203
+			// Test and transform regexp
204
+			$oidR = $this->regexp_eval($oid);
205 205
             
206
-            foreach($oidList as $val)
207
-            {
208
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
209
-                {
210
-                    if (!preg_match('/^-?[0-9]*\.?[0-9]+$/',$val->value))
211
-                    { // If not a number, change " to ' and put " around it
212
-                        $val->value=preg_replace('/"/',"'",$val->value);
213
-                        $val->value='"'.$val->value.'"';
214
-                    }
215
-                    $rep=0;
216
-                    $rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
217
-                    if ($rep==0)
218
-                    {
219
-                        $this->logging->log("Error in rule_eval",WARN,'');
220
-                        return false;
221
-                    }
222
-                    $found=1;
223
-                    break;
224
-                }
225
-            }
226
-            if ($found==0)
227
-            {	// OID not found : throw error
228
-                throw new Exception('OID '.$oid.' not found in trap');
229
-            }
230
-        }
231
-        $item=0;
232
-        $rule=$this->eval_cleanup($rule);
233
-        $this->logging->log('Rule after clenup: '.$rule,INFO );
206
+			foreach($oidList as $val)
207
+			{
208
+				if (preg_match("/^$oidR$/",$val->oid) == 1)
209
+				{
210
+					if (!preg_match('/^-?[0-9]*\.?[0-9]+$/',$val->value))
211
+					{ // If not a number, change " to ' and put " around it
212
+						$val->value=preg_replace('/"/',"'",$val->value);
213
+						$val->value='"'.$val->value.'"';
214
+					}
215
+					$rep=0;
216
+					$rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
217
+					if ($rep==0)
218
+					{
219
+						$this->logging->log("Error in rule_eval",WARN,'');
220
+						return false;
221
+					}
222
+					$found=1;
223
+					break;
224
+				}
225
+			}
226
+			if ($found==0)
227
+			{	// OID not found : throw error
228
+				throw new Exception('OID '.$oid.' not found in trap');
229
+			}
230
+		}
231
+		$item=0;
232
+		$rule=$this->eval_cleanup($rule);
233
+		$this->logging->log('Rule after clenup: '.$rule,INFO );
234 234
         
235
-        return  $this->evaluation($rule,$item);
236
-    }
235
+		return  $this->evaluation($rule,$item);
236
+	}
237 237
     
238 238
 }
239 239
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -26,14 +26,14 @@  discard block
 block discarded – undo
26 26
     }
27 27
     
28 28
     
29
-    protected function eval_getElement($rule,&$item)
29
+    protected function eval_getElement($rule, &$item)
30 30
     {
31 31
         if ($item >= strlen($rule))
32 32
         {
33
-            throw new Exception("Early end of string ".$rule ." at " .$item );
33
+            throw new Exception("Early end of string ".$rule." at ".$item);
34 34
         }
35
-        while ($rule[$item]==' ') $item++;
36
-        if (preg_match('/[\-0-9\.]/',$rule[$item]))
35
+        while ($rule[$item] == ' ') $item++;
36
+        if (preg_match('/[\-0-9\.]/', $rule[$item]))
37 37
         { // number
38 38
             return $this->get_number($rule, $item);
39 39
         }
@@ -50,52 +50,52 @@  discard block
 block discarded – undo
50 50
         { // function
51 51
             return $this->get_function($rule, $item);
52 52
         }
53
-        throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
53
+        throw new Exception("number/string not found in ".$rule." at ".$item.' : '.$rule[$item]);
54 54
         
55 55
     }
56 56
     
57
-    protected function eval_getOper($rule,&$item)
57
+    protected function eval_getOper($rule, &$item)
58 58
     {
59
-        while ($rule[$item]==' ') $item++;
59
+        while ($rule[$item] == ' ') $item++;
60 60
         switch ($rule[$item])
61 61
         {
62 62
             case '<':
63
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
64
-                $item++; return array(0,"<");
63
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, "<="); }
64
+                $item++; return array(0, "<");
65 65
             case '>':
66
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
67
-                $item++; return array(0,">");
66
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, ">="); }
67
+                $item++; return array(0, ">");
68 68
             case '=':
69
-                $item++; return array(0,"=");
69
+                $item++; return array(0, "=");
70 70
             case '!':
71
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
72
-                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
71
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, "!="); }
72
+                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule." at ".$item);
73 73
             case '~':
74
-                $item++; return array(0,"~");
74
+                $item++; return array(0, "~");
75 75
             case '|':
76
-                $item++; return array(1,"|");
76
+                $item++; return array(1, "|");
77 77
             case '&':
78
-                $item++; return array(1,"&");
78
+                $item++; return array(1, "&");
79 79
             default	:
80
-                throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
80
+                throw new Exception("Erreur in expr - operator not found in ".$rule." at ".$item);
81 81
         }
82 82
     }
83 83
     
84
-    private function do_compare($val1,$val2,$comp,$negate)
84
+    private function do_compare($val1, $val2, $comp, $negate)
85 85
     {
86
-        switch ($comp){
87
-            case '<':	$retVal= ($val1 < $val2); break;
88
-            case '<=':	$retVal= ($val1 <= $val2); break;
89
-            case '>':	$retVal= ($val1 > $val2); break;
90
-            case '>=':	$retVal= ($val1 >= $val2); break;
91
-            case '=':	$retVal= ($val1 == $val2); break;
92
-            case '!=':	$retVal= ($val1 != $val2); break;
93
-            case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
94
-            case '|':	$retVal= ($val1 || $val2); break;
95
-            case '&':	$retVal= ($val1 && $val2); break;
86
+        switch ($comp) {
87
+            case '<':	$retVal=($val1 < $val2); break;
88
+            case '<=':	$retVal=($val1 <= $val2); break;
89
+            case '>':	$retVal=($val1 > $val2); break;
90
+            case '>=':	$retVal=($val1 >= $val2); break;
91
+            case '=':	$retVal=($val1 == $val2); break;
92
+            case '!=':	$retVal=($val1 != $val2); break;
93
+            case '~':	$retVal=(preg_match('/'.preg_replace('/"/', '', $val2).'/', $val1)); break;
94
+            case '|':	$retVal=($val1 || $val2); break;
95
+            case '&':	$retVal=($val1 && $val2); break;
96 96
             default:  throw new Exception("Error in expression - unknown comp : ".$comp);
97 97
         }
98
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
98
+        if ($negate === true) $retVal=!$retVal; // Inverse result if negate before expression
99 99
         
100 100
         return $retVal;
101 101
     }
@@ -108,56 +108,56 @@  discard block
 block discarded – undo
108 108
      *   comparison int vs strings will return null (error)
109 109
      *	return : bool or null on error
110 110
      */
111
-    public function evaluation($rule,&$item)
111
+    public function evaluation($rule, &$item)
112 112
     {
113 113
         //echo "Evaluation of ".substr($rule,$item)."\n";
114 114
         $negate=$this->check_negate_first($rule, $item);
115 115
         // First element : number, string or ()
116
-        list($type1,$val1) = $this->eval_getElement($rule,$item);
116
+        list($type1, $val1)=$this->eval_getElement($rule, $item);
117 117
         //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
118 118
         
119
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
119
+        if ($item == strlen($rule)) // If only element, return value, but only boolean
120 120
         {
121 121
             if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
122
-            if ($negate === true) $val1= ! $val1;
122
+            if ($negate === true) $val1=!$val1;
123 123
             return $val1;
124 124
         }
125 125
         
126 126
         // Second element : operator
127
-        list($typec,$comp) = $this->eval_getOper($rule,$item);
127
+        list($typec, $comp)=$this->eval_getOper($rule, $item);
128 128
         //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
129 129
         
130 130
         // Third element : number, string or ()
131
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
131
+        if ($rule[$item] == '!') // starts with a ! so evaluate whats next
132 132
         {
133 133
             $item++;
134 134
             if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
135
-            $val2= ! $this->evaluation($rule,$item);
135
+            $val2=!$this->evaluation($rule, $item);
136 136
             $type2=2; // result is a boolean
137 137
         }
138 138
         else
139 139
         {
140
-            list($type2,$val2) = $this->eval_getElement($rule,$item);
140
+            list($type2, $val2)=$this->eval_getElement($rule, $item);
141 141
         }
142 142
         //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
143 143
         
144
-        if ($type1!=$type2)  // cannot compare different types
144
+        if ($type1 != $type2)  // cannot compare different types
145 145
         {
146 146
             throw new Exception("Cannot compare string & number : ".$rule);
147 147
         }
148
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
148
+        if ($typec == 1 && $type1 != 2) // cannot use & or | with string/number
149 149
         {
150 150
             throw new Exception("Cannot use boolean operators with string & number : ".$rule);
151 151
         }
152 152
         
153
-        $retVal = $this->do_compare($val1, $val2, $comp, $negate);
153
+        $retVal=$this->do_compare($val1, $val2, $comp, $negate);
154 154
         
155
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
155
+        if ($item == strlen($rule)) return $retVal; // End of string : return evaluation
156 156
         // check for logical operator :
157 157
         switch ($rule[$item])
158 158
         {
159
-            case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
160
-            case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
159
+            case '|':	$item++; return ($retVal || $this->evaluation($rule, $item));
160
+            case '&':	$item++; return ($retVal && $this->evaluation($rule, $item));
161 161
             
162 162
             default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
163 163
         }
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
         // replace * with \* in oid for preg_replace
179 179
         $oid=preg_replace('/\*/', '\*', $oid);
180 180
         
181
-        $this->logging->log('Regexp eval : '.$oid.' / '.$oidR,DEBUG );
181
+        $this->logging->log('Regexp eval : '.$oid.' / '.$oidR, DEBUG);
182 182
         
183 183
         return $oidR;
184 184
     }
@@ -189,50 +189,50 @@  discard block
 block discarded – undo
189 189
      *  @param array $oidList : OIDs values to sustitute.
190 190
      *	@return bool : true : rule match, false : rule don't match , throw exception on error.
191 191
      */   
192
-    public function eval_rule($rule,$oidList)
192
+    public function eval_rule($rule, $oidList)
193 193
     {
194
-        if ($rule==null || $rule == '') // Empty rule is always true
194
+        if ($rule == null || $rule == '') // Empty rule is always true
195 195
         {
196 196
             return true;
197 197
         }
198 198
         $matches=array();
199
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
199
+        while (preg_match('/_OID\(([0-9\.\*]+)\)/', $rule, $matches) == 1)
200 200
         {
201 201
             $oid=$matches[1];
202 202
             $found=0;
203 203
             // Test and transform regexp
204
-            $oidR = $this->regexp_eval($oid);
204
+            $oidR=$this->regexp_eval($oid);
205 205
             
206
-            foreach($oidList as $val)
206
+            foreach ($oidList as $val)
207 207
             {
208
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
208
+                if (preg_match("/^$oidR$/", $val->oid) == 1)
209 209
                 {
210
-                    if (!preg_match('/^-?[0-9]*\.?[0-9]+$/',$val->value))
210
+                    if (!preg_match('/^-?[0-9]*\.?[0-9]+$/', $val->value))
211 211
                     { // If not a number, change " to ' and put " around it
212
-                        $val->value=preg_replace('/"/',"'",$val->value);
212
+                        $val->value=preg_replace('/"/', "'", $val->value);
213 213
                         $val->value='"'.$val->value.'"';
214 214
                     }
215 215
                     $rep=0;
216
-                    $rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
217
-                    if ($rep==0)
216
+                    $rule=preg_replace('/_OID\('.$oid.'\)/', $val->value, $rule, -1, $rep);
217
+                    if ($rep == 0)
218 218
                     {
219
-                        $this->logging->log("Error in rule_eval",WARN,'');
219
+                        $this->logging->log("Error in rule_eval", WARN, '');
220 220
                         return false;
221 221
                     }
222 222
                     $found=1;
223 223
                     break;
224 224
                 }
225 225
             }
226
-            if ($found==0)
226
+            if ($found == 0)
227 227
             {	// OID not found : throw error
228 228
                 throw new Exception('OID '.$oid.' not found in trap');
229 229
             }
230 230
         }
231 231
         $item=0;
232 232
         $rule=$this->eval_cleanup($rule);
233
-        $this->logging->log('Rule after clenup: '.$rule,INFO );
233
+        $this->logging->log('Rule after clenup: '.$rule, INFO);
234 234
         
235
-        return  $this->evaluation($rule,$item);
235
+        return  $this->evaluation($rule, $item);
236 236
     }
237 237
     
238 238
 }
239 239
\ No newline at end of file
Please login to merge, or discard this patch.
Braces   +36 added lines, -13 removed lines patch added patch discarded remove patch
@@ -32,7 +32,9 @@  discard block
 block discarded – undo
32 32
         {
33 33
             throw new Exception("Early end of string ".$rule ." at " .$item );
34 34
         }
35
-        while ($rule[$item]==' ') $item++;
35
+        while ($rule[$item]==' ') {
36
+        	$item++;
37
+        }
36 38
         if (preg_match('/[\-0-9\.]/',$rule[$item]))
37 39
         { // number
38 40
             return $this->get_number($rule, $item);
@@ -56,7 +58,9 @@  discard block
 block discarded – undo
56 58
     
57 59
     protected function eval_getOper($rule,&$item)
58 60
     {
59
-        while ($rule[$item]==' ') $item++;
61
+        while ($rule[$item]==' ') {
62
+        	$item++;
63
+        }
60 64
         switch ($rule[$item])
61 65
         {
62 66
             case '<':
@@ -95,7 +99,10 @@  discard block
 block discarded – undo
95 99
             case '&':	$retVal= ($val1 && $val2); break;
96 100
             default:  throw new Exception("Error in expression - unknown comp : ".$comp);
97 101
         }
98
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
102
+        if ($negate === true) {
103
+        	$retVal = ! $retVal;
104
+        }
105
+        // Inverse result if negate before expression
99 106
         
100 107
         return $retVal;
101 108
     }
@@ -116,10 +123,14 @@  discard block
 block discarded – undo
116 123
         list($type1,$val1) = $this->eval_getElement($rule,$item);
117 124
         //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
118 125
         
119
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
126
+        if ($item==strlen($rule)) {
127
+        	// If only element, return value, but only boolean
120 128
         {
121 129
             if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
122
-            if ($negate === true) $val1= ! $val1;
130
+        }
131
+            if ($negate === true) {
132
+            	$val1= ! $val1;
133
+            }
123 134
             return $val1;
124 135
         }
125 136
         
@@ -128,31 +139,41 @@  discard block
 block discarded – undo
128 139
         //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
129 140
         
130 141
         // Third element : number, string or ()
131
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
142
+        if ( $rule[$item] == '!') {
143
+        	// starts with a ! so evaluate whats next
132 144
         {
133 145
             $item++;
134
-            if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
146
+        }
147
+            if ($typec != 1) {
148
+            	throw new Exception("Mixing boolean and comparison : ".$rule);
149
+            }
135 150
             $val2= ! $this->evaluation($rule,$item);
136 151
             $type2=2; // result is a boolean
137
-        }
138
-        else
152
+        } else
139 153
         {
140 154
             list($type2,$val2) = $this->eval_getElement($rule,$item);
141 155
         }
142 156
         //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
143 157
         
144
-        if ($type1!=$type2)  // cannot compare different types
158
+        if ($type1!=$type2) {
159
+        	// cannot compare different types
145 160
         {
146 161
             throw new Exception("Cannot compare string & number : ".$rule);
147 162
         }
148
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
163
+        }
164
+        if ($typec==1 && $type1 !=2) {
165
+        	// cannot use & or | with string/number
149 166
         {
150 167
             throw new Exception("Cannot use boolean operators with string & number : ".$rule);
151 168
         }
169
+        }
152 170
         
153 171
         $retVal = $this->do_compare($val1, $val2, $comp, $negate);
154 172
         
155
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
173
+        if ($item==strlen($rule)) {
174
+        	return $retVal;
175
+        }
176
+        // End of string : return evaluation
156 177
         // check for logical operator :
157 178
         switch ($rule[$item])
158 179
         {
@@ -191,10 +212,12 @@  discard block
 block discarded – undo
191 212
      */   
192 213
     public function eval_rule($rule,$oidList)
193 214
     {
194
-        if ($rule==null || $rule == '') // Empty rule is always true
215
+        if ($rule==null || $rule == '') {
216
+        	// Empty rule is always true
195 217
         {
196 218
             return true;
197 219
         }
220
+        }
198 221
         $matches=array();
199 222
         while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
200 223
         {
Please login to merge, or discard this patch.
bin/trap_in.php 3 patches
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->logging->log("Exception : ". $e->getMessage(),2,0);
47 45
     }
Please login to merge, or discard this patch.
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->logging->log("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->logging->log("Exception : ". $e->getMessage(),2,0);
46
+	   $trap->logging->log("Exception : ".$e->getMessage(), 2, 0);
47 47
     }
48 48
 }
49 49
 
Please login to merge, or discard this patch.
application/clicommands/MibCommand.php 3 patches
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -22,77 +22,77 @@  discard block
 block discarded – undo
22 22
 class MibCommand extends Command
23 23
 {
24 24
 	/**
25
-	*	Update mib database
26
-	*
27
-	*	USAGE 
28
-	*
29
-	*	icingli trapdirector mib update
30
-	*	
31
-	*	OPTIONS
32
-	*	
33
-	*	--pid <file> : run in background with pid in <file>
34
-	*
35
-	*	--verb    : Set output log to verbose
36
-	*
37
-	*   --force-check : force check of all traps & objects for change. (NOT IMPLEMENTED)
38
-	*/
25
+	 *	Update mib database
26
+	 *
27
+	 *	USAGE 
28
+	 *
29
+	 *	icingli trapdirector mib update
30
+	 *	
31
+	 *	OPTIONS
32
+	 *	
33
+	 *	--pid <file> : run in background with pid in <file>
34
+	 *
35
+	 *	--verb    : Set output log to verbose
36
+	 *
37
+	 *   --force-check : force check of all traps & objects for change. (NOT IMPLEMENTED)
38
+	 */
39 39
 	public function updateAction()
40 40
 	{
41
-	    $background = $this->params->get('pid', null);
42
-	    $logLevel= $this->params->has('verb') ? 4 : 2;
43
-	    if ($this->params->has('force-check')) { echo "Not implemented"; return;}
44
-	    $forceCheck=$this->params->has('force-check')?True:False;
45
-	    $pid=1;
46
-	    if ($background != null)
47
-	    {
48
-	        $file=@fopen($background,'w');
49
-	        if ($file == false)
50
-	        {
51
-	            echo 'Error : cannot open pid file '.$background;
52
-	            return 1;
53
-	        }
54
-	        $pid = pcntl_fork();
55
-	        if ($pid == -1) {
56
-	            echo 'Error : Cannot fork process';
57
-	            return 1;
58
-	        }
59
-	    }
60
-	    $module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
41
+		$background = $this->params->get('pid', null);
42
+		$logLevel= $this->params->has('verb') ? 4 : 2;
43
+		if ($this->params->has('force-check')) { echo "Not implemented"; return;}
44
+		$forceCheck=$this->params->has('force-check')?True:False;
45
+		$pid=1;
46
+		if ($background != null)
47
+		{
48
+			$file=@fopen($background,'w');
49
+			if ($file == false)
50
+			{
51
+				echo 'Error : cannot open pid file '.$background;
52
+				return 1;
53
+			}
54
+			$pid = pcntl_fork();
55
+			if ($pid == -1) {
56
+				echo 'Error : Cannot fork process';
57
+				return 1;
58
+			}
59
+		}
60
+		$module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
61 61
 		require_once($module->getBaseDir() .'/bin/trap_class.php');
62 62
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
63 63
 		$trap = new Trap($icingaweb2_etc);
64 64
 		if ($pid == 1)
65 65
 		{
66
-		    $trap->setLogging($logLevel,'display');
66
+			$trap->setLogging($logLevel,'display');
67 67
 		}
68 68
 		else
69 69
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
70
-		    if ($pid != 0)
71
-		    {
72
-		        // father process
73
-		        fwrite($file,$pid);
74
-		        fclose($file);
75
-		        echo "OK : process $pid in bckground";
76
-		        return 0;
77
-		    }
78
-		    else
79
-		    {  // son process : close all file descriptors and go to a new session
80
-		        fclose($file);		        
70
+			if ($pid != 0)
71
+			{
72
+				// father process
73
+				fwrite($file,$pid);
74
+				fclose($file);
75
+				echo "OK : process $pid in bckground";
76
+				return 0;
77
+			}
78
+			else
79
+			{  // son process : close all file descriptors and go to a new session
80
+				fclose($file);		        
81 81
 // 		        $sid = posix_setsid();
82
-                fclose(STDIN);
83
-                fclose(STDOUT);
84
-                fclose(STDERR);
85
-                try
86
-                {
87
-                    $trap->mibClass->update_mib_database(false,$forceCheck);
88
-                }
89
-                catch (Exception $e)
90
-                {
91
-                    $trap->logging->log('Error in updating : ' . $e->getMessage(),2);
92
-                }
93
-                unlink($background);
94
-                return 0;
95
-		    }
82
+				fclose(STDIN);
83
+				fclose(STDOUT);
84
+				fclose(STDERR);
85
+				try
86
+				{
87
+					$trap->mibClass->update_mib_database(false,$forceCheck);
88
+				}
89
+				catch (Exception $e)
90
+				{
91
+					$trap->logging->log('Error in updating : ' . $e->getMessage(),2);
92
+				}
93
+				unlink($background);
94
+				return 0;
95
+			}
96 96
 		    
97 97
 		}
98 98
 		
@@ -110,28 +110,28 @@  discard block
 block discarded – undo
110 110
 		}
111 111
 		if ($pid != 1)
112 112
 		{
113
-		    unlink($background);
113
+			unlink($background);
114 114
 		}
115 115
 	}
116 116
 	/**
117
-	*	purge all mib database NOT IMPLEMENTED
118
-	*
119
-	*	USAGE 
120
-	*
121
-	*	icingli trapdirector mib purge --confirm
122
-	*	
123
-	*	OPTIONS
124
-	*	
125
-	*	--confirm : needed to execute purge
126
-	*/
117
+	 *	purge all mib database NOT IMPLEMENTED
118
+	 *
119
+	 *	USAGE 
120
+	 *
121
+	 *	icingli trapdirector mib purge --confirm
122
+	 *	
123
+	 *	OPTIONS
124
+	 *	
125
+	 *	--confirm : needed to execute purge
126
+	 */
127 127
 	public function purgeAction()
128 128
 	{
129 129
 		$db_prefix=$this->Config()->get('config', 'database_prefix');
130 130
 		
131 131
 		if (!$this->params->has('confirm'))
132 132
 		{
133
-		    echo "This needs confirmation with '--confirm'\n";
134
-		    return;
133
+			echo "This needs confirmation with '--confirm'\n";
134
+			return;
135 135
 		}
136 136
 		
137 137
 		$Config = new TrapModuleConfig($db_prefix);
@@ -144,9 +144,9 @@  discard block
 block discarded – undo
144 144
 			$db = IcingaDbConnection::fromResourceName($dbresource)->getConnection();
145 145
 			
146 146
 			$query = $db->delete(
147
-			    $Config->getMIBCacheTableName(),
148
-			    'id>0');
149
-            echo 'Deleted '. $query . " traps and objects\n";
147
+				$Config->getMIBCacheTableName(),
148
+				'id>0');
149
+			echo 'Deleted '. $query . " traps and objects\n";
150 150
 		}
151 151
 		catch (Exception $e)
152 152
 		{
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -38,39 +38,39 @@  discard block
 block discarded – undo
38 38
 	*/
39 39
 	public function updateAction()
40 40
 	{
41
-	    $background = $this->params->get('pid', null);
42
-	    $logLevel= $this->params->has('verb') ? 4 : 2;
43
-	    if ($this->params->has('force-check')) { echo "Not implemented"; return;}
44
-	    $forceCheck=$this->params->has('force-check')?True:False;
41
+	    $background=$this->params->get('pid', null);
42
+	    $logLevel=$this->params->has('verb') ? 4 : 2;
43
+	    if ($this->params->has('force-check')) { echo "Not implemented"; return; }
44
+	    $forceCheck=$this->params->has('force-check') ?True:False;
45 45
 	    $pid=1;
46 46
 	    if ($background != null)
47 47
 	    {
48
-	        $file=@fopen($background,'w');
48
+	        $file=@fopen($background, 'w');
49 49
 	        if ($file == false)
50 50
 	        {
51 51
 	            echo 'Error : cannot open pid file '.$background;
52 52
 	            return 1;
53 53
 	        }
54
-	        $pid = pcntl_fork();
54
+	        $pid=pcntl_fork();
55 55
 	        if ($pid == -1) {
56 56
 	            echo 'Error : Cannot fork process';
57 57
 	            return 1;
58 58
 	        }
59 59
 	    }
60 60
 	    $module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
61
-		require_once($module->getBaseDir() .'/bin/trap_class.php');
61
+		require_once($module->getBaseDir().'/bin/trap_class.php');
62 62
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
63
-		$trap = new Trap($icingaweb2_etc);
63
+		$trap=new Trap($icingaweb2_etc);
64 64
 		if ($pid == 1)
65 65
 		{
66
-		    $trap->setLogging($logLevel,'display');
66
+		    $trap->setLogging($logLevel, 'display');
67 67
 		}
68 68
 		else
69 69
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
70 70
 		    if ($pid != 0)
71 71
 		    {
72 72
 		        // father process
73
-		        fwrite($file,$pid);
73
+		        fwrite($file, $pid);
74 74
 		        fclose($file);
75 75
 		        echo "OK : process $pid in bckground";
76 76
 		        return 0;
@@ -84,11 +84,11 @@  discard block
 block discarded – undo
84 84
                 fclose(STDERR);
85 85
                 try
86 86
                 {
87
-                    $trap->mibClass->update_mib_database(false,$forceCheck);
87
+                    $trap->mibClass->update_mib_database(false, $forceCheck);
88 88
                 }
89 89
                 catch (Exception $e)
90 90
                 {
91
-                    $trap->logging->log('Error in updating : ' . $e->getMessage(),2);
91
+                    $trap->logging->log('Error in updating : '.$e->getMessage(), 2);
92 92
                 }
93 93
                 unlink($background);
94 94
                 return 0;
@@ -100,13 +100,13 @@  discard block
 block discarded – undo
100 100
 		{
101 101
 			echo "Update main mib database : \n";
102 102
 			echo "# (trap found) C (trap already processed) . (every 2 seconds) : \n";
103
-			$trap->mibClass->update_mib_database(true,$forceCheck);
103
+			$trap->mibClass->update_mib_database(true, $forceCheck);
104 104
 			echo "Done\n";
105 105
 			
106 106
 		}
107 107
 		catch (Exception $e)
108 108
 		{
109
-			echo 'Error in updating : ' . $e->getMessage();
109
+			echo 'Error in updating : '.$e->getMessage();
110 110
 		}
111 111
 		if ($pid != 1)
112 112
 		{
@@ -134,23 +134,23 @@  discard block
 block discarded – undo
134 134
 		    return;
135 135
 		}
136 136
 		
137
-		$Config = new TrapModuleConfig($db_prefix);
137
+		$Config=new TrapModuleConfig($db_prefix);
138 138
 		
139 139
 		try
140 140
 		{
141 141
 			
142 142
 			$dbresource=$this->Config()->get('config', 'database');
143 143
 			echo "DB name : $dbresource\n";
144
-			$db = IcingaDbConnection::fromResourceName($dbresource)->getConnection();
144
+			$db=IcingaDbConnection::fromResourceName($dbresource)->getConnection();
145 145
 			
146
-			$query = $db->delete(
146
+			$query=$db->delete(
147 147
 			    $Config->getMIBCacheTableName(),
148 148
 			    'id>0');
149
-            echo 'Deleted '. $query . " traps and objects\n";
149
+            echo 'Deleted '.$query." traps and objects\n";
150 150
 		}
151 151
 		catch (Exception $e)
152 152
 		{
153
-			echo 'Error in DB : ' . $e->getMessage();
153
+			echo 'Error in DB : '.$e->getMessage();
154 154
 		}	   
155 155
 	}  	 	
156 156
 
Please login to merge, or discard this patch.
Braces   +5 added lines, -10 removed lines patch added patch discarded remove patch
@@ -64,8 +64,7 @@  discard block
 block discarded – undo
64 64
 		if ($pid == 1)
65 65
 		{
66 66
 		    $trap->setLogging($logLevel,'display');
67
-		}
68
-		else
67
+		} else
69 68
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
70 69
 		    if ($pid != 0)
71 70
 		    {
@@ -74,8 +73,7 @@  discard block
 block discarded – undo
74 73
 		        fclose($file);
75 74
 		        echo "OK : process $pid in bckground";
76 75
 		        return 0;
77
-		    }
78
-		    else
76
+		    } else
79 77
 		    {  // son process : close all file descriptors and go to a new session
80 78
 		        fclose($file);		        
81 79
 // 		        $sid = posix_setsid();
@@ -85,8 +83,7 @@  discard block
 block discarded – undo
85 83
                 try
86 84
                 {
87 85
                     $trap->mibClass->update_mib_database(false,$forceCheck);
88
-                }
89
-                catch (Exception $e)
86
+                } catch (Exception $e)
90 87
                 {
91 88
                     $trap->logging->log('Error in updating : ' . $e->getMessage(),2);
92 89
                 }
@@ -103,8 +100,7 @@  discard block
 block discarded – undo
103 100
 			$trap->mibClass->update_mib_database(true,$forceCheck);
104 101
 			echo "Done\n";
105 102
 			
106
-		}
107
-		catch (Exception $e)
103
+		} catch (Exception $e)
108 104
 		{
109 105
 			echo 'Error in updating : ' . $e->getMessage();
110 106
 		}
@@ -147,8 +143,7 @@  discard block
 block discarded – undo
147 143
 			    $Config->getMIBCacheTableName(),
148 144
 			    'id>0');
149 145
             echo 'Deleted '. $query . " traps and objects\n";
150
-		}
151
-		catch (Exception $e)
146
+		} catch (Exception $e)
152 147
 		{
153 148
 			echo 'Error in DB : ' . $e->getMessage();
154 149
 		}	   
Please login to merge, or discard this patch.
application/controllers/SettingsController.php 3 patches
Braces   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -52,8 +52,7 @@  discard block
 block discarded – undo
52 52
               $this->Config()->saveIni();
53 53
               $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54 54
               //$emptyConfig=1;
55
-          }
56
-          catch (Exception $e)
55
+          } catch (Exception $e)
57 56
           {
58 57
               $this->view->configErrorDetected=$e->getMessage();
59 58
           }
@@ -141,8 +140,7 @@  discard block
 block discarded – undo
141 140
               $this->view->apimessage='API config : ' . $e->getMessage();
142 141
               $this->view->apimessageError=true;
143 142
           }
144
-      }
145
-      else
143
+      } else
146 144
       {
147 145
           $this->view->apimessage='API parameters not configured';
148 146
           $this->view->apimessageError=true;
@@ -208,7 +206,9 @@  discard block
 block discarded – undo
208 206
           $input="154865134987aaaa";
209 207
           exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
210 208
           
211
-          if (! isset($output[0])) $output[0]="NO OUT";
209
+          if (! isset($output[0])) {
210
+          	$output[0]="NO OUT";
211
+          }
212 212
           
213 213
           if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
214 214
           {
@@ -310,8 +310,7 @@  discard block
 block discarded – undo
310 310
 	    $this->getUIDatabase()->testGetDb(); // Get DB in test mode
311 311
 	    printf('Schema already exists');
312 312
 	    
313
-	} 
314
-	catch (DBException $e) 
313
+	} catch (DBException $e) 
315 314
 	{
316 315
 
317 316
 		printf('Creating schema : <br>');
@@ -367,8 +366,7 @@  discard block
 block discarded – undo
367 366
           $this->getUIDatabase()->testGetDb(); // Get DB in test mode
368 367
           echo 'Schema already exists and is up to date<br>';
369 368
           return;
370
-      }
371
-      catch (DBException $e)
369
+      } catch (DBException $e)
372 370
       {
373 371
           $dberror=$e->getArray(); 
374 372
       }
@@ -452,16 +450,18 @@  discard block
 block discarded – undo
452 450
           }
453 451
           // Assume there is only one line... TODO : see if there is a better way to do this
454 452
           $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
455
-          if (!preg_match('/-n/',$line))
456
-              return array(1,'snmptrapd has no -n option : '.$line);
457
-          if (!preg_match('/-O[^ ]*n/',$line))
458
-              return array(1,'snmptrapd has no -On option : '.$line);
459
-          if (!preg_match('/-O[^ ]*e/',$line))
460
-              return array(1,'snmptrapd has no -Oe option : '.$line);
453
+          if (!preg_match('/-n/',$line)) {
454
+                        return array(1,'snmptrapd has no -n option : '.$line);
455
+          }
456
+          if (!preg_match('/-O[^ ]*n/',$line)) {
457
+                        return array(1,'snmptrapd has no -On option : '.$line);
458
+          }
459
+          if (!preg_match('/-O[^ ]*e/',$line)) {
460
+                        return array(1,'snmptrapd has no -Oe option : '.$line);
461
+          }
461 462
 
462 463
           return array(0,'snmptrapd listening to UDP/162, options : '.$line);
463
-      }
464
-      else
464
+      } else
465 465
       {
466 466
           return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
467 467
       }
Please login to merge, or discard this patch.
Indentation   +231 added lines, -231 removed lines patch added patch discarded remove patch
@@ -25,16 +25,16 @@  discard block
 block discarded – undo
25 25
    */
26 26
   private function get_param()
27 27
   {
28
-      $dberrorMsg=$this->params->get('dberror');
29
-      if ($dberrorMsg != '')
30
-      {
31
-          $this->view->errorDetected=$dberrorMsg;
32
-      }
33
-      $dberrorMsg=$this->params->get('idodberror');
34
-      if ($dberrorMsg != '')
35
-      {
36
-          $this->view->errorDetected=$dberrorMsg;
37
-      }
28
+	  $dberrorMsg=$this->params->get('dberror');
29
+	  if ($dberrorMsg != '')
30
+	  {
31
+		  $this->view->errorDetected=$dberrorMsg;
32
+	  }
33
+	  $dberrorMsg=$this->params->get('idodberror');
34
+	  if ($dberrorMsg != '')
35
+	  {
36
+		  $this->view->errorDetected=$dberrorMsg;
37
+	  }
38 38
   }
39 39
   
40 40
   /**
@@ -43,22 +43,22 @@  discard block
 block discarded – undo
43 43
    */
44 44
   private function check_empty_config()
45 45
   {
46
-      $this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
47
-      if ($this->Config()->isEmpty() == true)
48
-      {
49
-          $this->Config()->setSection('config'); // Set base config section.
50
-          try
51
-          {
52
-              $this->Config()->saveIni();
53
-              $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54
-              //$emptyConfig=1;
55
-          }
56
-          catch (Exception $e)
57
-          {
58
-              $this->view->configErrorDetected=$e->getMessage();
59
-          }
46
+	  $this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
47
+	  if ($this->Config()->isEmpty() == true)
48
+	  {
49
+		  $this->Config()->setSection('config'); // Set base config section.
50
+		  try
51
+		  {
52
+			  $this->Config()->saveIni();
53
+			  $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54
+			  //$emptyConfig=1;
55
+		  }
56
+		  catch (Exception $e)
57
+		  {
58
+			  $this->view->configErrorDetected=$e->getMessage();
59
+		  }
60 60
           
61
-      }
61
+	  }
62 62
   }
63 63
   
64 64
   /**
@@ -71,56 +71,56 @@  discard block
 block discarded – undo
71 71
    */
72 72
   private function check_db()
73 73
   {
74
-      $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
-          0	=>	array('Database configuration OK','',''),
76
-          1	=>	array('Database set in config.ini','No database in config.ini',''),
77
-          2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
78
-              Url::fromPath('config/resource')),
79
-          3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
80
-              Url::fromPath('trapdirector/settings/createschema')),
81
-          4	=>	array('Schema is set','Schema is not set for ',
82
-              Url::fromPath('trapdirector/settings/createschema')),
83
-          5	=>	array('Schema is up to date','Schema is outdated :',
84
-              Url::fromPath('trapdirector/settings/updateschema')),
85
-      );
74
+	  $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
+		  0	=>	array('Database configuration OK','',''),
76
+		  1	=>	array('Database set in config.ini','No database in config.ini',''),
77
+		  2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
78
+			  Url::fromPath('config/resource')),
79
+		  3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
80
+			  Url::fromPath('trapdirector/settings/createschema')),
81
+		  4	=>	array('Schema is set','Schema is not set for ',
82
+			  Url::fromPath('trapdirector/settings/createschema')),
83
+		  5	=>	array('Schema is up to date','Schema is outdated :',
84
+			  Url::fromPath('trapdirector/settings/updateschema')),
85
+	  );
86 86
       
87
-      try {
88
-          $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
-          $dberror=array(0,'');
90
-      } catch (DBException $e) {
91
-          $dberror = $e->getArray();
92
-      }
87
+	  try {
88
+		  $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
+		  $dberror=array(0,'');
90
+	  } catch (DBException $e) {
91
+		  $dberror = $e->getArray();
92
+	  }
93 93
       
94
-      $this->view->db_error=$dberror[0];
95
-      switch ($dberror[0])
96
-      {
97
-          case 2:
98
-          case 4:
99
-              $db_message[$dberror[0]][1] .= $dberror[1];
100
-              break;
101
-          case 3:
102
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
103
-              break;
104
-          case 5:
105
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
106
-              break;
107
-          case 0:
108
-          case 1:
109
-              break;
110
-          default:
111
-              new ProgrammingError('Out of bond result from database test');
112
-      }
113
-      $this->view->message=$db_message;
94
+	  $this->view->db_error=$dberror[0];
95
+	  switch ($dberror[0])
96
+	  {
97
+		  case 2:
98
+		  case 4:
99
+			  $db_message[$dberror[0]][1] .= $dberror[1];
100
+			  break;
101
+		  case 3:
102
+			  $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
103
+			  break;
104
+		  case 5:
105
+			  $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
106
+			  break;
107
+		  case 0:
108
+		  case 1:
109
+			  break;
110
+		  default:
111
+			  new ProgrammingError('Out of bond result from database test');
112
+	  }
113
+	  $this->view->message=$db_message;
114 114
       
115
-      try {
116
-          $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
-          $dberror=array(0,'');
118
-      } catch (DBException $e) {
119
-          $dberror = $e->getArray();
120
-      }
115
+	  try {
116
+		  $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
+		  $dberror=array(0,'');
118
+	  } catch (DBException $e) {
119
+		  $dberror = $e->getArray();
120
+	  }
121 121
       
122
-      $this->view->ido_db_error=$dberror[0];
123
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
122
+	  $this->view->ido_db_error=$dberror[0];
123
+	  $this->view->ido_message='IDO Database : ' . $dberror[1];
124 124
   }
125 125
   
126 126
   /**
@@ -130,23 +130,23 @@  discard block
 block discarded – undo
130 130
    */
131 131
   private function check_api()
132 132
   {
133
-      if ($this->Config()->get('config', 'icingaAPI_host') != '')
134
-      {
135
-          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
136
-          $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
137
-          try {
138
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
139
-              //$this->view->apimessageError=false;
140
-          } catch (RuntimeException $e) {
141
-              $this->view->apimessage='API config : ' . $e->getMessage();
142
-              $this->view->apimessageError=true;
143
-          }
144
-      }
145
-      else
146
-      {
147
-          $this->view->apimessage='API parameters not configured';
148
-          $this->view->apimessageError=true;
149
-      }
133
+	  if ($this->Config()->get('config', 'icingaAPI_host') != '')
134
+	  {
135
+		  $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
136
+		  $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
137
+		  try {
138
+			  list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
139
+			  //$this->view->apimessageError=false;
140
+		  } catch (RuntimeException $e) {
141
+			  $this->view->apimessage='API config : ' . $e->getMessage();
142
+			  $this->view->apimessageError=true;
143
+		  }
144
+	  }
145
+	  else
146
+	  {
147
+		  $this->view->apimessage='API parameters not configured';
148
+		  $this->view->apimessageError=true;
149
+	  }
150 150
   }
151 151
 
152 152
   /**
@@ -157,21 +157,21 @@  discard block
 block discarded – undo
157 157
    */
158 158
   private function check_icingaweb_path()
159 159
   {
160
-      $this->view->icingaEtcWarn=0;
161
-      $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
162
-      if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
163
-      {
164
-          $output=array();
160
+	  $this->view->icingaEtcWarn=0;
161
+	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
162
+	  if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
163
+	  {
164
+		  $output=array();
165 165
           
166
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
166
+		  exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
167 167
           
168 168
           
169
-          if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
170
-          {
171
-              $this->view->icingaEtcWarn=1;
172
-              $this->view->icingaweb2_etc=$icingaweb2_etc;
173
-          }
174
-      }
169
+		  if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
170
+		  {
171
+			  $this->view->icingaEtcWarn=1;
172
+			  $this->view->icingaweb2_etc=$icingaweb2_etc;
173
+		  }
174
+	  }
175 175
       
176 176
   }
177 177
   
@@ -182,15 +182,15 @@  discard block
 block discarded – undo
182 182
    */
183 183
   private function get_db_list($allowed)
184 184
   {
185
-      $resources = array();
186
-      foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
187
-      {
188
-          if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
189
-          {
190
-              $resources[$name] = $name;
191
-          }
192
-      }
193
-      return $resources;
185
+	  $resources = array();
186
+	  foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
187
+	  {
188
+		  if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
189
+		  {
190
+			  $resources[$name] = $name;
191
+		  }
192
+	  }
193
+	  return $resources;
194 194
   }
195 195
   
196 196
   /**
@@ -199,23 +199,23 @@  discard block
 block discarded – undo
199 199
    */
200 200
   private function get_php_binary()
201 201
   {
202
-      $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
202
+	  $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
203 203
 
204
-      foreach ($phpBinary as $phpBin )
205
-      {
206
-          $output=array();
207
-          $retCode=255;
208
-          $input="154865134987aaaa";
209
-          exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
204
+	  foreach ($phpBinary as $phpBin )
205
+	  {
206
+		  $output=array();
207
+		  $retCode=255;
208
+		  $input="154865134987aaaa";
209
+		  exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
210 210
           
211
-          if (! isset($output[0])) $output[0]="NO OUT";
211
+		  if (! isset($output[0])) $output[0]="NO OUT";
212 212
           
213
-          if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
214
-          {
215
-              return $phpBin;
216
-          }          
217
-      }
218
-      return NULL;
213
+		  if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
214
+		  {
215
+			  return $phpBin;
216
+		  }          
217
+	  }
218
+	  return NULL;
219 219
   }
220 220
   
221 221
   /**
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
   public function indexAction()
235 235
   {
236 236
       
237
-    // CHeck permissions : display tests in any case, but no configuration.
237
+	// CHeck permissions : display tests in any case, but no configuration.
238 238
 	$this->view->configPermission=$this->checkModuleConfigPermission(1);
239 239
 	// But check read permission
240 240
 	$this->checkReadPermission();
@@ -242,16 +242,16 @@  discard block
 block discarded – undo
242 242
 	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');	
243 243
 	
244 244
 	// Get message : sent on configuration problems detected by controllers
245
-    $this->get_param();
245
+	$this->get_param();
246 246
     
247
-    // Test if configuration exists, if not create for installer script
247
+	// Test if configuration exists, if not create for installer script
248 248
 	$this->check_empty_config();
249 249
 
250 250
 	// Test Database
251
-    $this->check_db();
251
+	$this->check_db();
252 252
 	
253 253
 	//********* Test API
254
-    $this->check_api();
254
+	$this->check_api();
255 255
 	
256 256
 	//*********** Test snmptrapd alive and options
257 257
 	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
 	$phpBinary = $this->get_php_binary();
266 266
 	if ($phpBinary == null)
267 267
 	{
268
-	    $phpBinary = ' PHP BINARY NOT FOUND ';
268
+		$phpBinary = ' PHP BINARY NOT FOUND ';
269 269
 	    
270 270
 	}
271 271
 	
@@ -273,11 +273,11 @@  discard block
 block discarded – undo
273 273
 	$this->view->traps_in_config= $phpBinary . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
274 274
 	
275 275
 	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
276
-	    . ' -c all ' 
277
-	    . ' -d ' . $this->Module()->getBaseDir()
278
-	    . ' -p ' . $phpBinary
279
-	    . ' -a ' . exec('whoami')
280
-	    . ' -w ' . Icinga::app()->getConfigDir();
276
+		. ' -c all ' 
277
+		. ' -d ' . $this->Module()->getBaseDir()
278
+		. ' -p ' . $phpBinary
279
+		. ' -a ' . exec('whoami')
280
+		. ' -w ' . Icinga::app()->getConfigDir();
281 281
 	        
282 282
 	// ******************* configuration form setup*******************
283 283
 	$this->view->form = $form = new TrapsConfigForm();
@@ -311,15 +311,15 @@  discard block
 block discarded – undo
311 311
   public function satelliteAction()
312 312
   {
313 313
       
314
-      // CHeck permissions
315
-      $this->view->configPermission=$this->checkModuleConfigPermission();
314
+	  // CHeck permissions
315
+	  $this->view->configPermission=$this->checkModuleConfigPermission();
316 316
       
317
-      // Setup tabs
318
-      $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
317
+	  // Setup tabs
318
+	  $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
319 319
       
320
-      $this->view->masterHASet = FALSE;
320
+	  $this->view->masterHASet = FALSE;
321 321
       
322
-      $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
322
+	  $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
323 323
   }
324 324
   
325 325
   
@@ -335,8 +335,8 @@  discard block
 block discarded – undo
335 335
 	
336 336
 	try 
337 337
 	{
338
-	    $this->getUIDatabase()->testGetDb(); // Get DB in test mode
339
-	    printf('Schema already exists');
338
+		$this->getUIDatabase()->testGetDb(); // Get DB in test mode
339
+		printf('Schema already exists');
340 340
 	    
341 341
 	} 
342 342
 	catch (DBException $e) 
@@ -347,19 +347,19 @@  discard block
 block discarded – undo
347 347
 		// Get module database name
348 348
 		$dbName=$this->Config()->get('config', 'database');
349 349
 
350
-        $dbResource = ResourceFactory::getResourceConfig($dbName);
351
-        $dbType=$dbResource->get('db');
352
-        switch ($dbType) {
353
-          case 'mysql':
354
-              $dbFileExt='sql';
355
-              break;
356
-          case 'pgsql':
357
-              $dbFileExt='pgsql';
358
-              break;
359
-          default:
360
-              printf("Database configuration error : Unsuported DB");
361
-              return;
362
-        } 
350
+		$dbResource = ResourceFactory::getResourceConfig($dbName);
351
+		$dbType=$dbResource->get('db');
352
+		switch ($dbType) {
353
+		  case 'mysql':
354
+			  $dbFileExt='sql';
355
+			  break;
356
+		  case 'pgsql':
357
+			  $dbFileExt='pgsql';
358
+			  break;
359
+		  default:
360
+			  printf("Database configuration error : Unsuported DB");
361
+			  return;
362
+		} 
363 363
 
364 364
 		printf('<pre>');
365 365
 		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
@@ -383,32 +383,32 @@  discard block
 block discarded – undo
383 383
   public function updateschemaAction()
384 384
   {
385 385
 	  $this->checkModuleConfigPermission();
386
-      $this->getTabs()->add('get',array(
387
-    		'active'	=> true,
388
-    		'label'		=> $this->translate('Update Schema'),
389
-    		'url'		=> Url::fromRequest()
390
-    	));
386
+	  $this->getTabs()->add('get',array(
387
+			'active'	=> true,
388
+			'label'		=> $this->translate('Update Schema'),
389
+			'url'		=> Url::fromRequest()
390
+		));
391 391
 	  // check if needed
392 392
 	  $dberror=array();
393
-      try
394
-      {
395
-          $this->getUIDatabase()->testGetDb(); // Get DB in test mode
396
-          echo 'Schema already exists and is up to date<br>';
397
-          return;
398
-      }
399
-      catch (DBException $e)
400
-      {
401
-          $dberror=$e->getArray(); 
402
-      }
393
+	  try
394
+	  {
395
+		  $this->getUIDatabase()->testGetDb(); // Get DB in test mode
396
+		  echo 'Schema already exists and is up to date<br>';
397
+		  return;
398
+	  }
399
+	  catch (DBException $e)
400
+	  {
401
+		  $dberror=$e->getArray(); 
402
+	  }
403 403
 	  
404 404
 	  echo 'Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a><br><br>';
405 405
 	  
406 406
 	  if ($dberror[0] != 5)
407 407
 	  {
408
-	      echo 'Database does not exists or is not setup correctly<br>';
409
-	      return;
408
+		  echo 'Database does not exists or is not setup correctly<br>';
409
+		  return;
410 410
 	  }
411
-      // setup
411
+	  // setup
412 412
 	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
413 413
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
414 414
 	  $debug_level=4;
@@ -421,20 +421,20 @@  discard block
 block discarded – undo
421 421
 	  $target_version=$dberror[2];
422 422
 	  
423 423
 	  if ($this->params->get('msgok') == null) {
424
-	      // Check for messages and display if any
425
-              echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
426
-	      $Trap->setLogging(2,'syslog');
427
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
428
-	      if ($message != '')
429
-	      {
430
-	          echo 'Note :<br><pre>';
431
-	          echo $message;
432
-	          echo '</pre>';
433
-	          echo '<br>';
434
-	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
435
-	          echo '<br>';
436
-	          return;
437
-	      }
424
+		  // Check for messages and display if any
425
+			  echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
426
+		  $Trap->setLogging(2,'syslog');
427
+		  $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
428
+		  if ($message != '')
429
+		  {
430
+			  echo 'Note :<br><pre>';
431
+			  echo $message;
432
+			  echo '</pre>';
433
+			  echo '<br>';
434
+			  echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
435
+			  echo '<br>';
436
+			  return;
437
+		  }
438 438
 	  }
439 439
 	  
440 440
 	  $Trap->setLogging($debug_level,'display');
@@ -449,50 +449,50 @@  discard block
 block discarded – undo
449 449
   
450 450
   private function checkSnmpTrapd()
451 451
   {
452
-      $psOutput=array();
453
-      // First check is someone is listening to port 162. As not root, we can't have pid... 
454
-      $sspath = exec('which ss 2>/dev/null');
455
-      if(empty($sspath))
456
-      {
457
-          // RHEL based systems
458
-          $sspath = '/usr/sbin/ss';
459
-      }
460
-      if(!is_executable("$sspath"))
461
-      {
462
-          return array(1,"Can not execute $sspath");
463
-      }
464
-      exec("$sspath -lun | grep ':162 '",$psOutput);
465
-      if (count($psOutput) == 0)
466
-      {
467
-          return array(1,'Port UDP/162 is not open : is snmptrapd running?');
468
-      }
469
-      $psOutput=array();
470
-      $selinux_state = '';
471
-      if(is_executable('/usr/sbin/getenforce'))
472
-      {
473
-          $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
474
-      }
475
-      if($selinux_state !== 'Enforcing')
476
-      {
477
-          exec('ps --no-headers -o command -C snmptrapd',$psOutput);
478
-          if (count($psOutput) == 0)
479
-          {
480
-              return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
481
-          }
482
-          // Assume there is only one line... TODO : see if there is a better way to do this
483
-          $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
484
-          if (!preg_match('/-n/',$line))
485
-              return array(1,'snmptrapd has no -n option : '.$line);
486
-          if (!preg_match('/-O[^ ]*n/',$line))
487
-              return array(1,'snmptrapd has no -On option : '.$line);
488
-          if (!preg_match('/-O[^ ]*e/',$line))
489
-              return array(1,'snmptrapd has no -Oe option : '.$line);
452
+	  $psOutput=array();
453
+	  // First check is someone is listening to port 162. As not root, we can't have pid... 
454
+	  $sspath = exec('which ss 2>/dev/null');
455
+	  if(empty($sspath))
456
+	  {
457
+		  // RHEL based systems
458
+		  $sspath = '/usr/sbin/ss';
459
+	  }
460
+	  if(!is_executable("$sspath"))
461
+	  {
462
+		  return array(1,"Can not execute $sspath");
463
+	  }
464
+	  exec("$sspath -lun | grep ':162 '",$psOutput);
465
+	  if (count($psOutput) == 0)
466
+	  {
467
+		  return array(1,'Port UDP/162 is not open : is snmptrapd running?');
468
+	  }
469
+	  $psOutput=array();
470
+	  $selinux_state = '';
471
+	  if(is_executable('/usr/sbin/getenforce'))
472
+	  {
473
+		  $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
474
+	  }
475
+	  if($selinux_state !== 'Enforcing')
476
+	  {
477
+		  exec('ps --no-headers -o command -C snmptrapd',$psOutput);
478
+		  if (count($psOutput) == 0)
479
+		  {
480
+			  return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
481
+		  }
482
+		  // Assume there is only one line... TODO : see if there is a better way to do this
483
+		  $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
484
+		  if (!preg_match('/-n/',$line))
485
+			  return array(1,'snmptrapd has no -n option : '.$line);
486
+		  if (!preg_match('/-O[^ ]*n/',$line))
487
+			  return array(1,'snmptrapd has no -On option : '.$line);
488
+		  if (!preg_match('/-O[^ ]*e/',$line))
489
+			  return array(1,'snmptrapd has no -Oe option : '.$line);
490 490
 
491
-          return array(0,'snmptrapd listening to UDP/162, options : '.$line);
492
-      }
493
-      else
494
-      {
495
-          return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
496
-      }
491
+		  return array(0,'snmptrapd listening to UDP/162, options : '.$line);
492
+	  }
493
+	  else
494
+	  {
495
+		  return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
496
+	  }
497 497
   }
498 498
 }
Please login to merge, or discard this patch.
Spacing   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -72,23 +72,23 @@  discard block
 block discarded – undo
72 72
   private function check_db()
73 73
   {
74 74
       $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
-          0	=>	array('Database configuration OK','',''),
76
-          1	=>	array('Database set in config.ini','No database in config.ini',''),
77
-          2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
75
+          0	=>	array('Database configuration OK', '', ''),
76
+          1	=>	array('Database set in config.ini', 'No database in config.ini', ''),
77
+          2	=>	array('Database exists in Icingaweb2 config', 'Database does not exist in Icingaweb2 : ',
78 78
               Url::fromPath('config/resource')),
79
-          3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
79
+          3	=>	array('Database credentials OK', 'Database does not exist/invalid credentials/no schema : ',
80 80
               Url::fromPath('trapdirector/settings/createschema')),
81
-          4	=>	array('Schema is set','Schema is not set for ',
81
+          4	=>	array('Schema is set', 'Schema is not set for ',
82 82
               Url::fromPath('trapdirector/settings/createschema')),
83
-          5	=>	array('Schema is up to date','Schema is outdated :',
83
+          5	=>	array('Schema is up to date', 'Schema is outdated :',
84 84
               Url::fromPath('trapdirector/settings/updateschema')),
85 85
       );
86 86
       
87 87
       try {
88 88
           $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
-          $dberror=array(0,'');
89
+          $dberror=array(0, '');
90 90
       } catch (DBException $e) {
91
-          $dberror = $e->getArray();
91
+          $dberror=$e->getArray();
92 92
       }
93 93
       
94 94
       $this->view->db_error=$dberror[0];
@@ -96,13 +96,13 @@  discard block
 block discarded – undo
96 96
       {
97 97
           case 2:
98 98
           case 4:
99
-              $db_message[$dberror[0]][1] .= $dberror[1];
99
+              $db_message[$dberror[0]][1].=$dberror[1];
100 100
               break;
101 101
           case 3:
102
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
102
+              $db_message[$dberror[0]][1].=$dberror[1].', Message : '.$dberror[2];
103 103
               break;
104 104
           case 5:
105
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
105
+              $db_message[$dberror[0]][1].=' version '.$dberror[1].', version needed : '.$dberror[2];
106 106
               break;
107 107
           case 0:
108 108
           case 1:
@@ -114,13 +114,13 @@  discard block
 block discarded – undo
114 114
       
115 115
       try {
116 116
           $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
-          $dberror=array(0,'');
117
+          $dberror=array(0, '');
118 118
       } catch (DBException $e) {
119
-          $dberror = $e->getArray();
119
+          $dberror=$e->getArray();
120 120
       }
121 121
       
122 122
       $this->view->ido_db_error=$dberror[0];
123
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
123
+      $this->view->ido_message='IDO Database : '.$dberror[1];
124 124
   }
125 125
   
126 126
   /**
@@ -132,13 +132,13 @@  discard block
 block discarded – undo
132 132
   {
133 133
       if ($this->Config()->get('config', 'icingaAPI_host') != '')
134 134
       {
135
-          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
135
+          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'), $this->Config()->get('config', 'icingaAPI_port'));
136 136
           $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
137 137
           try {
138
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
138
+              list($this->view->apimessageError, $this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
139 139
               //$this->view->apimessageError=false;
140 140
           } catch (RuntimeException $e) {
141
-              $this->view->apimessage='API config : ' . $e->getMessage();
141
+              $this->view->apimessage='API config : '.$e->getMessage();
142 142
               $this->view->apimessageError=true;
143 143
           }
144 144
       }
@@ -163,10 +163,10 @@  discard block
 block discarded – undo
163 163
       {
164 164
           $output=array();
165 165
           
166
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
166
+          exec('cat '.$this->module->getBaseDir().'/bin/trap_in.php | grep "\$icingaweb2Etc=" ', $output);
167 167
           
168 168
           
169
-          if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
169
+          if (!isset($output[0]) || !preg_match('#"'.$icingaweb2_etc.'"#', $output[0]))
170 170
           {
171 171
               $this->view->icingaEtcWarn=1;
172 172
               $this->view->icingaweb2_etc=$icingaweb2_etc;
@@ -182,12 +182,12 @@  discard block
 block discarded – undo
182 182
    */
183 183
   private function get_db_list($allowed)
184 184
   {
185
-      $resources = array();
185
+      $resources=array();
186 186
       foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
187 187
       {
188 188
           if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
189 189
           {
190
-              $resources[$name] = $name;
190
+              $resources[$name]=$name;
191 191
           }
192 192
       }
193 193
       return $resources;
@@ -199,18 +199,18 @@  discard block
 block discarded – undo
199 199
    */
200 200
   private function get_php_binary()
201 201
   {
202
-      $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
202
+      $phpBinary=array(PHP_BINARY, PHP_BINDIR."/php", '/usr/bin/php');
203 203
 
204
-      foreach ($phpBinary as $phpBin )
204
+      foreach ($phpBinary as $phpBin)
205 205
       {
206 206
           $output=array();
207 207
           $retCode=255;
208 208
           $input="154865134987aaaa";
209
-          exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
209
+          exec("$phpBin -r \"echo '$input';\"", $output, $retCode);
210 210
           
211
-          if (! isset($output[0])) $output[0]="NO OUT";
211
+          if (!isset($output[0])) $output[0]="NO OUT";
212 212
           
213
-          if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
213
+          if ($retCode == 0 && preg_match("/$input/", $output[0]) == 1)
214 214
           {
215 215
               return $phpBin;
216 216
           }          
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 	// But check read permission
240 240
 	$this->checkReadPermission();
241 241
 	
242
-	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');	
242
+	$this->view->tabs=$this->Module()->getConfigTabs()->activate('config');	
243 243
 	
244 244
 	// Get message : sent on configuration problems detected by controllers
245 245
     $this->get_param();
@@ -254,39 +254,39 @@  discard block
 block discarded – undo
254 254
     $this->check_api();
255 255
 	
256 256
 	//*********** Test snmptrapd alive and options
257
-	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
257
+	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage)=$this->checkSnmpTrapd();
258 258
 
259 259
 	// List DB in $ressources
260
-	$resources = $this->get_db_list(array('mysql', 'pgsql')); 
260
+	$resources=$this->get_db_list(array('mysql', 'pgsql')); 
261 261
 
262 262
 	// Check standard Icingaweb2 path
263 263
 	$this->check_icingaweb_path();
264 264
 
265
-	$phpBinary = $this->get_php_binary();
265
+	$phpBinary=$this->get_php_binary();
266 266
 	if ($phpBinary == null)
267 267
 	{
268
-	    $phpBinary = ' PHP BINARY NOT FOUND ';
268
+	    $phpBinary=' PHP BINARY NOT FOUND ';
269 269
 	    
270 270
 	}
271 271
 	
272 272
 	// Setup path for mini documentation
273
-	$this->view->traps_in_config= $phpBinary . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
273
+	$this->view->traps_in_config=$phpBinary.' '.$this->Module()->getBaseDir().'/bin/trap_in.php';
274 274
 	
275
-	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
275
+	$this->view->installer=$this->Module()->getBaseDir().'/bin/installer.sh '
276 276
 	    . ' -c all ' 
277
-	    . ' -d ' . $this->Module()->getBaseDir()
278
-	    . ' -p ' . $phpBinary
279
-	    . ' -a ' . exec('whoami')
280
-	    . ' -w ' . Icinga::app()->getConfigDir();
277
+	    . ' -d '.$this->Module()->getBaseDir()
278
+	    . ' -p '.$phpBinary
279
+	    . ' -a '.exec('whoami')
280
+	    . ' -w '.Icinga::app()->getConfigDir();
281 281
 	        
282 282
 	// ******************* configuration form setup*******************
283
-	$this->view->form = $form = new TrapsConfigForm();
283
+	$this->view->form=$form=new TrapsConfigForm();
284 284
 	
285 285
 	// set default paths;
286
-	$this->view->form->setPaths($this->Module()->getBaseDir(),Icinga::app()->getConfigDir());
286
+	$this->view->form->setPaths($this->Module()->getBaseDir(), Icinga::app()->getConfigDir());
287 287
 	
288 288
 	// set default ido database
289
-	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring','backends')->get('icinga','resource'));
289
+	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring', 'backends')->get('icinga', 'resource'));
290 290
 	
291 291
 	// Make form handle request.
292 292
 	$form->setIniConfig($this->Config())
@@ -315,18 +315,18 @@  discard block
 block discarded – undo
315 315
       $this->view->configPermission=$this->checkModuleConfigPermission();
316 316
       
317 317
       // Setup tabs
318
-      $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
318
+      $this->view->tabs=$this->Module()->getConfigTabs()->activate('satellite');	
319 319
       
320
-      $this->view->masterHASet = FALSE;
320
+      $this->view->masterHASet=FALSE;
321 321
       
322
-      $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
322
+      $this->view->masterHAConf=array('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
323 323
   }
324 324
   
325 325
   
326 326
   public function createschemaAction()
327 327
   {
328 328
 	$this->checkModuleConfigPermission();
329
-	$this->getTabs()->add('create_schema',array(
329
+	$this->getTabs()->add('create_schema', array(
330 330
 		'active'	=> true,
331 331
 		'label'		=> $this->translate('Create Schema'),
332 332
 		'url'		=> Url::fromRequest()
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
 		// Get module database name
348 348
 		$dbName=$this->Config()->get('config', 'database');
349 349
 
350
-        $dbResource = ResourceFactory::getResourceConfig($dbName);
350
+        $dbResource=ResourceFactory::getResourceConfig($dbName);
351 351
         $dbType=$dbResource->get('db');
352 352
         switch ($dbType) {
353 353
           case 'mysql':
@@ -362,28 +362,28 @@  discard block
 block discarded – undo
362 362
         } 
363 363
 
364 364
 		printf('<pre>');
365
-		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
365
+		require_once $this->Module()->getBaseDir().'/bin/trap_class.php';
366 366
 		
367 367
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
368 368
 		$debug_level=4;
369
-		$Trap = new Trap($icingaweb2_etc);
370
-		$Trap->setLogging($debug_level,'display');
369
+		$Trap=new Trap($icingaweb2_etc);
370
+		$Trap->setLogging($debug_level, 'display');
371 371
 		
372 372
 		$prefix=$this->Config()->get('config', 'database_prefix');
373 373
 		// schema file : <path>/SQL/schema_v<verion>.<dbtype>
374
-		$schema=$this->Module()->getBaseDir() . 
375
-		'/SQL/schema_v'. $this->getModuleConfig()->getDbCurVersion() . '.' . $dbFileExt;
374
+		$schema=$this->Module()->getBaseDir(). 
375
+		'/SQL/schema_v'.$this->getModuleConfig()->getDbCurVersion().'.'.$dbFileExt;
376 376
 		
377
-		$Trap->trapsDB->create_schema($schema,$prefix);
377
+		$Trap->trapsDB->create_schema($schema, $prefix);
378 378
 		echo '</pre>';
379 379
 	}
380
-	echo '<br><br>Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a>';
380
+	echo '<br><br>Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a>';
381 381
   }
382 382
 
383 383
   public function updateschemaAction()
384 384
   {
385 385
 	  $this->checkModuleConfigPermission();
386
-      $this->getTabs()->add('get',array(
386
+      $this->getTabs()->add('get', array(
387 387
     		'active'	=> true,
388 388
     		'label'		=> $this->translate('Update Schema'),
389 389
     		'url'		=> Url::fromRequest()
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
           $dberror=$e->getArray(); 
402 402
       }
403 403
 	  
404
-	  echo 'Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a><br><br>';
404
+	  echo 'Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a><br><br>';
405 405
 	  
406 406
 	  if ($dberror[0] != 5)
407 407
 	  {
@@ -409,40 +409,40 @@  discard block
 block discarded – undo
409 409
 	      return;
410 410
 	  }
411 411
       // setup
412
-	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
412
+	  require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
413 413
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
414 414
 	  $debug_level=4;
415
-	  $Trap = new Trap($icingaweb2_etc);
415
+	  $Trap=new Trap($icingaweb2_etc);
416 416
 	  
417 417
 	  
418 418
 	  $prefix=$this->Config()->get('config', 'database_prefix');
419
-	  $updateSchema=$this->Module()->getBaseDir() . '/SQL/';
419
+	  $updateSchema=$this->Module()->getBaseDir().'/SQL/';
420 420
 	  
421 421
 	  $target_version=$dberror[2];
422 422
 	  
423 423
 	  if ($this->params->get('msgok') == null) {
424 424
 	      // Check for messages and display if any
425 425
               echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
426
-	      $Trap->setLogging(2,'syslog');
427
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
426
+	      $Trap->setLogging(2, 'syslog');
427
+	      $message=$Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix, true);
428 428
 	      if ($message != '')
429 429
 	      {
430 430
 	          echo 'Note :<br><pre>';
431 431
 	          echo $message;
432 432
 	          echo '</pre>';
433 433
 	          echo '<br>';
434
-	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
434
+	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="'.Url::fromPath('trapdirector/settings/updateschema').'?msgok=1">Click here to update</a>';
435 435
 	          echo '<br>';
436 436
 	          return;
437 437
 	      }
438 438
 	  }
439 439
 	  
440
-	  $Trap->setLogging($debug_level,'display');
440
+	  $Trap->setLogging($debug_level, 'display');
441 441
 	  
442
-	  echo 'Updating schema to '. $target_version . ': <br>';
442
+	  echo 'Updating schema to '.$target_version.': <br>';
443 443
 	  echo '<pre>';
444 444
 	  	  
445
-	  $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix);
445
+	  $Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix);
446 446
 	  echo '</pre>';
447 447
   }  
448 448
 
@@ -451,48 +451,48 @@  discard block
 block discarded – undo
451 451
   {
452 452
       $psOutput=array();
453 453
       // First check is someone is listening to port 162. As not root, we can't have pid... 
454
-      $sspath = exec('which ss 2>/dev/null');
455
-      if(empty($sspath))
454
+      $sspath=exec('which ss 2>/dev/null');
455
+      if (empty($sspath))
456 456
       {
457 457
           // RHEL based systems
458
-          $sspath = '/usr/sbin/ss';
458
+          $sspath='/usr/sbin/ss';
459 459
       }
460
-      if(!is_executable("$sspath"))
460
+      if (!is_executable("$sspath"))
461 461
       {
462
-          return array(1,"Can not execute $sspath");
462
+          return array(1, "Can not execute $sspath");
463 463
       }
464
-      exec("$sspath -lun | grep ':162 '",$psOutput);
464
+      exec("$sspath -lun | grep ':162 '", $psOutput);
465 465
       if (count($psOutput) == 0)
466 466
       {
467
-          return array(1,'Port UDP/162 is not open : is snmptrapd running?');
467
+          return array(1, 'Port UDP/162 is not open : is snmptrapd running?');
468 468
       }
469 469
       $psOutput=array();
470
-      $selinux_state = '';
471
-      if(is_executable('/usr/sbin/getenforce'))
470
+      $selinux_state='';
471
+      if (is_executable('/usr/sbin/getenforce'))
472 472
       {
473
-          $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
473
+          $selinux_state=exec('/usr/sbin/getenforce 2>/dev/null');
474 474
       }
475
-      if($selinux_state !== 'Enforcing')
475
+      if ($selinux_state !== 'Enforcing')
476 476
       {
477
-          exec('ps --no-headers -o command -C snmptrapd',$psOutput);
477
+          exec('ps --no-headers -o command -C snmptrapd', $psOutput);
478 478
           if (count($psOutput) == 0)
479 479
           {
480
-              return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
480
+              return array(1, "UDP/162 : OK, but no snmptrapd process (?)");
481 481
           }
482 482
           // Assume there is only one line... TODO : see if there is a better way to do this
483
-          $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
484
-          if (!preg_match('/-n/',$line))
485
-              return array(1,'snmptrapd has no -n option : '.$line);
486
-          if (!preg_match('/-O[^ ]*n/',$line))
487
-              return array(1,'snmptrapd has no -On option : '.$line);
488
-          if (!preg_match('/-O[^ ]*e/',$line))
489
-              return array(1,'snmptrapd has no -Oe option : '.$line);
483
+          $line=preg_replace('/^.*snmptrapd /', '', $psOutput[0]);
484
+          if (!preg_match('/-n/', $line))
485
+              return array(1, 'snmptrapd has no -n option : '.$line);
486
+          if (!preg_match('/-O[^ ]*n/', $line))
487
+              return array(1, 'snmptrapd has no -On option : '.$line);
488
+          if (!preg_match('/-O[^ ]*e/', $line))
489
+              return array(1, 'snmptrapd has no -Oe option : '.$line);
490 490
 
491
-          return array(0,'snmptrapd listening to UDP/162, options : '.$line);
491
+          return array(0, 'snmptrapd listening to UDP/162, options : '.$line);
492 492
       }
493 493
       else
494 494
       {
495
-          return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
495
+          return array(0, 'A daemon (hidden by SELinux) is listening on UDP/162');
496 496
       }
497 497
   }
498 498
 }
Please login to merge, or discard this patch.
application/controllers/ApiController.php 3 patches
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -11,28 +11,28 @@  discard block
 block discarded – undo
11 11
 class ApiController extends TrapsController
12 12
 {
13 13
 	
14
-    private $json_options=JSON_PRETTY_PRINT;
14
+	private $json_options=JSON_PRETTY_PRINT;
15 15
     
16
-    protected function send_json($object)
17
-    {
18
-        if (isset($object['Error']))
19
-        {
20
-            $this->send_json_error($object);
21
-            return;
22
-        }
23
-        $this->_helper->layout()->disableLayout();
24
-        $this->getResponse()->setHeader('Content-Type', 'application/json', true);
25
-        $this->getResponse()->sendHeaders();
26
-        echo json_encode($object, $this->json_options) . "\n";
27
-    }
16
+	protected function send_json($object)
17
+	{
18
+		if (isset($object['Error']))
19
+		{
20
+			$this->send_json_error($object);
21
+			return;
22
+		}
23
+		$this->_helper->layout()->disableLayout();
24
+		$this->getResponse()->setHeader('Content-Type', 'application/json', true);
25
+		$this->getResponse()->sendHeaders();
26
+		echo json_encode($object, $this->json_options) . "\n";
27
+	}
28 28
 
29
-    protected function send_json_error($object)
30
-    {
31
-        $this->_helper->layout()->disableLayout();
32
-        $this->getResponse()->setHeader('Content-Type', 'application/json', true);
33
-        $this->getResponse()->sendHeaders();
34
-        echo json_encode($object, $this->json_options) . "\n";
35
-    }
29
+	protected function send_json_error($object)
30
+	{
31
+		$this->_helper->layout()->disableLayout();
32
+		$this->getResponse()->setHeader('Content-Type', 'application/json', true);
33
+		$this->getResponse()->sendHeaders();
34
+		echo json_encode($object, $this->json_options) . "\n";
35
+	}
36 36
     
37 37
 	public function indexAction()
38 38
 	{	
@@ -47,18 +47,18 @@  discard block
 block discarded – undo
47 47
 	
48 48
 	public function dboptionActions()
49 49
 	{
50
-	    $this->checkReadPermission();
51
-	    $apiObj= new RestAPI($this);
50
+		$this->checkReadPermission();
51
+		$apiObj= new RestAPI($this);
52 52
 	    
53
-	    $params = $this->getRequest()->getParams();
54
-	    if (isset($params['name']))
55
-	    {
53
+		$params = $this->getRequest()->getParams();
54
+		if (isset($params['name']))
55
+		{
56 56
 	        
57
-	    }
58
-	    else 
59
-	    {
57
+		}
58
+		else 
59
+		{
60 60
 	        
61
-	    }
61
+		}
62 62
 	}
63 63
 	
64 64
 }
65 65
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -23,7 +23,7 @@  discard block
 block discarded – undo
23 23
         $this->_helper->layout()->disableLayout();
24 24
         $this->getResponse()->setHeader('Content-Type', 'application/json', true);
25 25
         $this->getResponse()->sendHeaders();
26
-        echo json_encode($object, $this->json_options) . "\n";
26
+        echo json_encode($object, $this->json_options)."\n";
27 27
     }
28 28
 
29 29
     protected function send_json_error($object)
@@ -31,15 +31,15 @@  discard block
 block discarded – undo
31 31
         $this->_helper->layout()->disableLayout();
32 32
         $this->getResponse()->setHeader('Content-Type', 'application/json', true);
33 33
         $this->getResponse()->sendHeaders();
34
-        echo json_encode($object, $this->json_options) . "\n";
34
+        echo json_encode($object, $this->json_options)."\n";
35 35
     }
36 36
     
37 37
 	public function indexAction()
38 38
 	{	
39 39
 		$this->checkReadPermission();
40
-		$apiObj= new RestAPI($this);
40
+		$apiObj=new RestAPI($this);
41 41
 
42
-		$modif = $apiObj->last_modified();
42
+		$modif=$apiObj->last_modified();
43 43
 		$this->send_json($modif);
44 44
 		//print_r($modif);
45 45
 		return;
@@ -48,9 +48,9 @@  discard block
 block discarded – undo
48 48
 	public function dboptionActions()
49 49
 	{
50 50
 	    $this->checkReadPermission();
51
-	    $apiObj= new RestAPI($this);
51
+	    $apiObj=new RestAPI($this);
52 52
 	    
53
-	    $params = $this->getRequest()->getParams();
53
+	    $params=$this->getRequest()->getParams();
54 54
 	    if (isset($params['name']))
55 55
 	    {
56 56
 	        
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -54,8 +54,7 @@
 block discarded – undo
54 54
 	    if (isset($params['name']))
55 55
 	    {
56 56
 	        
57
-	    }
58
-	    else 
57
+	    } else 
59 58
 	    {
60 59
 	        
61 60
 	    }
Please login to merge, or discard this patch.
library/Trapdirector/TrapsActions/TrapDBQuery.php 3 patches
Indentation   +191 added lines, -191 removed lines patch added patch discarded remove patch
@@ -20,225 +20,225 @@
 block discarded – undo
20 20
 trait TrapDBQuery
21 21
 {
22 22
     
23
-    /** @return TrapsController */
24
-    abstract protected function getTrapCtrl();
23
+	/** @return TrapsController */
24
+	abstract protected function getTrapCtrl();
25 25
 
26
-    /** @return Zend_Db_Adapter_Abstract : returns DB connexion or null on error */
27
-    abstract public function getDbConn();
26
+	/** @return Zend_Db_Adapter_Abstract : returns DB connexion or null on error */
27
+	abstract public function getDbConn();
28 28
     
29
-    /** Add handler rule in traps DB
30
-     *	@param array $params : array(<db item>=><value>)
31
-     *	@return int inserted id
32
-     */
33
-    public function addHandlerRule($params)
34
-    {
35
-        // TODO Check for rule consistency
29
+	/** Add handler rule in traps DB
30
+	 *	@param array $params : array(<db item>=><value>)
31
+	 *	@return int inserted id
32
+	 */
33
+	public function addHandlerRule($params)
34
+	{
35
+		// TODO Check for rule consistency
36 36
         
37
-        $dbConn = $this->getDbConn();
38
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
39
-        // Add last modified date = creation date and username
40
-        $params['created'] = new Zend_Db_Expr('NOW()');
41
-        $params['modified'] = new 	Zend_Db_Expr('NOW()');
42
-        $params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
37
+		$dbConn = $this->getDbConn();
38
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
39
+		// Add last modified date = creation date and username
40
+		$params['created'] = new Zend_Db_Expr('NOW()');
41
+		$params['modified'] = new 	Zend_Db_Expr('NOW()');
42
+		$params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
43 43
         
44
-        $query=$dbConn->insert(
45
-            $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
46
-            $params
47
-            );
48
-        if($query==false)
49
-        {
50
-            return null;
51
-        }
52
-        return $dbConn->lastInsertId();
53
-    }
44
+		$query=$dbConn->insert(
45
+			$this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
46
+			$params
47
+			);
48
+		if($query==false)
49
+		{
50
+			return null;
51
+		}
52
+		return $dbConn->lastInsertId();
53
+	}
54 54
     
55
-    /** Update handler rule in traps DB
56
-     *	@param array $params : (<db item>=><value>)
57
-     *   @param integer $ruleID : rule id in db
58
-     *	@return array affected rows
59
-     */
60
-    public function updateHandlerRule($params,$ruleID)
61
-    {
62
-        // TODO Check for rule consistency
63
-        $dbConn = $this->getDbConn();
64
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
65
-        // Add last modified date = creation date and username
66
-        $params['modified'] = new 	Zend_Db_Expr('NOW()');
67
-        $params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
55
+	/** Update handler rule in traps DB
56
+	 *	@param array $params : (<db item>=><value>)
57
+	 *   @param integer $ruleID : rule id in db
58
+	 *	@return array affected rows
59
+	 */
60
+	public function updateHandlerRule($params,$ruleID)
61
+	{
62
+		// TODO Check for rule consistency
63
+		$dbConn = $this->getDbConn();
64
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
65
+		// Add last modified date = creation date and username
66
+		$params['modified'] = new 	Zend_Db_Expr('NOW()');
67
+		$params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
68 68
         
69
-        $numRows=$dbConn->update(
70
-            $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
71
-            $params,
72
-            'id='.$ruleID
73
-            );
74
-        return $numRows;
75
-    }
69
+		$numRows=$dbConn->update(
70
+			$this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
71
+			$params,
72
+			'id='.$ruleID
73
+			);
74
+		return $numRows;
75
+	}
76 76
     
77
-    /** Delete rule by id
78
-     *	@param int $ruleID rule id
79
-     */
80
-    public function deleteRule($ruleID)
81
-    {
82
-        if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
77
+	/** Delete rule by id
78
+	 *	@param int $ruleID rule id
79
+	 */
80
+	public function deleteRule($ruleID)
81
+	{
82
+		if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
83 83
         
84
-        $dbConn = $this->getDbConn();
85
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
84
+		$dbConn = $this->getDbConn();
85
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
86 86
         
87
-        $query=$dbConn->delete(
88
-            $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
89
-            'id='.$ruleID
90
-            );
91
-        return $query;
92
-    }
87
+		$query=$dbConn->delete(
88
+			$this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
89
+			'id='.$ruleID
90
+			);
91
+		return $query;
92
+	}
93 93
 
94
-    /**
95
-     * Get last trap rule table modification
96
-     * @throws \ErrorException
97
-     * @return Zend_Db_Select
98
-     */
99
-    public function lastModification()
100
-    {
101
-        $dbConn = $this->getDbConn();
102
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
94
+	/**
95
+	 * Get last trap rule table modification
96
+	 * @throws \ErrorException
97
+	 * @return Zend_Db_Select
98
+	 */
99
+	public function lastModification()
100
+	{
101
+		$dbConn = $this->getDbConn();
102
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
103 103
         
104
-        $query = $dbConn->select()
105
-        ->from(
106
-            $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
107
-            array('lastModified'=>'UNIX_TIMESTAMP(MAX(modified))'));
108
-        $returnRow=$dbConn->fetchRow($query);
109
-        return $returnRow->lastmodified;
110
-    }
104
+		$query = $dbConn->select()
105
+		->from(
106
+			$this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
107
+			array('lastModified'=>'UNIX_TIMESTAMP(MAX(modified))'));
108
+		$returnRow=$dbConn->fetchRow($query);
109
+		return $returnRow->lastmodified;
110
+	}
111 111
     
112
-    /** Delete trap by ip & oid
113
-     *	@param $ipAddr string source IP (v4 or v6)
114
-     *	@param $oid string oid
115
-     */
116
-    public function deleteTrap($ipAddr,$oid)
117
-    {
112
+	/** Delete trap by ip & oid
113
+	 *	@param $ipAddr string source IP (v4 or v6)
114
+	 *	@param $oid string oid
115
+	 */
116
+	public function deleteTrap($ipAddr,$oid)
117
+	{
118 118
         
119
-        $dbConn = $this->getDbConn();
120
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
121
-        $condition=null;
122
-        if ($ipAddr != null)
123
-        {
124
-            $condition="source_ip='$ipAddr'";
125
-        }
126
-        if ($oid != null)
127
-        {
128
-            $condition=($condition===null)?'':$condition.' AND ';
129
-            $condition.="trap_oid='$oid'";
130
-        }
131
-        if($condition === null) return null;
132
-        $query=$dbConn->delete(
133
-            $this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
134
-            $condition
135
-            );
136
-        // TODO test ret code etc...
137
-        return $query;
138
-    }
119
+		$dbConn = $this->getDbConn();
120
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
121
+		$condition=null;
122
+		if ($ipAddr != null)
123
+		{
124
+			$condition="source_ip='$ipAddr'";
125
+		}
126
+		if ($oid != null)
127
+		{
128
+			$condition=($condition===null)?'':$condition.' AND ';
129
+			$condition.="trap_oid='$oid'";
130
+		}
131
+		if($condition === null) return null;
132
+		$query=$dbConn->delete(
133
+			$this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
134
+			$condition
135
+			);
136
+		// TODO test ret code etc...
137
+		return $query;
138
+	}
139 139
     
140 140
     
141
-    /** count trap by ip & oid
142
-     *	@param $ipAddr string source IP (v4 or v6)
143
-     *	@param $oid string oid
144
-     */
145
-    public function countTrap($ipAddr,$oid)
146
-    {
141
+	/** count trap by ip & oid
142
+	 *	@param $ipAddr string source IP (v4 or v6)
143
+	 *	@param $oid string oid
144
+	 */
145
+	public function countTrap($ipAddr,$oid)
146
+	{
147 147
         
148
-        $dbConn = $this->getDbConn();
149
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
148
+		$dbConn = $this->getDbConn();
149
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
150 150
         
151
-        $condition=null;
152
-        if ($ipAddr != null)
153
-        {
154
-            $condition="source_ip='$ipAddr'";
155
-        }
156
-        if ($oid != null)
157
-        {
158
-            $condition=($condition===null)?'':$condition.' AND ';
159
-            $condition.="trap_oid='$oid'";
160
-        }
161
-        if($condition === null) return 0;
162
-        $query=$dbConn->select()
163
-            ->from(
164
-                $this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
165
-                array('num'=>'count(*)'))
166
-            ->where($condition);
167
-        $returnRow=$dbConn->fetchRow($query);
168
-        return $returnRow->num;
169
-    }
151
+		$condition=null;
152
+		if ($ipAddr != null)
153
+		{
154
+			$condition="source_ip='$ipAddr'";
155
+		}
156
+		if ($oid != null)
157
+		{
158
+			$condition=($condition===null)?'':$condition.' AND ';
159
+			$condition.="trap_oid='$oid'";
160
+		}
161
+		if($condition === null) return 0;
162
+		$query=$dbConn->select()
163
+			->from(
164
+				$this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
165
+				array('num'=>'count(*)'))
166
+			->where($condition);
167
+		$returnRow=$dbConn->fetchRow($query);
168
+		return $returnRow->num;
169
+	}
170 170
     
171
-    /** get configuration value
172
-     *	@param string $element : configuration name in db
173
-     */
174
-    public function getDBConfigValue($element)
175
-    {
171
+	/** get configuration value
172
+	 *	@param string $element : configuration name in db
173
+	 */
174
+	public function getDBConfigValue($element)
175
+	{
176 176
         
177
-        $dbConn = $this->getDbConn();
178
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
177
+		$dbConn = $this->getDbConn();
178
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
179 179
         
180
-        $query=$dbConn->select()
181
-        ->from(
182
-            $this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
183
-            array('value'=>'value'))
184
-            ->where('name=?',$element);
185
-            $returnRow=$dbConn->fetchRow($query);
186
-            if ($returnRow==null)  // value does not exists
187
-            {
188
-                $default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
189
-                if ( ! isset($default[$element])) return null; // no default and not value
180
+		$query=$dbConn->select()
181
+		->from(
182
+			$this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
183
+			array('value'=>'value'))
184
+			->where('name=?',$element);
185
+			$returnRow=$dbConn->fetchRow($query);
186
+			if ($returnRow==null)  // value does not exists
187
+			{
188
+				$default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
189
+				if ( ! isset($default[$element])) return null; // no default and not value
190 190
                 
191
-                $this->addDBConfigValue($element,$default[$element]);
192
-                return $default[$element];
193
-            }
194
-            if ($returnRow->value == null) // value id empty
195
-            {
196
-                $default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
197
-                if ( ! isset($default[$element])) return null; // no default and not value
198
-                $this->setDBConfigValue($element,$default[$element]);
199
-                return $default[$element];
200
-            }
201
-            return $returnRow->value;
202
-    }
191
+				$this->addDBConfigValue($element,$default[$element]);
192
+				return $default[$element];
193
+			}
194
+			if ($returnRow->value == null) // value id empty
195
+			{
196
+				$default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
197
+				if ( ! isset($default[$element])) return null; // no default and not value
198
+				$this->setDBConfigValue($element,$default[$element]);
199
+				return $default[$element];
200
+			}
201
+			return $returnRow->value;
202
+	}
203 203
     
204
-    /** add configuration value
205
-     *	@param string $element : name of config element
206
-     *   @param string $value : value
207
-     */
204
+	/** add configuration value
205
+	 *	@param string $element : name of config element
206
+	 *   @param string $value : value
207
+	 */
208 208
     
209
-    public function addDBConfigValue($element,$value)
210
-    {
209
+	public function addDBConfigValue($element,$value)
210
+	{
211 211
         
212
-        $dbConn = $this->getDbConn();
213
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
212
+		$dbConn = $this->getDbConn();
213
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
214 214
         
215
-        $query=$dbConn->insert(
216
-            $this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
217
-            array(
218
-                'name' => $element,
219
-                'value'=>$value
220
-            )
221
-            );
222
-        return $query;
223
-    }
215
+		$query=$dbConn->insert(
216
+			$this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
217
+			array(
218
+				'name' => $element,
219
+				'value'=>$value
220
+			)
221
+			);
222
+		return $query;
223
+	}
224 224
     
225
-    /** set configuration value
226
-     *	@param string $element : name of config element
227
-     *   @param string $value : value
228
-     */
229
-    public function setDBConfigValue($element,$value)
230
-    {
225
+	/** set configuration value
226
+	 *	@param string $element : name of config element
227
+	 *   @param string $value : value
228
+	 */
229
+	public function setDBConfigValue($element,$value)
230
+	{
231 231
         
232
-        $dbConn = $this->getDbConn();
233
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
232
+		$dbConn = $this->getDbConn();
233
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
234 234
         
235
-        $query=$dbConn->update(
236
-            $this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
237
-            array('value'=>$value),
238
-            'name=\''.$element.'\''
239
-            );
240
-        return $query;
241
-    }
235
+		$query=$dbConn->update(
236
+			$this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
237
+			array('value'=>$value),
238
+			'name=\''.$element.'\''
239
+			);
240
+		return $query;
241
+	}
242 242
     
243 243
     
244 244
 }
245 245
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -34,18 +34,18 @@  discard block
 block discarded – undo
34 34
     {
35 35
         // TODO Check for rule consistency
36 36
         
37
-        $dbConn = $this->getDbConn();
37
+        $dbConn=$this->getDbConn();
38 38
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
39 39
         // Add last modified date = creation date and username
40
-        $params['created'] = new Zend_Db_Expr('NOW()');
41
-        $params['modified'] = new 	Zend_Db_Expr('NOW()');
42
-        $params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
40
+        $params['created']=new Zend_Db_Expr('NOW()');
41
+        $params['modified']=new 	Zend_Db_Expr('NOW()');
42
+        $params['modifier']=$this->getTrapCtrl()->Auth()->getUser()->getUsername();
43 43
         
44 44
         $query=$dbConn->insert(
45 45
             $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
46 46
             $params
47 47
             );
48
-        if($query==false)
48
+        if ($query == false)
49 49
         {
50 50
             return null;
51 51
         }
@@ -57,14 +57,14 @@  discard block
 block discarded – undo
57 57
      *   @param integer $ruleID : rule id in db
58 58
      *	@return array affected rows
59 59
      */
60
-    public function updateHandlerRule($params,$ruleID)
60
+    public function updateHandlerRule($params, $ruleID)
61 61
     {
62 62
         // TODO Check for rule consistency
63
-        $dbConn = $this->getDbConn();
63
+        $dbConn=$this->getDbConn();
64 64
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
65 65
         // Add last modified date = creation date and username
66
-        $params['modified'] = new 	Zend_Db_Expr('NOW()');
67
-        $params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
66
+        $params['modified']=new 	Zend_Db_Expr('NOW()');
67
+        $params['modifier']=$this->getTrapCtrl()->Auth()->getUser()->getUsername();
68 68
         
69 69
         $numRows=$dbConn->update(
70 70
             $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
@@ -79,9 +79,9 @@  discard block
 block discarded – undo
79 79
      */
80 80
     public function deleteRule($ruleID)
81 81
     {
82
-        if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
82
+        if (!preg_match('/^[0-9]+$/', $ruleID)) { throw new Exception('Invalid id'); }
83 83
         
84
-        $dbConn = $this->getDbConn();
84
+        $dbConn=$this->getDbConn();
85 85
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
86 86
         
87 87
         $query=$dbConn->delete(
@@ -98,10 +98,10 @@  discard block
 block discarded – undo
98 98
      */
99 99
     public function lastModification()
100 100
     {
101
-        $dbConn = $this->getDbConn();
101
+        $dbConn=$this->getDbConn();
102 102
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
103 103
         
104
-        $query = $dbConn->select()
104
+        $query=$dbConn->select()
105 105
         ->from(
106 106
             $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
107 107
             array('lastModified'=>'UNIX_TIMESTAMP(MAX(modified))'));
@@ -113,10 +113,10 @@  discard block
 block discarded – undo
113 113
      *	@param $ipAddr string source IP (v4 or v6)
114 114
      *	@param $oid string oid
115 115
      */
116
-    public function deleteTrap($ipAddr,$oid)
116
+    public function deleteTrap($ipAddr, $oid)
117 117
     {
118 118
         
119
-        $dbConn = $this->getDbConn();
119
+        $dbConn=$this->getDbConn();
120 120
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
121 121
         $condition=null;
122 122
         if ($ipAddr != null)
@@ -125,10 +125,10 @@  discard block
 block discarded – undo
125 125
         }
126 126
         if ($oid != null)
127 127
         {
128
-            $condition=($condition===null)?'':$condition.' AND ';
128
+            $condition=($condition === null) ? '' : $condition.' AND ';
129 129
             $condition.="trap_oid='$oid'";
130 130
         }
131
-        if($condition === null) return null;
131
+        if ($condition === null) return null;
132 132
         $query=$dbConn->delete(
133 133
             $this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
134 134
             $condition
@@ -142,10 +142,10 @@  discard block
 block discarded – undo
142 142
      *	@param $ipAddr string source IP (v4 or v6)
143 143
      *	@param $oid string oid
144 144
      */
145
-    public function countTrap($ipAddr,$oid)
145
+    public function countTrap($ipAddr, $oid)
146 146
     {
147 147
         
148
-        $dbConn = $this->getDbConn();
148
+        $dbConn=$this->getDbConn();
149 149
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
150 150
         
151 151
         $condition=null;
@@ -155,10 +155,10 @@  discard block
 block discarded – undo
155 155
         }
156 156
         if ($oid != null)
157 157
         {
158
-            $condition=($condition===null)?'':$condition.' AND ';
158
+            $condition=($condition === null) ? '' : $condition.' AND ';
159 159
             $condition.="trap_oid='$oid'";
160 160
         }
161
-        if($condition === null) return 0;
161
+        if ($condition === null) return 0;
162 162
         $query=$dbConn->select()
163 163
             ->from(
164 164
                 $this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
@@ -174,28 +174,28 @@  discard block
 block discarded – undo
174 174
     public function getDBConfigValue($element)
175 175
     {
176 176
         
177
-        $dbConn = $this->getDbConn();
177
+        $dbConn=$this->getDbConn();
178 178
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
179 179
         
180 180
         $query=$dbConn->select()
181 181
         ->from(
182 182
             $this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
183 183
             array('value'=>'value'))
184
-            ->where('name=?',$element);
184
+            ->where('name=?', $element);
185 185
             $returnRow=$dbConn->fetchRow($query);
186
-            if ($returnRow==null)  // value does not exists
186
+            if ($returnRow == null)  // value does not exists
187 187
             {
188 188
                 $default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
189
-                if ( ! isset($default[$element])) return null; // no default and not value
189
+                if (!isset($default[$element])) return null; // no default and not value
190 190
                 
191
-                $this->addDBConfigValue($element,$default[$element]);
191
+                $this->addDBConfigValue($element, $default[$element]);
192 192
                 return $default[$element];
193 193
             }
194 194
             if ($returnRow->value == null) // value id empty
195 195
             {
196 196
                 $default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
197
-                if ( ! isset($default[$element])) return null; // no default and not value
198
-                $this->setDBConfigValue($element,$default[$element]);
197
+                if (!isset($default[$element])) return null; // no default and not value
198
+                $this->setDBConfigValue($element, $default[$element]);
199 199
                 return $default[$element];
200 200
             }
201 201
             return $returnRow->value;
@@ -206,10 +206,10 @@  discard block
 block discarded – undo
206 206
      *   @param string $value : value
207 207
      */
208 208
     
209
-    public function addDBConfigValue($element,$value)
209
+    public function addDBConfigValue($element, $value)
210 210
     {
211 211
         
212
-        $dbConn = $this->getDbConn();
212
+        $dbConn=$this->getDbConn();
213 213
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
214 214
         
215 215
         $query=$dbConn->insert(
@@ -226,10 +226,10 @@  discard block
 block discarded – undo
226 226
      *	@param string $element : name of config element
227 227
      *   @param string $value : value
228 228
      */
229
-    public function setDBConfigValue($element,$value)
229
+    public function setDBConfigValue($element, $value)
230 230
     {
231 231
         
232
-        $dbConn = $this->getDbConn();
232
+        $dbConn=$this->getDbConn();
233 233
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
234 234
         
235 235
         $query=$dbConn->update(
Please login to merge, or discard this patch.
Braces   +47 added lines, -15 removed lines patch added patch discarded remove patch
@@ -35,7 +35,9 @@  discard block
 block discarded – undo
35 35
         // TODO Check for rule consistency
36 36
         
37 37
         $dbConn = $this->getDbConn();
38
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
38
+        if ($dbConn === null) {
39
+        	throw new \ErrorException('uncatched db error');
40
+        }
39 41
         // Add last modified date = creation date and username
40 42
         $params['created'] = new Zend_Db_Expr('NOW()');
41 43
         $params['modified'] = new 	Zend_Db_Expr('NOW()');
@@ -61,7 +63,9 @@  discard block
 block discarded – undo
61 63
     {
62 64
         // TODO Check for rule consistency
63 65
         $dbConn = $this->getDbConn();
64
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
66
+        if ($dbConn === null) {
67
+        	throw new \ErrorException('uncatched db error');
68
+        }
65 69
         // Add last modified date = creation date and username
66 70
         $params['modified'] = new 	Zend_Db_Expr('NOW()');
67 71
         $params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
@@ -82,7 +86,9 @@  discard block
 block discarded – undo
82 86
         if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
83 87
         
84 88
         $dbConn = $this->getDbConn();
85
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
89
+        if ($dbConn === null) {
90
+        	throw new \ErrorException('uncatched db error');
91
+        }
86 92
         
87 93
         $query=$dbConn->delete(
88 94
             $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
@@ -99,7 +105,9 @@  discard block
 block discarded – undo
99 105
     public function lastModification()
100 106
     {
101 107
         $dbConn = $this->getDbConn();
102
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
108
+        if ($dbConn === null) {
109
+        	throw new \ErrorException('uncatched db error');
110
+        }
103 111
         
104 112
         $query = $dbConn->select()
105 113
         ->from(
@@ -117,7 +125,9 @@  discard block
 block discarded – undo
117 125
     {
118 126
         
119 127
         $dbConn = $this->getDbConn();
120
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
128
+        if ($dbConn === null) {
129
+        	throw new \ErrorException('uncatched db error');
130
+        }
121 131
         $condition=null;
122 132
         if ($ipAddr != null)
123 133
         {
@@ -128,7 +138,9 @@  discard block
 block discarded – undo
128 138
             $condition=($condition===null)?'':$condition.' AND ';
129 139
             $condition.="trap_oid='$oid'";
130 140
         }
131
-        if($condition === null) return null;
141
+        if($condition === null) {
142
+        	return null;
143
+        }
132 144
         $query=$dbConn->delete(
133 145
             $this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
134 146
             $condition
@@ -146,7 +158,9 @@  discard block
 block discarded – undo
146 158
     {
147 159
         
148 160
         $dbConn = $this->getDbConn();
149
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
161
+        if ($dbConn === null) {
162
+        	throw new \ErrorException('uncatched db error');
163
+        }
150 164
         
151 165
         $condition=null;
152 166
         if ($ipAddr != null)
@@ -158,7 +172,9 @@  discard block
 block discarded – undo
158 172
             $condition=($condition===null)?'':$condition.' AND ';
159 173
             $condition.="trap_oid='$oid'";
160 174
         }
161
-        if($condition === null) return 0;
175
+        if($condition === null) {
176
+        	return 0;
177
+        }
162 178
         $query=$dbConn->select()
163 179
             ->from(
164 180
                 $this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
@@ -175,7 +191,9 @@  discard block
 block discarded – undo
175 191
     {
176 192
         
177 193
         $dbConn = $this->getDbConn();
178
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
194
+        if ($dbConn === null) {
195
+        	throw new \ErrorException('uncatched db error');
196
+        }
179 197
         
180 198
         $query=$dbConn->select()
181 199
         ->from(
@@ -183,18 +201,28 @@  discard block
 block discarded – undo
183 201
             array('value'=>'value'))
184 202
             ->where('name=?',$element);
185 203
             $returnRow=$dbConn->fetchRow($query);
186
-            if ($returnRow==null)  // value does not exists
204
+            if ($returnRow==null) {
205
+            	// value does not exists
187 206
             {
188 207
                 $default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
189
-                if ( ! isset($default[$element])) return null; // no default and not value
208
+            }
209
+                if ( ! isset($default[$element])) {
210
+                	return null;
211
+                }
212
+                // no default and not value
190 213
                 
191 214
                 $this->addDBConfigValue($element,$default[$element]);
192 215
                 return $default[$element];
193 216
             }
194
-            if ($returnRow->value == null) // value id empty
217
+            if ($returnRow->value == null) {
218
+            	// value id empty
195 219
             {
196 220
                 $default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
197
-                if ( ! isset($default[$element])) return null; // no default and not value
221
+            }
222
+                if ( ! isset($default[$element])) {
223
+                	return null;
224
+                }
225
+                // no default and not value
198 226
                 $this->setDBConfigValue($element,$default[$element]);
199 227
                 return $default[$element];
200 228
             }
@@ -210,7 +238,9 @@  discard block
 block discarded – undo
210 238
     {
211 239
         
212 240
         $dbConn = $this->getDbConn();
213
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
241
+        if ($dbConn === null) {
242
+        	throw new \ErrorException('uncatched db error');
243
+        }
214 244
         
215 245
         $query=$dbConn->insert(
216 246
             $this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
@@ -230,7 +260,9 @@  discard block
 block discarded – undo
230 260
     {
231 261
         
232 262
         $dbConn = $this->getDbConn();
233
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
263
+        if ($dbConn === null) {
264
+        	throw new \ErrorException('uncatched db error');
265
+        }
234 266
         
235 267
         $query=$dbConn->update(
236 268
             $this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
Please login to merge, or discard this patch.