Passed
Pull Request — master (#78)
by
unknown
03:12
created
library/Trapdirector/Icinga2API.php 3 patches
Braces   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -84,10 +84,11 @@  discard block
 block discarded – undo
84 84
     {
85 85
         $host = $this->getHostByFilter(
86 86
             'host.__name=="'. $name .'"');
87
-        if (isset($host[0]))
88
-            return $host[0];
89
-        else
90
-            return NULL;
87
+        if (isset($host[0])) {
88
+                    return $host[0];
89
+        } else {
90
+                    return NULL;
91
+        }
91 92
     }
92 93
  
93 94
     /**
@@ -173,8 +174,7 @@  discard block
 block discarded – undo
173 174
                 {
174 175
                     $serviceList[$service->name]=
175 176
                         array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
176
-                }
177
-                else
177
+                } else
178 178
                 {
179 179
                     $serviceList[$service->name]['num']++;
180 180
                 }
Please login to merge, or discard this patch.
Indentation   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -10,303 +10,303 @@
 block discarded – undo
10 10
 class Icinga2API extends IcingaApiBase
11 11
 {
12 12
     
13
-    /**
14
-     * Creates Icinga2API object
15
-     * 
16
-     * @param string $host host name or IP
17
-     * @param number $port API port
18
-     */
19
-    public function __construct($host, $port = 5665)
20
-    {
21
-        parent::__construct($host,$port);
22
-    }
23
-    /**
13
+	/**
14
+	 * Creates Icinga2API object
15
+	 * 
16
+	 * @param string $host host name or IP
17
+	 * @param number $port API port
18
+	 */
19
+	public function __construct($host, $port = 5665)
20
+	{
21
+		parent::__construct($host,$port);
22
+	}
23
+	/**
24 24
 
25 25
 /************ Host query ************/  
26 26
 
27
-    /**
28
-     * return array of host by filter
29
-     * @param string $hostfilter
30
-     * @throws Exception
31
-     * @return array objects : array('__name','name','display_name','id' (=__name), 'address', 'ip4' (=address), 'address6', 'ip6' (=address6)
32
-     */
33
-    public function getHostByFilter(string $hostfilter)
34
-    {
35
-        $hosts = $this->standardQuery(
36
-            'host',
37
-            $hostfilter,
38
-            //'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
39
-            array('__name','name','display_name','address','address6')
40
-            );
41
-        foreach ( array_keys($hosts) as $key )
42
-        {
43
-            $hosts[$key]->id = $hosts[$key]->__name;
44
-            $hosts[$key]->ip4 = $hosts[$key]->address;
45
-            $hosts[$key]->ip6 = $hosts[$key]->address6;
46
-        }
47
-        return $hosts;
48
-    }
27
+	/**
28
+	 * return array of host by filter
29
+	 * @param string $hostfilter
30
+	 * @throws Exception
31
+	 * @return array objects : array('__name','name','display_name','id' (=__name), 'address', 'ip4' (=address), 'address6', 'ip6' (=address6)
32
+	 */
33
+	public function getHostByFilter(string $hostfilter)
34
+	{
35
+		$hosts = $this->standardQuery(
36
+			'host',
37
+			$hostfilter,
38
+			//'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
39
+			array('__name','name','display_name','address','address6')
40
+			);
41
+		foreach ( array_keys($hosts) as $key )
42
+		{
43
+			$hosts[$key]->id = $hosts[$key]->__name;
44
+			$hosts[$key]->ip4 = $hosts[$key]->address;
45
+			$hosts[$key]->ip6 = $hosts[$key]->address6;
46
+		}
47
+		return $hosts;
48
+	}
49 49
     
50
-    /**
51
-     * return array of host by IP (4 or 6)
52
-     * @param string $ip
53
-     * @throws Exception
54
-     * @return array objects : array('__name','name','display_name')
55
-     */
56
-    public function getHostByIP(string $ip) 
57
-    {
58
-        return $this->getHostByFilter('match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6)');
59
-    }
50
+	/**
51
+	 * return array of host by IP (4 or 6)
52
+	 * @param string $ip
53
+	 * @throws Exception
54
+	 * @return array objects : array('__name','name','display_name')
55
+	 */
56
+	public function getHostByIP(string $ip) 
57
+	{
58
+		return $this->getHostByFilter('match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6)');
59
+	}
60 60
 
61 61
     
62
-    /**
63
-     * Get host(s) by name in API
64
-     * @param string $name
65
-     * @return array|NULL[] : see getHostByIP
66
-     */
67
-    public function getHostByName(string $name)
68
-    {
69
-        return $this->getHostByFilter('match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name)');
70
-    }
62
+	/**
63
+	 * Get host(s) by name in API
64
+	 * @param string $name
65
+	 * @return array|NULL[] : see getHostByIP
66
+	 */
67
+	public function getHostByName(string $name)
68
+	{
69
+		return $this->getHostByFilter('match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name)');
70
+	}
71 71
 
72
-    /**
73
-     * Get host(s) by name in API
74
-     * @param string $name
75
-     * @return array|NULL[] : see getHostByIP
76
-     */
77
-    public function getHostByNameOrIP(string $name)
78
-    {
79
-        return $this->getHostByFilter( 
80
-            'match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name) || match("*' . $name . '*",host.address) || match("*' . $name . '*",host.address6)');
81
-    }
72
+	/**
73
+	 * Get host(s) by name in API
74
+	 * @param string $name
75
+	 * @return array|NULL[] : see getHostByIP
76
+	 */
77
+	public function getHostByNameOrIP(string $name)
78
+	{
79
+		return $this->getHostByFilter( 
80
+			'match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name) || match("*' . $name . '*",host.address) || match("*' . $name . '*",host.address6)');
81
+	}
82 82
     
83
-    public function getHostInfoByID(string $name)
84
-    {
85
-        $host = $this->getHostByFilter(
86
-            'host.__name=="'. $name .'"');
87
-        if (isset($host[0]))
88
-            return $host[0];
89
-        else
90
-            return NULL;
91
-    }
83
+	public function getHostInfoByID(string $name)
84
+	{
85
+		$host = $this->getHostByFilter(
86
+			'host.__name=="'. $name .'"');
87
+		if (isset($host[0]))
88
+			return $host[0];
89
+		else
90
+			return NULL;
91
+	}
92 92
  
93
-    /**
94
-     * Get all host and IP from hostgroup
95
-     * @param string $hostGroup
96
-     * @throws Exception
97
-     * @return array : attributes : address, address6, name
98
-     */
99
-    public function getHostsIPByHostGroup($hostGroup)
100
-    {        
101
-        return $this->standardQuery(
102
-            'host', 
103
-            '"' . $hostGroup . '" in host.groups',
104
-            array('address','address6','name')
93
+	/**
94
+	 * Get all host and IP from hostgroup
95
+	 * @param string $hostGroup
96
+	 * @throws Exception
97
+	 * @return array : attributes : address, address6, name
98
+	 */
99
+	public function getHostsIPByHostGroup($hostGroup)
100
+	{        
101
+		return $this->standardQuery(
102
+			'host', 
103
+			'"' . $hostGroup . '" in host.groups',
104
+			array('address','address6','name')
105 105
                 
106
-        );
107
-    }
106
+		);
107
+	}
108 108
 
109 109
 
110
-    /** Get services from host in API
111
-     *	
112
-     *  @throws Exception
113
-     *	@param $id string host name
114
-     *  @param bool $active
115
-     *  @param bool $passive_svc
116
-     *	@return array display_name (of service), service_object_id
117
-     */
118
-    public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
119
-    {
120
-        $filter = 'match("' . $id . '!*", service.__name)';
121
-        if ($active === TRUE)
122
-        {
123
-            $filter .= ' && service.active==true';
124
-        }
125
-        if ($passive_svc === TRUE)
126
-        {
127
-            $filter .= ' && service.enable_passive_checks==true';
128
-        }
129
-        $services =  $this->standardQuery(
130
-            'service',
131
-            $filter,
132
-            array('__name','name','display_name','active')
133
-            );
110
+	/** Get services from host in API
111
+	 *	
112
+	 *  @throws Exception
113
+	 *	@param $id string host name
114
+	 *  @param bool $active
115
+	 *  @param bool $passive_svc
116
+	 *	@return array display_name (of service), service_object_id
117
+	 */
118
+	public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
119
+	{
120
+		$filter = 'match("' . $id . '!*", service.__name)';
121
+		if ($active === TRUE)
122
+		{
123
+			$filter .= ' && service.active==true';
124
+		}
125
+		if ($passive_svc === TRUE)
126
+		{
127
+			$filter .= ' && service.enable_passive_checks==true';
128
+		}
129
+		$services =  $this->standardQuery(
130
+			'service',
131
+			$filter,
132
+			array('__name','name','display_name','active')
133
+			);
134 134
         
135
-        foreach ( array_keys($services) as $key )
136
-        {
137
-            $services[$key]->id = $services[$key]->__name;
138
-        }
135
+		foreach ( array_keys($services) as $key )
136
+		{
137
+			$services[$key]->id = $services[$key]->__name;
138
+		}
139 139
         
140
-        return $services;
140
+		return $services;
141 141
         
142
-    }
142
+	}
143 143
 
144 144
 /************  Host group query ************/    
145
-    /**
146
-     * return array of host by IP (4 or 6) or name
147
-     * @param string $group Host group name
148
-     * @throws Exception
149
-     * @return array objects : array('name','display_name')
150
-     */
151
-    public function getHostsByGroup(string $group)
152
-    {
153
-         return $this->standardQuery(
154
-            'host',
155
-            '"' . $group . '" in host.groups',
156
-            array('name','display_name')
157
-            );
158
-    }
145
+	/**
146
+	 * return array of host by IP (4 or 6) or name
147
+	 * @param string $group Host group name
148
+	 * @throws Exception
149
+	 * @return array objects : array('name','display_name')
150
+	 */
151
+	public function getHostsByGroup(string $group)
152
+	{
153
+		 return $this->standardQuery(
154
+			'host',
155
+			'"' . $group . '" in host.groups',
156
+			array('name','display_name')
157
+			);
158
+	}
159 159
     
160
-    public function getServicesByHostGroupid(string $group)
161
-    {
162
-        $hostList = $this->getHostsByGroup($group);
163
-        //return $hostList;
164
-        $hostNum = count($hostList);
165
-        $serviceList=array();
166
-        foreach ($hostList as $curHost)
167
-        {
168
-            $services = $this->getServicesByHostid($curHost->name);
169
-            foreach ($services as $service)
170
-            {
171
-                //return $service;
172
-                if (! isset($serviceList[$service->name]))
173
-                {
174
-                    $serviceList[$service->name]=
175
-                        array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
176
-                }
177
-                else
178
-                {
179
-                    $serviceList[$service->name]['num']++;
180
-                }
181
-            }
182
-        }
183
-        $commonServices=array();
184
-        foreach ($serviceList as $key => $values)
185
-        {
186
-            if ($values['num'] >= $hostNum)
187
-            {
188
-                array_push($commonServices,array($key,$values['display_name']));
189
-            }
190
-        }
191
-        return $commonServices;
192
-    }
160
+	public function getServicesByHostGroupid(string $group)
161
+	{
162
+		$hostList = $this->getHostsByGroup($group);
163
+		//return $hostList;
164
+		$hostNum = count($hostList);
165
+		$serviceList=array();
166
+		foreach ($hostList as $curHost)
167
+		{
168
+			$services = $this->getServicesByHostid($curHost->name);
169
+			foreach ($services as $service)
170
+			{
171
+				//return $service;
172
+				if (! isset($serviceList[$service->name]))
173
+				{
174
+					$serviceList[$service->name]=
175
+						array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
176
+				}
177
+				else
178
+				{
179
+					$serviceList[$service->name]['num']++;
180
+				}
181
+			}
182
+		}
183
+		$commonServices=array();
184
+		foreach ($serviceList as $key => $values)
185
+		{
186
+			if ($values['num'] >= $hostNum)
187
+			{
188
+				array_push($commonServices,array($key,$values['display_name']));
189
+			}
190
+		}
191
+		return $commonServices;
192
+	}
193 193
  
194
-    /**
195
-     * Get all host and IP from hostgroup
196
-     * @param string $hostGroup
197
-     * @throws Exception
198
-     * @return array : attributes : address, address6, name
199
-     */
200
-    public function getHostGroupByName($name)
201
-    {
202
-        $hosts = $this->standardQuery(
203
-            'hostgroup',
204
-            'match("*' . $name . '*",hostgroup.name)',
205
-            array('__name','name','display_name')
194
+	/**
195
+	 * Get all host and IP from hostgroup
196
+	 * @param string $hostGroup
197
+	 * @throws Exception
198
+	 * @return array : attributes : address, address6, name
199
+	 */
200
+	public function getHostGroupByName($name)
201
+	{
202
+		$hosts = $this->standardQuery(
203
+			'hostgroup',
204
+			'match("*' . $name . '*",hostgroup.name)',
205
+			array('__name','name','display_name')
206 206
             
207
-            );
208
-        foreach ( array_keys($hosts) as $key )
209
-        {
210
-            $hosts[$key]->id = $hosts[$key]->__name;
211
-        }
212
-        return $hosts;
213
-    }
207
+			);
208
+		foreach ( array_keys($hosts) as $key )
209
+		{
210
+			$hosts[$key]->id = $hosts[$key]->__name;
211
+		}
212
+		return $hosts;
213
+	}
214 214
     
215
-    /**
216
-     * Get hostgroup by id (__name)
217
-     * @param string $hostGroup
218
-     * @throws Exception
219
-     * @return array : __name, name, display_name
220
-     */
221
-    public function getHostGroupById($name)
222
-    {
223
-        $hosts = $this->standardQuery(
224
-            'hostgroup',
225
-            'hostgroup.__name=="'. $name .'"',
226
-            array('__name','name','display_name')
215
+	/**
216
+	 * Get hostgroup by id (__name)
217
+	 * @param string $hostGroup
218
+	 * @throws Exception
219
+	 * @return array : __name, name, display_name
220
+	 */
221
+	public function getHostGroupById($name)
222
+	{
223
+		$hosts = $this->standardQuery(
224
+			'hostgroup',
225
+			'hostgroup.__name=="'. $name .'"',
226
+			array('__name','name','display_name')
227 227
             
228
-            );
229
-        $hosts[0]->id = $hosts[0]->__name;
230
-        return $hosts[0];
231
-    }
228
+			);
229
+		$hosts[0]->id = $hosts[0]->__name;
230
+		return $hosts[0];
231
+	}
232 232
     
233 233
 /****************   Service queries ************/
234
-    /** Get services object id by host name / service name
235
-     *	does not catch exceptions
236
-     *	@param $hostname string host name
237
-     *	@param $name string service name
238
-     *  @param bool $active : if true, return only active service
239
-     *  @param bool $passive_svc : if true, return only service accepting passive checks
240
-     *	@return array  service id
241
-     */
242
-    public function getServiceIDByName($hostname,$name,bool $active = TRUE, bool $passive_svc = TRUE)
243
-    {
244
-        $filter = 'service.__name=="' . $hostname . '!'. $name .'"';
245
-        if ($active === TRUE)
246
-        {
247
-            $filter .= ' && service.active==true';
248
-        }
249
-        if ($passive_svc === TRUE)
250
-        {
251
-            $filter .= ' && service.enable_passive_checks==true';
252
-        }
253
-        $services =  $this->standardQuery(
254
-            'service',
255
-            $filter,
256
-            array('__name','name','display_name','active','enable_passive_checks')
257
-            );
234
+	/** Get services object id by host name / service name
235
+	 *	does not catch exceptions
236
+	 *	@param $hostname string host name
237
+	 *	@param $name string service name
238
+	 *  @param bool $active : if true, return only active service
239
+	 *  @param bool $passive_svc : if true, return only service accepting passive checks
240
+	 *	@return array  service id
241
+	 */
242
+	public function getServiceIDByName($hostname,$name,bool $active = TRUE, bool $passive_svc = TRUE)
243
+	{
244
+		$filter = 'service.__name=="' . $hostname . '!'. $name .'"';
245
+		if ($active === TRUE)
246
+		{
247
+			$filter .= ' && service.active==true';
248
+		}
249
+		if ($passive_svc === TRUE)
250
+		{
251
+			$filter .= ' && service.enable_passive_checks==true';
252
+		}
253
+		$services =  $this->standardQuery(
254
+			'service',
255
+			$filter,
256
+			array('__name','name','display_name','active','enable_passive_checks')
257
+			);
258 258
         
259
-        foreach ( array_keys($services) as $key )
260
-        {
261
-            $services[$key]->id = $services[$key]->__name;
262
-        }
259
+		foreach ( array_keys($services) as $key )
260
+		{
261
+			$services[$key]->id = $services[$key]->__name;
262
+		}
263 263
         
264
-        return $services;
265
-    }
264
+		return $services;
265
+	}
266 266
  
267
-    /** Get services object by id (host!name)
268
-     *	does not catch exceptions
269
-     *	@param $name string service __name (host!name)
270
-     *	@return array  service id
271
-     */
272
-    public function getServiceById($name)
273
-    {
274
-        $filter = 'service.__name=="' .  $name .'"';
275
-        $services =  $this->standardQuery(
276
-            'service',
277
-            $filter,
278
-            array('__name','name','display_name','active','enable_passive_checks')
279
-            );
267
+	/** Get services object by id (host!name)
268
+	 *	does not catch exceptions
269
+	 *	@param $name string service __name (host!name)
270
+	 *	@return array  service id
271
+	 */
272
+	public function getServiceById($name)
273
+	{
274
+		$filter = 'service.__name=="' .  $name .'"';
275
+		$services =  $this->standardQuery(
276
+			'service',
277
+			$filter,
278
+			array('__name','name','display_name','active','enable_passive_checks')
279
+			);
280 280
         
281
-        foreach ( array_keys($services) as $key )
282
-        {
283
-            $services[$key]->id = $services[$key]->__name;
284
-        }
281
+		foreach ( array_keys($services) as $key )
282
+		{
283
+			$services[$key]->id = $services[$key]->__name;
284
+		}
285 285
         
286
-        return $services;
287
-    }
286
+		return $services;
287
+	}
288 288
 
289
-    /** Get services object by id (host!name)
290
-     *	does not catch exceptions
291
-     *	@param $name string service __name (host!name)
292
-     *	@return array  service id
293
-     */
294
-    public function getNOKService()
295
-    {
296
-        $filter = 'service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
-        $services =  $this->standardQuery(
298
-            'service',
299
-            $filter,
300
-            array('__name','name','last_check','host_name','state')
301
-            );
289
+	/** Get services object by id (host!name)
290
+	 *	does not catch exceptions
291
+	 *	@param $name string service __name (host!name)
292
+	 *	@return array  service id
293
+	 */
294
+	public function getNOKService()
295
+	{
296
+		$filter = 'service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
+		$services =  $this->standardQuery(
298
+			'service',
299
+			$filter,
300
+			array('__name','name','last_check','host_name','state')
301
+			);
302 302
         
303
-        foreach ( array_keys($services) as $key )
304
-        {
305
-            $services[$key]->id = $services[$key]->__name;
306
-        }
303
+		foreach ( array_keys($services) as $key )
304
+		{
305
+			$services[$key]->id = $services[$key]->__name;
306
+		}
307 307
         
308
-        return $services;
309
-    }
308
+		return $services;
309
+	}
310 310
     
311 311
     
312 312
 }
Please login to merge, or discard this patch.
Spacing   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -16,9 +16,9 @@  discard block
 block discarded – undo
16 16
      * @param string $host host name or IP
17 17
      * @param number $port API port
18 18
      */
19
-    public function __construct($host, $port = 5665)
19
+    public function __construct($host, $port=5665)
20 20
     {
21
-        parent::__construct($host,$port);
21
+        parent::__construct($host, $port);
22 22
     }
23 23
     /**
24 24
 
@@ -32,17 +32,17 @@  discard block
 block discarded – undo
32 32
      */
33 33
     public function getHostByFilter(string $hostfilter)
34 34
     {
35
-        $hosts = $this->standardQuery(
35
+        $hosts=$this->standardQuery(
36 36
             'host',
37 37
             $hostfilter,
38 38
             //'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
39
-            array('__name','name','display_name','address','address6')
39
+            array('__name', 'name', 'display_name', 'address', 'address6')
40 40
             );
41
-        foreach ( array_keys($hosts) as $key )
41
+        foreach (array_keys($hosts) as $key)
42 42
         {
43
-            $hosts[$key]->id = $hosts[$key]->__name;
44
-            $hosts[$key]->ip4 = $hosts[$key]->address;
45
-            $hosts[$key]->ip6 = $hosts[$key]->address6;
43
+            $hosts[$key]->id=$hosts[$key]->__name;
44
+            $hosts[$key]->ip4=$hosts[$key]->address;
45
+            $hosts[$key]->ip6=$hosts[$key]->address6;
46 46
         }
47 47
         return $hosts;
48 48
     }
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
      */
56 56
     public function getHostByIP(string $ip) 
57 57
     {
58
-        return $this->getHostByFilter('match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6)');
58
+        return $this->getHostByFilter('match("*'.$ip.'*",host.address) || match("*'.$ip.'*",host.address6)');
59 59
     }
60 60
 
61 61
     
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
      */
67 67
     public function getHostByName(string $name)
68 68
     {
69
-        return $this->getHostByFilter('match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name)');
69
+        return $this->getHostByFilter('match("*'.$name.'*",host.name) || match("*'.$name.'*",host.display_name)');
70 70
     }
71 71
 
72 72
     /**
@@ -77,13 +77,13 @@  discard block
 block discarded – undo
77 77
     public function getHostByNameOrIP(string $name)
78 78
     {
79 79
         return $this->getHostByFilter( 
80
-            'match("*' . $name . '*",host.name) || match("*' . $name . '*",host.display_name) || match("*' . $name . '*",host.address) || match("*' . $name . '*",host.address6)');
80
+            'match("*'.$name.'*",host.name) || match("*'.$name.'*",host.display_name) || match("*'.$name.'*",host.address) || match("*'.$name.'*",host.address6)');
81 81
     }
82 82
     
83 83
     public function getHostInfoByID(string $name)
84 84
     {
85
-        $host = $this->getHostByFilter(
86
-            'host.__name=="'. $name .'"');
85
+        $host=$this->getHostByFilter(
86
+            'host.__name=="'.$name.'"');
87 87
         if (isset($host[0]))
88 88
             return $host[0];
89 89
         else
@@ -100,8 +100,8 @@  discard block
 block discarded – undo
100 100
     {        
101 101
         return $this->standardQuery(
102 102
             'host', 
103
-            '"' . $hostGroup . '" in host.groups',
104
-            array('address','address6','name')
103
+            '"'.$hostGroup.'" in host.groups',
104
+            array('address', 'address6', 'name')
105 105
                 
106 106
         );
107 107
     }
@@ -115,26 +115,26 @@  discard block
 block discarded – undo
115 115
      *  @param bool $passive_svc
116 116
      *	@return array display_name (of service), service_object_id
117 117
      */
118
-    public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
118
+    public function getServicesByHostid(string $id, bool $active=TRUE, bool $passive_svc=TRUE)
119 119
     {
120
-        $filter = 'match("' . $id . '!*", service.__name)';
120
+        $filter='match("'.$id.'!*", service.__name)';
121 121
         if ($active === TRUE)
122 122
         {
123
-            $filter .= ' && service.active==true';
123
+            $filter.=' && service.active==true';
124 124
         }
125 125
         if ($passive_svc === TRUE)
126 126
         {
127
-            $filter .= ' && service.enable_passive_checks==true';
127
+            $filter.=' && service.enable_passive_checks==true';
128 128
         }
129
-        $services =  $this->standardQuery(
129
+        $services=$this->standardQuery(
130 130
             'service',
131 131
             $filter,
132
-            array('__name','name','display_name','active')
132
+            array('__name', 'name', 'display_name', 'active')
133 133
             );
134 134
         
135
-        foreach ( array_keys($services) as $key )
135
+        foreach (array_keys($services) as $key)
136 136
         {
137
-            $services[$key]->id = $services[$key]->__name;
137
+            $services[$key]->id=$services[$key]->__name;
138 138
         }
139 139
         
140 140
         return $services;
@@ -152,27 +152,27 @@  discard block
 block discarded – undo
152 152
     {
153 153
          return $this->standardQuery(
154 154
             'host',
155
-            '"' . $group . '" in host.groups',
156
-            array('name','display_name')
155
+            '"'.$group.'" in host.groups',
156
+            array('name', 'display_name')
157 157
             );
158 158
     }
159 159
     
160 160
     public function getServicesByHostGroupid(string $group)
161 161
     {
162
-        $hostList = $this->getHostsByGroup($group);
162
+        $hostList=$this->getHostsByGroup($group);
163 163
         //return $hostList;
164
-        $hostNum = count($hostList);
164
+        $hostNum=count($hostList);
165 165
         $serviceList=array();
166 166
         foreach ($hostList as $curHost)
167 167
         {
168
-            $services = $this->getServicesByHostid($curHost->name);
168
+            $services=$this->getServicesByHostid($curHost->name);
169 169
             foreach ($services as $service)
170 170
             {
171 171
                 //return $service;
172
-                if (! isset($serviceList[$service->name]))
172
+                if (!isset($serviceList[$service->name]))
173 173
                 {
174 174
                     $serviceList[$service->name]=
175
-                        array('num'=> 1 ,'__name' => $service->__name,'display_name' => $service->display_name);
175
+                        array('num'=> 1, '__name' => $service->__name, 'display_name' => $service->display_name);
176 176
                 }
177 177
                 else
178 178
                 {
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
         {
186 186
             if ($values['num'] >= $hostNum)
187 187
             {
188
-                array_push($commonServices,array($key,$values['display_name']));
188
+                array_push($commonServices, array($key, $values['display_name']));
189 189
             }
190 190
         }
191 191
         return $commonServices;
@@ -199,15 +199,15 @@  discard block
 block discarded – undo
199 199
      */
200 200
     public function getHostGroupByName($name)
201 201
     {
202
-        $hosts = $this->standardQuery(
202
+        $hosts=$this->standardQuery(
203 203
             'hostgroup',
204
-            'match("*' . $name . '*",hostgroup.name)',
205
-            array('__name','name','display_name')
204
+            'match("*'.$name.'*",hostgroup.name)',
205
+            array('__name', 'name', 'display_name')
206 206
             
207 207
             );
208
-        foreach ( array_keys($hosts) as $key )
208
+        foreach (array_keys($hosts) as $key)
209 209
         {
210
-            $hosts[$key]->id = $hosts[$key]->__name;
210
+            $hosts[$key]->id=$hosts[$key]->__name;
211 211
         }
212 212
         return $hosts;
213 213
     }
@@ -220,13 +220,13 @@  discard block
 block discarded – undo
220 220
      */
221 221
     public function getHostGroupById($name)
222 222
     {
223
-        $hosts = $this->standardQuery(
223
+        $hosts=$this->standardQuery(
224 224
             'hostgroup',
225
-            'hostgroup.__name=="'. $name .'"',
226
-            array('__name','name','display_name')
225
+            'hostgroup.__name=="'.$name.'"',
226
+            array('__name', 'name', 'display_name')
227 227
             
228 228
             );
229
-        $hosts[0]->id = $hosts[0]->__name;
229
+        $hosts[0]->id=$hosts[0]->__name;
230 230
         return $hosts[0];
231 231
     }
232 232
     
@@ -239,26 +239,26 @@  discard block
 block discarded – undo
239 239
      *  @param bool $passive_svc : if true, return only service accepting passive checks
240 240
      *	@return array  service id
241 241
      */
242
-    public function getServiceIDByName($hostname,$name,bool $active = TRUE, bool $passive_svc = TRUE)
242
+    public function getServiceIDByName($hostname, $name, bool $active=TRUE, bool $passive_svc=TRUE)
243 243
     {
244
-        $filter = 'service.__name=="' . $hostname . '!'. $name .'"';
244
+        $filter='service.__name=="'.$hostname.'!'.$name.'"';
245 245
         if ($active === TRUE)
246 246
         {
247
-            $filter .= ' && service.active==true';
247
+            $filter.=' && service.active==true';
248 248
         }
249 249
         if ($passive_svc === TRUE)
250 250
         {
251
-            $filter .= ' && service.enable_passive_checks==true';
251
+            $filter.=' && service.enable_passive_checks==true';
252 252
         }
253
-        $services =  $this->standardQuery(
253
+        $services=$this->standardQuery(
254 254
             'service',
255 255
             $filter,
256
-            array('__name','name','display_name','active','enable_passive_checks')
256
+            array('__name', 'name', 'display_name', 'active', 'enable_passive_checks')
257 257
             );
258 258
         
259
-        foreach ( array_keys($services) as $key )
259
+        foreach (array_keys($services) as $key)
260 260
         {
261
-            $services[$key]->id = $services[$key]->__name;
261
+            $services[$key]->id=$services[$key]->__name;
262 262
         }
263 263
         
264 264
         return $services;
@@ -271,16 +271,16 @@  discard block
 block discarded – undo
271 271
      */
272 272
     public function getServiceById($name)
273 273
     {
274
-        $filter = 'service.__name=="' .  $name .'"';
275
-        $services =  $this->standardQuery(
274
+        $filter='service.__name=="'.$name.'"';
275
+        $services=$this->standardQuery(
276 276
             'service',
277 277
             $filter,
278
-            array('__name','name','display_name','active','enable_passive_checks')
278
+            array('__name', 'name', 'display_name', 'active', 'enable_passive_checks')
279 279
             );
280 280
         
281
-        foreach ( array_keys($services) as $key )
281
+        foreach (array_keys($services) as $key)
282 282
         {
283
-            $services[$key]->id = $services[$key]->__name;
283
+            $services[$key]->id=$services[$key]->__name;
284 284
         }
285 285
         
286 286
         return $services;
@@ -293,16 +293,16 @@  discard block
 block discarded – undo
293 293
      */
294 294
     public function getNOKService()
295 295
     {
296
-        $filter = 'service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
-        $services =  $this->standardQuery(
296
+        $filter='service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)';
297
+        $services=$this->standardQuery(
298 298
             'service',
299 299
             $filter,
300
-            array('__name','name','last_check','host_name','state')
300
+            array('__name', 'name', 'last_check', 'host_name', 'state')
301 301
             );
302 302
         
303
-        foreach ( array_keys($services) as $key )
303
+        foreach (array_keys($services) as $key)
304 304
         {
305
-            $services[$key]->id = $services[$key]->__name;
305
+            $services[$key]->id=$services[$key]->__name;
306 306
         }
307 307
         
308 308
         return $services;
Please login to merge, or discard this patch.
application/controllers/StatusController.php 3 patches
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -21,8 +21,8 @@  discard block
 block discarded – undo
21 21
 		/************  Trapdb ***********/
22 22
 		try
23 23
 		{
24
-		    $dbConn = $this->getUIDatabase()->getDbConn();
25
-		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
24
+			$dbConn = $this->getUIDatabase()->getDbConn();
25
+			if ($dbConn === null) throw new \ErrorException('uncatched db error');
26 26
 			$query = $dbConn->select()->from(
27 27
 				$this->getModuleConfig()->getTrapTableName(),
28 28
 				array('COUNT(*)')
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 		
52 52
 		try
53 53
 		{		
54
-		    $this->view->currentLogDestination=$this->getUIDatabase()->getDBConfigValue('log_destination');
54
+			$this->view->currentLogDestination=$this->getUIDatabase()->getDBConfigValue('log_destination');
55 55
 			$this->view->logDestinations=$this->getModuleConfig()->getLogDestinations();
56 56
 			$this->view->currentLogFile=$this->getUIDatabase()->getDBConfigValue('log_file');
57 57
 			$this->view->logLevels=$this->getModuleConfig()->getlogLevels();
@@ -65,23 +65,23 @@  discard block
 block discarded – undo
65 65
 		/*************** SNMP configuration ****************/
66 66
 		try
67 67
 		{
68
-		    $this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
69
-		    $this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
-		    $this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
68
+			$this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
69
+			$this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
+			$this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
71 71
 		    
72 72
 		}
73 73
 		catch (Exception $e)
74 74
 		{
75
-		    $this->displayExitError('status',$e->getMessage());
75
+			$this->displayExitError('status',$e->getMessage());
76 76
 		}		
77 77
 		
78 78
 	} 
79 79
   
80 80
 	/** Mib management
81
-	*	Post param : action=update_mib_db : update mib database
82
-	*	Post param : ation=check_update : check if mib update is finished
83
-	*	File post : mibfile -> save mib file
84
-	*/
81
+	 *	Post param : action=update_mib_db : update mib database
82
+	 *	Post param : ation=check_update : check if mib update is finished
83
+	 *	File post : mibfile -> save mib file
84
+	 */
85 85
 	public function mibAction()
86 86
 	{
87 87
 		$this->prepareTabs()->activate('mib');
@@ -100,22 +100,22 @@  discard block
 block discarded – undo
100 100
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
101 101
 					if (preg_match('/OK/',$return))
102 102
 					{
103
-					    $this->_helper->json(array('status'=>'OK'));
103
+						$this->_helper->json(array('status'=>'OK'));
104 104
 					}
105 105
 					// Error
106 106
 					$this->_helper->json(array('status'=>$return));
107 107
 				}
108 108
 				if ($action == 'check_update')
109 109
 				{
110
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
111
-				    if ($file == false)
112
-				    {   // process is dead
113
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
114
-				        return;
115
-				    }
116
-				    $pid=fgets($file);
117
-				    $output=array();
118
-				    $retVal=0;
110
+					$file=@fopen('/tmp/trapdirector_update.pid','r');
111
+					if ($file == false)
112
+					{   // process is dead
113
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
114
+						return;
115
+					}
116
+					$pid=fgets($file);
117
+					$output=array();
118
+					$retVal=0;
119 119
 					exec('ps '.$pid,$output,$retVal);
120 120
 					if ($retVal == 0)
121 121
 					{ // process is alive
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 					}
124 124
 					else
125 125
 					{ // process is dead
126
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
126
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
127 127
 					}
128 128
 				}
129 129
 				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
@@ -136,27 +136,27 @@  discard block
 block discarded – undo
136 136
 				$destDir=array_shift($DirConf);
137 137
 				if (!is_dir($destDir))
138 138
 				{
139
-				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
139
+					$this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
140 140
 				}
141 141
 				else
142 142
 				{
143
-				    if (!is_writable($destDir))
144
-				    {
145
-				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
146
-				    }
147
-				    else
148
-				    {
149
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150
-				        $sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']);
151
-				        if (move_uploaded_file($sourceTmpNam,$destination)===false)
152
-    				    {
153
-    				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154
-    				    }
155
-    				    else
156
-    				    {
157
-    				        $this->view->uploadStatus="File $name uploaded in $destDir";
158
-    				    }
159
-				    }
143
+					if (!is_writable($destDir))
144
+					{
145
+						$this->view->uploadStatus="ERROR : $destDir directory is not writable";
146
+					}
147
+					else
148
+					{
149
+						$destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150
+						$sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']);
151
+						if (move_uploaded_file($sourceTmpNam,$destination)===false)
152
+						{
153
+							$this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154
+						}
155
+						else
156
+						{
157
+							$this->view->uploadStatus="File $name uploaded in $destDir";
158
+						}
159
+					}
160 160
 				}
161 161
 
162 162
 			}
@@ -172,16 +172,16 @@  discard block
 block discarded – undo
172 172
 			$translate=exec($snmptranslate . ' 1');
173 173
 			if (preg_match('/iso/',$translate))
174 174
 			{
175
-			    $translate=exec($snmptranslate . ' 1.3.6.1.4');
176
-			    if (preg_match('/private/',$translate))
177
-			    {		    
178
-    				$this->view->snmptranslate='works fine';
179
-    				$this->view->snmptranslate_state='ok';
180
-			    }
181
-			    else
182
-			    {
183
-			        $this->view->snmptranslate='works fine but missing basic MIBs';
184
-			    }
175
+				$translate=exec($snmptranslate . ' 1.3.6.1.4');
176
+				if (preg_match('/private/',$translate))
177
+				{		    
178
+					$this->view->snmptranslate='works fine';
179
+					$this->view->snmptranslate_state='ok';
180
+				}
181
+				else
182
+				{
183
+					$this->view->snmptranslate='works fine but missing basic MIBs';
184
+				}
185 185
 			}
186 186
 			else
187 187
 			{
@@ -244,63 +244,63 @@  discard block
 block discarded – undo
244 244
 	/** UI options */
245 245
 	public function uimgtAction()
246 246
 	{
247
-	    $this->prepareTabs()->activate('uimgt');
247
+		$this->prepareTabs()->activate('uimgt');
248 248
 	    
249
-	    $this->view->setError='';
250
-	    $this->view->setOKMsg='';
249
+		$this->view->setError='';
250
+		$this->view->setOKMsg='';
251 251
 	    
252
-	    //max_rows=25&row_update=update
253
-	    if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
254
-	    {
255
-	        $maxRows = $this->getRequest()->getParam('max_rows');
256
-	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257
-	        {
258
-	            $this->view->setError='Max rows must be a number';
259
-	        }
260
-	        else
261
-	        {
262
-	            $this->setitemListDisplay($maxRows);
263
-	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
264
-	        }
265
-	    }
252
+		//max_rows=25&row_update=update
253
+		if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
254
+		{
255
+			$maxRows = $this->getRequest()->getParam('max_rows');
256
+			if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257
+			{
258
+				$this->view->setError='Max rows must be a number';
259
+			}
260
+			else
261
+			{
262
+				$this->setitemListDisplay($maxRows);
263
+				$this->view->setOKMsg='Set max rows to ' . $maxRows;
264
+			}
265
+		}
266 266
 	    
267
-	    if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
268
-	    {
269
-	        $addCat = $this->getRequest()->getParam('add_category');
270
-            $this->addHandlersCategory($addCat);
271
-	    }
267
+		if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
268
+		{
269
+			$addCat = $this->getRequest()->getParam('add_category');
270
+			$this->addHandlersCategory($addCat);
271
+		}
272 272
 	    
273
-	    if ( $this->getRequest()->getPost('type',NULL) !== NULL )
274
-	    {
275
-	        $type = $this->getRequest()->getPost('type',NULL);
276
-	        $index = $this->getRequest()->getPost('index',NULL);
277
-	        $newname = $this->getRequest()->getPost('newname',NULL);
273
+		if ( $this->getRequest()->getPost('type',NULL) !== NULL )
274
+		{
275
+			$type = $this->getRequest()->getPost('type',NULL);
276
+			$index = $this->getRequest()->getPost('index',NULL);
277
+			$newname = $this->getRequest()->getPost('newname',NULL);
278 278
 
279
-	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280
-	            $this->_helper->json(array('status'=>'Bad index'));
279
+			if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280
+				$this->_helper->json(array('status'=>'Bad index'));
281 281
 	        
282
-	        switch ($type)
283
-	        {
284
-	            case 'delete':
285
-	                $this->delHandlersCategory($index);
286
-	                $this->_helper->json(array('status'=>'OK'));
287
-	                return;
288
-	                break;
289
-	            case 'rename':
290
-	                $this->renameHandlersCategory($index, $newname);
291
-	                $this->_helper->json(array('status'=>'OK'));
292
-	                return;
293
-	                break;
294
-	            default:
295
-	                $this->_helper->json(array('status'=>'Unknwon command'));
296
-	                return;
297
-	                break;
298
-	        }
299
-	    }
282
+			switch ($type)
283
+			{
284
+				case 'delete':
285
+					$this->delHandlersCategory($index);
286
+					$this->_helper->json(array('status'=>'OK'));
287
+					return;
288
+					break;
289
+				case 'rename':
290
+					$this->renameHandlersCategory($index, $newname);
291
+					$this->_helper->json(array('status'=>'OK'));
292
+					return;
293
+					break;
294
+				default:
295
+					$this->_helper->json(array('status'=>'Unknwon command'));
296
+					return;
297
+					break;
298
+			}
299
+		}
300 300
 	    
301
-	    $this->view->maxRows = $this->itemListDisplay();
301
+		$this->view->maxRows = $this->itemListDisplay();
302 302
 	    
303
-	    $this->view->categories = $this->getHandlersCategory();
303
+		$this->view->categories = $this->getHandlersCategory();
304 304
 	    
305 305
 	    
306 306
 	    
@@ -349,47 +349,47 @@  discard block
 block discarded – undo
349 349
 	 */
350 350
 	public function pluginsAction()
351 351
 	{
352
-	    $this->prepareTabs()->activate('plugins');
352
+		$this->prepareTabs()->activate('plugins');
353 353
 	    
354
-	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
355
-	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
356
-	    $Trap = new Trap($icingaweb2_etc,4);
354
+		require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
355
+		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
356
+		$Trap = new Trap($icingaweb2_etc,4);
357 357
 	    
358
-	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
358
+		$this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
359 359
 	    
360
-	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
360
+		$enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
361 361
 
362
-	    $pluginList = $Trap->pluginClass->pluginList();
362
+		$pluginList = $Trap->pluginClass->pluginList();
363 363
 	    
364
-	    // Plugin list and fill function name list
365
-	    $functionList=array();
366
-	    $this->view->pluginArray=array();
367
-	    foreach ($pluginList as $plugin)
368
-	    {
369
-	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
370
-	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
371
-	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
372
-	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
373
-	        $pluginDetails->description = htmlentities($pluginDetails->description);
374
-	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
375
-	        array_push($this->view->pluginArray, $pluginDetails);
376
-	        // Get functions for function details
377
-	        foreach ($pluginDetails->funcArray as $function)
378
-	        {
379
-	            array_push($functionList,$function);
380
-	        }
381
-	    }
364
+		// Plugin list and fill function name list
365
+		$functionList=array();
366
+		$this->view->pluginArray=array();
367
+		foreach ($pluginList as $plugin)
368
+		{
369
+			$pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
370
+			$pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
371
+			$pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
372
+			$pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
373
+			$pluginDetails->description = htmlentities($pluginDetails->description);
374
+			$pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
375
+			array_push($this->view->pluginArray, $pluginDetails);
376
+			// Get functions for function details
377
+			foreach ($pluginDetails->funcArray as $function)
378
+			{
379
+				array_push($functionList,$function);
380
+			}
381
+		}
382 382
 	    
383
-	    // Function list with details
384
-	    $this->view->functionList=array();
385
-	    foreach ($functionList as $function)
386
-	    {
387
-	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
388
-	        $functionDetail->params = htmlentities($functionDetail->params);
389
-	        $functionDetail->description = htmlentities($functionDetail->description);
390
-	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
391
-	        array_push($this->view->functionList, $functionDetail);
392
-	    }
383
+		// Function list with details
384
+		$this->view->functionList=array();
385
+		foreach ($functionList as $function)
386
+		{
387
+			$functionDetail = $Trap->pluginClass->getFunctionDetails($function);
388
+			$functionDetail->params = htmlentities($functionDetail->params);
389
+			$functionDetail->description = htmlentities($functionDetail->description);
390
+			$functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
391
+			array_push($this->view->functionList, $functionDetail);
392
+		}
393 393
 
394 394
 	}
395 395
 
@@ -398,47 +398,47 @@  discard block
 block discarded – undo
398 398
 	 */
399 399
 	public function debugAction()
400 400
 	{
401
-	    $this->view->answer='No answer';
402
-	    $this->view->input1 = '';
401
+		$this->view->answer='No answer';
402
+		$this->view->input1 = '';
403 403
 	    
404
-	    $postData=$this->getRequest()->getPost();
405
-	    if (isset($postData['input1']))
406
-	    {
407
-	        $input1 = $postData['input1'];
408
-	        $input2 = $postData['input2'];
409
-	        $input3 = $postData['input3'];
410
-	        $this->view->input1 = $input1;
411
-	        //$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
412
-	        try {
413
-	            $this->view->answer = 'Answer : ';
414
-	            $API = $this->getIdoConn();
415
-	            $DB = $this->getUIDatabase();
404
+		$postData=$this->getRequest()->getPost();
405
+		if (isset($postData['input1']))
406
+		{
407
+			$input1 = $postData['input1'];
408
+			$input2 = $postData['input2'];
409
+			$input3 = $postData['input3'];
410
+			$this->view->input1 = $input1;
411
+			//$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
412
+			try {
413
+				$this->view->answer = 'Answer : ';
414
+				$API = $this->getIdoConn();
415
+				$DB = $this->getUIDatabase();
416 416
 
417
-	            //$hosts = $DB->getServicesByHostGroupid($input1);
418
-	            //$this->view->answer .= 'services : '.print_r($hosts,true);
417
+				//$hosts = $DB->getServicesByHostGroupid($input1);
418
+				//$this->view->answer .= 'services : '.print_r($hosts,true);
419 419
 	            
420
-	            $hosts = $API->getServicesByHostGroupid($input1);
421
-	            $this->view->answer .= 'services : '.print_r($hosts,true);
420
+				$hosts = $API->getServicesByHostGroupid($input1);
421
+				$this->view->answer .= 'services : '.print_r($hosts,true);
422 422
 	            
423 423
 
424 424
 	            
425
-	            return;
426
-	            $hosts = $API->getHostByIP($input1);
427
-	            $this->view->answer .= 'Host : '. print_r($hosts,true);
428
-	            $hosts = $API->getHostGroupByName($input1);
429
-	            $this->view->answer .= 'Group : '.print_r($hosts,true);
430
-	            $hosts = $API->getServicesByHostid($input1);
431
-	            $this->view->answer .= 'service : '.print_r($hosts,true);
425
+				return;
426
+				$hosts = $API->getHostByIP($input1);
427
+				$this->view->answer .= 'Host : '. print_r($hosts,true);
428
+				$hosts = $API->getHostGroupByName($input1);
429
+				$this->view->answer .= 'Group : '.print_r($hosts,true);
430
+				$hosts = $API->getServicesByHostid($input1);
431
+				$this->view->answer .= 'service : '.print_r($hosts,true);
432 432
 	            
433
-	            /* $hosts = $API->getHostsIPByHostGroup($input1);
433
+				/* $hosts = $API->getHostsIPByHostGroup($input1);
434 434
 	            $this->view->answer .= "\n Hostgrp : " . print_r($hosts,true); */
435 435
 	            
436
-	        } catch (Exception $e)
437
-	        {
438
-	            $this->view->answer = "Exception : " . print_r($e);
439
-	        }
436
+			} catch (Exception $e)
437
+			{
438
+				$this->view->answer = "Exception : " . print_r($e);
439
+			}
440 440
 	        
441
-	    }
441
+		}
442 442
 	    
443 443
 	}
444 444
 	
@@ -450,36 +450,36 @@  discard block
 block discarded – undo
450 450
 		)->add('mib', array(
451 451
 			'label' => $this->translate('MIB Management'),
452 452
 			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
453
-	    )->add('uimgt', array(
454
-	        'label' => $this->translate('UI Configuration'),
455
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
456
-        )->add('services', array(
453
+		)->add('uimgt', array(
454
+			'label' => $this->translate('UI Configuration'),
455
+			'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
456
+		)->add('services', array(
457 457
 			'label' => $this->translate('Services management'),
458 458
 			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
459
-	    )->add('plugins', array(
460
-	        'label' => $this->translate('Plugins management'),
461
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
462
-	    );
459
+		)->add('plugins', array(
460
+			'label' => $this->translate('Plugins management'),
461
+			'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
462
+		);
463 463
 	} 
464 464
 }
465 465
 
466 466
 // TODO : see if useless 
467 467
 class UploadForm extends Form
468 468
 { 
469
-    public function __construct($options = null) 
470
-    {
471
-        parent::__construct($options);
472
-        $this->addElements2();
473
-    }
469
+	public function __construct($options = null) 
470
+	{
471
+		parent::__construct($options);
472
+		$this->addElements2();
473
+	}
474 474
 
475
-    public function addElements2()
476
-    {
477
-        // File Input
478
-        $file = new File('mib-file');
479
-        $file->setLabel('Mib upload');
480
-             //->setAttrib('multiple', null);
481
-        $this->addElement($file);
475
+	public function addElements2()
476
+	{
477
+		// File Input
478
+		$file = new File('mib-file');
479
+		$file->setLabel('Mib upload');
480
+			 //->setAttrib('multiple', null);
481
+		$this->addElement($file);
482 482
 		$button = new Submit("upload",array('ignore'=>false));
483 483
 		$this->addElement($button);//->setIgnore(false);
484
-    }
484
+	}
485 485
 }
Please login to merge, or discard this patch.
Spacing   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -21,19 +21,19 @@  discard block
 block discarded – undo
21 21
 		/************  Trapdb ***********/
22 22
 		try
23 23
 		{
24
-		    $dbConn = $this->getUIDatabase()->getDbConn();
24
+		    $dbConn=$this->getUIDatabase()->getDbConn();
25 25
 		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
26
-			$query = $dbConn->select()->from(
26
+			$query=$dbConn->select()->from(
27 27
 				$this->getModuleConfig()->getTrapTableName(),
28 28
 				array('COUNT(*)')
29 29
 			);			
30 30
 			$this->view->trap_count=$dbConn->fetchOne($query);
31
-			$query = $dbConn->select()->from(
31
+			$query=$dbConn->select()->from(
32 32
 				$this->getModuleConfig()->getTrapDataTableName(),
33 33
 				array('COUNT(*)')
34 34
 			);			
35 35
 			$this->view->trap_object_count=$dbConn->fetchOne($query);
36
-			$query = $dbConn->select()->from(
36
+			$query=$dbConn->select()->from(
37 37
 				$this->getModuleConfig()->getTrapRuleName(),
38 38
 				array('COUNT(*)')
39 39
 			);			
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 		}
45 45
 		catch (Exception $e)
46 46
 		{
47
-			$this->displayExitError('status',$e->getMessage());
47
+			$this->displayExitError('status', $e->getMessage());
48 48
 		}
49 49
 		
50 50
 		/*************** Log destination *******************/
@@ -59,20 +59,20 @@  discard block
 block discarded – undo
59 59
 		}
60 60
 		catch (Exception $e)
61 61
 		{
62
-			$this->displayExitError('status',$e->getMessage());
62
+			$this->displayExitError('status', $e->getMessage());
63 63
 		}
64 64
 		
65 65
 		/*************** SNMP configuration ****************/
66 66
 		try
67 67
 		{
68
-		    $this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
68
+		    $this->view->useSnmpTrapAddess=($this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1) ? TRUE : FALSE;
69 69
 		    $this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
-		    $this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
70
+		    $this->view->SnmpTrapAddressOIDDefault=($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid']) ? TRUE : FALSE;
71 71
 		    
72 72
 		}
73 73
 		catch (Exception $e)
74 74
 		{
75
-		    $this->displayExitError('status',$e->getMessage());
75
+		    $this->displayExitError('status', $e->getMessage());
76 76
 		}		
77 77
 		
78 78
 	} 
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 				if ($action == 'update_mib_db')
99 99
 				{ // Do the update in background
100 100
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
101
-					if (preg_match('/OK/',$return))
101
+					if (preg_match('/OK/', $return))
102 102
 					{
103 103
 					    $this->_helper->json(array('status'=>'OK'));
104 104
 					}
@@ -107,32 +107,32 @@  discard block
 block discarded – undo
107 107
 				}
108 108
 				if ($action == 'check_update')
109 109
 				{
110
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
110
+				    $file=@fopen('/tmp/trapdirector_update.pid', 'r');
111 111
 				    if ($file == false)
112 112
 				    {   // process is dead
113
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
113
+				        $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'Cannot open file'));
114 114
 				        return;
115 115
 				    }
116 116
 				    $pid=fgets($file);
117 117
 				    $output=array();
118 118
 				    $retVal=0;
119
-					exec('ps '.$pid,$output,$retVal);
119
+					exec('ps '.$pid, $output, $retVal);
120 120
 					if ($retVal == 0)
121 121
 					{ // process is alive
122 122
 						$this->_helper->json(array('status'=>'Alive and kicking'));
123 123
 					}
124 124
 					else
125 125
 					{ // process is dead
126
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
126
+					    $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'no proc'.$pid));
127 127
 					}
128 128
 				}
129
-				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
129
+				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible'));
130 130
 			}
131 131
 			/** Check for mib file UPLOAD */
132 132
 			if (isset($_FILES['mibfile']))
133 133
 			{
134 134
 				$name=htmlspecialchars($_FILES['mibfile']['name']);
135
-				$DirConf=explode(':',$this->Config()->get('config', 'snmptranslate_dirs'));
135
+				$DirConf=explode(':', $this->Config()->get('config', 'snmptranslate_dirs'));
136 136
 				$destDir=array_shift($DirConf);
137 137
 				if (!is_dir($destDir))
138 138
 				{
@@ -146,9 +146,9 @@  discard block
 block discarded – undo
146 146
 				    }
147 147
 				    else
148 148
 				    {
149
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
149
+				        $destination=$destDir.'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150 150
 				        $sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']);
151
-				        if (move_uploaded_file($sourceTmpNam,$destination)===false)
151
+				        if (move_uploaded_file($sourceTmpNam, $destination) === false)
152 152
     				    {
153 153
     				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154 154
     				    }
@@ -164,16 +164,16 @@  discard block
 block discarded – undo
164 164
 		}
165 165
 		
166 166
 		// snmptranslate tests
167
-		$snmptranslate = $this->Config()->get('config', 'snmptranslate');
167
+		$snmptranslate=$this->Config()->get('config', 'snmptranslate');
168 168
 		$this->view->snmptranslate_bin=$snmptranslate;
169 169
 		$this->view->snmptranslate_state='warn';
170
-		if (is_executable ( $snmptranslate ))
170
+		if (is_executable($snmptranslate))
171 171
 		{
172
-			$translate=exec($snmptranslate . ' 1');
173
-			if (preg_match('/iso/',$translate))
172
+			$translate=exec($snmptranslate.' 1');
173
+			if (preg_match('/iso/', $translate))
174 174
 			{
175
-			    $translate=exec($snmptranslate . ' 1.3.6.1.4');
176
-			    if (preg_match('/private/',$translate))
175
+			    $translate=exec($snmptranslate.' 1.3.6.1.4');
176
+			    if (preg_match('/private/', $translate))
177 177
 			    {		    
178 178
     				$this->view->snmptranslate='works fine';
179 179
     				$this->view->snmptranslate_state='ok';
@@ -196,46 +196,46 @@  discard block
 block discarded – undo
196 196
 		// mib database
197 197
 		
198 198
 		$this->view->mibDbCount=$this->getMIB()->countObjects();
199
-		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null,21);
199
+		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null, 21);
200 200
 		
201 201
 		// mib dirs
202 202
 		$DirConf=$this->Config()->get('config', 'snmptranslate_dirs');
203
-		$dirArray=explode(':',$DirConf);
203
+		$dirArray=explode(':', $DirConf);
204 204
 
205 205
 		// Get base directories from net-snmp-config
206 206
 		$output=$matches=array();
207 207
 		$retVal=0;
208
-		$sysDirs=exec('net-snmp-config --default-mibdirs',$output,$retVal);
209
-		if ($retVal==0)
208
+		$sysDirs=exec('net-snmp-config --default-mibdirs', $output, $retVal);
209
+		if ($retVal == 0)
210 210
 		{
211
-			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
211
+			$dirArray=array_merge($dirArray, explode(':', $sysDirs));
212 212
 		}
213 213
 		else
214 214
 		{
215
-			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
216
-			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
215
+			$translateOut=exec($this->Config()->get('config', 'snmptranslate').' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
216
+			if (preg_match('/MIBDIRS.*\'([^\']+)\'/', $translateOut, $matches))
217 217
 			{
218
-				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
218
+				$dirArray=array_merge($dirArray, explode(':', $matches[1]));
219 219
 			}
220 220
 			else
221 221
 			{
222
-				array_push($dirArray,'Install net-snmp-config to see system directories');
222
+				array_push($dirArray, 'Install net-snmp-config to see system directories');
223 223
 			}
224 224
 		}
225 225
 		
226 226
 		$this->view->dirArray=$dirArray;
227 227
 		
228 228
 		$output=null;
229
-		foreach (explode(':',$DirConf) as $mibdir)
229
+		foreach (explode(':', $DirConf) as $mibdir)
230 230
 		{
231
-			exec('ls '.$mibdir.' | grep -v traplist.txt',$output);
231
+			exec('ls '.$mibdir.' | grep -v traplist.txt', $output);
232 232
 		}
233 233
 		//$i=0;$listFiles='';while (isset($output[$i])) $listFiles.=$output[$i++];
234 234
 		//$this->view->fileList=explode(' ',$listFiles);
235 235
 		$this->view->fileList=$output;
236 236
 		
237 237
 		// Zend form 
238
-		$this->view->form= new UploadForm();
238
+		$this->view->form=new UploadForm();
239 239
 		//$this->view->form= new Form('upload-form');
240 240
 		
241 241
 		
@@ -250,9 +250,9 @@  discard block
 block discarded – undo
250 250
 	    $this->view->setOKMsg='';
251 251
 	    
252 252
 	    //max_rows=25&row_update=update
253
-	    if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
253
+	    if ($this->getRequest()->getParam('max_rows', NULL) !== NULL)
254 254
 	    {
255
-	        $maxRows = $this->getRequest()->getParam('max_rows');
255
+	        $maxRows=$this->getRequest()->getParam('max_rows');
256 256
 	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257 257
 	        {
258 258
 	            $this->view->setError='Max rows must be a number';
@@ -260,21 +260,21 @@  discard block
 block discarded – undo
260 260
 	        else
261 261
 	        {
262 262
 	            $this->setitemListDisplay($maxRows);
263
-	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
263
+	            $this->view->setOKMsg='Set max rows to '.$maxRows;
264 264
 	        }
265 265
 	    }
266 266
 	    
267
-	    if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
267
+	    if ($this->getRequest()->getParam('add_category', NULL) !== NULL)
268 268
 	    {
269
-	        $addCat = $this->getRequest()->getParam('add_category');
269
+	        $addCat=$this->getRequest()->getParam('add_category');
270 270
             $this->addHandlersCategory($addCat);
271 271
 	    }
272 272
 	    
273
-	    if ( $this->getRequest()->getPost('type',NULL) !== NULL )
273
+	    if ($this->getRequest()->getPost('type', NULL) !== NULL)
274 274
 	    {
275
-	        $type = $this->getRequest()->getPost('type',NULL);
276
-	        $index = $this->getRequest()->getPost('index',NULL);
277
-	        $newname = $this->getRequest()->getPost('newname',NULL);
275
+	        $type=$this->getRequest()->getPost('type', NULL);
276
+	        $index=$this->getRequest()->getPost('index', NULL);
277
+	        $newname=$this->getRequest()->getPost('newname', NULL);
278 278
 
279 279
 	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280 280
 	            $this->_helper->json(array('status'=>'Bad index'));
@@ -298,9 +298,9 @@  discard block
 block discarded – undo
298 298
 	        }
299 299
 	    }
300 300
 	    
301
-	    $this->view->maxRows = $this->itemListDisplay();
301
+	    $this->view->maxRows=$this->itemListDisplay();
302 302
 	    
303
-	    $this->view->categories = $this->getHandlersCategory();
303
+	    $this->view->categories=$this->getHandlersCategory();
304 304
 	    
305 305
 	    
306 306
 	    
@@ -324,18 +324,18 @@  discard block
 block discarded – undo
324 324
 		$this->view->templateForm_output='';
325 325
 		if (isset($postData['template_name']) && isset($postData['template_revert_time']))
326 326
 		{
327
-			$template_create = 'icingacli director service create --json \'{ "check_command": "dummy", ';
328
-			$template_create .= '"check_interval": "' .$postData['template_revert_time']. '", "check_timeout": "20", "disabled": false, "enable_active_checks": true, "enable_event_handler": true, "enable_notifications": true, "enable_passive_checks": true, "enable_perfdata": true, "max_check_attempts": "1", ';
329
-			$template_create .= '"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
327
+			$template_create='icingacli director service create --json \'{ "check_command": "dummy", ';
328
+			$template_create.='"check_interval": "'.$postData['template_revert_time'].'", "check_timeout": "20", "disabled": false, "enable_active_checks": true, "enable_event_handler": true, "enable_notifications": true, "enable_passive_checks": true, "enable_perfdata": true, "max_check_attempts": "1", ';
329
+			$template_create.='"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
330 330
 			$output=array();
331 331
 			$ret_code=0;
332
-			exec($template_create,$output,$ret_code);
332
+			exec($template_create, $output, $ret_code);
333 333
 			if ($ret_code != 0)
334 334
 			{
335
-				$this->displayExitError("Status -> Services","Error creating template : ".$output[0].'<br>Command was : '.$template_create);
335
+				$this->displayExitError("Status -> Services", "Error creating template : ".$output[0].'<br>Command was : '.$template_create);
336 336
 			}
337
-			exec('icingacli director config deploy',$output,$ret_code);
338
-			$this->view->templateForm_output='Template '.$postData['template_name']. ' created';
337
+			exec('icingacli director config deploy', $output, $ret_code);
338
+			$this->view->templateForm_output='Template '.$postData['template_name'].' created';
339 339
 		}
340 340
 		
341 341
 		// template creation form
@@ -351,15 +351,15 @@  discard block
 block discarded – undo
351 351
 	{
352 352
 	    $this->prepareTabs()->activate('plugins');
353 353
 	    
354
-	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
354
+	    require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
355 355
 	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
356
-	    $Trap = new Trap($icingaweb2_etc,4);
356
+	    $Trap=new Trap($icingaweb2_etc, 4);
357 357
 	    
358
-	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
358
+	    $this->view->pluginLoaded=htmlentities($Trap->pluginClass->registerAllPlugins(false));
359 359
 	    
360
-	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
360
+	    $enabledPlugins=$Trap->pluginClass->getEnabledPlugins();
361 361
 
362
-	    $pluginList = $Trap->pluginClass->pluginList();
362
+	    $pluginList=$Trap->pluginClass->pluginList();
363 363
 	    
364 364
 	    // Plugin list and fill function name list
365 365
 	    $functionList=array();
@@ -367,16 +367,16 @@  discard block
 block discarded – undo
367 367
 	    foreach ($pluginList as $plugin)
368 368
 	    {
369 369
 	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
370
-	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
371
-	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
372
-	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
373
-	        $pluginDetails->description = htmlentities($pluginDetails->description);
374
-	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
370
+	        $pluginDetails->enabled=(in_array($plugin, $enabledPlugins)) ? true : false;
371
+	        $pluginDetails->catchAllTraps=($pluginDetails->catchAllTraps === true) ? 'Yes' : 'No';
372
+	        $pluginDetails->processTraps=($pluginDetails->processTraps === true) ? 'Yes' : 'No';
373
+	        $pluginDetails->description=htmlentities($pluginDetails->description);
374
+	        $pluginDetails->description=preg_replace('/\n/', '<br>', $pluginDetails->description);
375 375
 	        array_push($this->view->pluginArray, $pluginDetails);
376 376
 	        // Get functions for function details
377 377
 	        foreach ($pluginDetails->funcArray as $function)
378 378
 	        {
379
-	            array_push($functionList,$function);
379
+	            array_push($functionList, $function);
380 380
 	        }
381 381
 	    }
382 382
 	    
@@ -384,10 +384,10 @@  discard block
 block discarded – undo
384 384
 	    $this->view->functionList=array();
385 385
 	    foreach ($functionList as $function)
386 386
 	    {
387
-	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
388
-	        $functionDetail->params = htmlentities($functionDetail->params);
389
-	        $functionDetail->description = htmlentities($functionDetail->description);
390
-	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
387
+	        $functionDetail=$Trap->pluginClass->getFunctionDetails($function);
388
+	        $functionDetail->params=htmlentities($functionDetail->params);
389
+	        $functionDetail->description=htmlentities($functionDetail->description);
390
+	        $functionDetail->description=preg_replace('/\n/', '<br>', $functionDetail->description);
391 391
 	        array_push($this->view->functionList, $functionDetail);
392 392
 	    }
393 393
 
@@ -399,43 +399,43 @@  discard block
 block discarded – undo
399 399
 	public function debugAction()
400 400
 	{
401 401
 	    $this->view->answer='No answer';
402
-	    $this->view->input1 = '';
402
+	    $this->view->input1='';
403 403
 	    
404 404
 	    $postData=$this->getRequest()->getPost();
405 405
 	    if (isset($postData['input1']))
406 406
 	    {
407
-	        $input1 = $postData['input1'];
408
-	        $input2 = $postData['input2'];
409
-	        $input3 = $postData['input3'];
410
-	        $this->view->input1 = $input1;
407
+	        $input1=$postData['input1'];
408
+	        $input2=$postData['input2'];
409
+	        $input3=$postData['input3'];
410
+	        $this->view->input1=$input1;
411 411
 	        //$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
412 412
 	        try {
413
-	            $this->view->answer = 'Answer : ';
414
-	            $API = $this->getIdoConn();
415
-	            $DB = $this->getUIDatabase();
413
+	            $this->view->answer='Answer : ';
414
+	            $API=$this->getIdoConn();
415
+	            $DB=$this->getUIDatabase();
416 416
 
417 417
 	            //$hosts = $DB->getServicesByHostGroupid($input1);
418 418
 	            //$this->view->answer .= 'services : '.print_r($hosts,true);
419 419
 	            
420
-	            $hosts = $API->getServicesByHostGroupid($input1);
421
-	            $this->view->answer .= 'services : '.print_r($hosts,true);
420
+	            $hosts=$API->getServicesByHostGroupid($input1);
421
+	            $this->view->answer.='services : '.print_r($hosts, true);
422 422
 	            
423 423
 
424 424
 	            
425 425
 	            return;
426
-	            $hosts = $API->getHostByIP($input1);
427
-	            $this->view->answer .= 'Host : '. print_r($hosts,true);
428
-	            $hosts = $API->getHostGroupByName($input1);
429
-	            $this->view->answer .= 'Group : '.print_r($hosts,true);
430
-	            $hosts = $API->getServicesByHostid($input1);
431
-	            $this->view->answer .= 'service : '.print_r($hosts,true);
426
+	            $hosts=$API->getHostByIP($input1);
427
+	            $this->view->answer.='Host : '.print_r($hosts, true);
428
+	            $hosts=$API->getHostGroupByName($input1);
429
+	            $this->view->answer.='Group : '.print_r($hosts, true);
430
+	            $hosts=$API->getServicesByHostid($input1);
431
+	            $this->view->answer.='service : '.print_r($hosts, true);
432 432
 	            
433 433
 	            /* $hosts = $API->getHostsIPByHostGroup($input1);
434 434
 	            $this->view->answer .= "\n Hostgrp : " . print_r($hosts,true); */
435 435
 	            
436 436
 	        } catch (Exception $e)
437 437
 	        {
438
-	            $this->view->answer = "Exception : " . print_r($e);
438
+	            $this->view->answer="Exception : ".print_r($e);
439 439
 	        }
440 440
 	        
441 441
 	    }
@@ -446,19 +446,19 @@  discard block
 block discarded – undo
446 446
 	{
447 447
 		return $this->getTabs()->add('status', array(
448 448
 			'label' => $this->translate('Status'),
449
-			'url'   => $this->getModuleConfig()->urlPath() . '/status')
449
+			'url'   => $this->getModuleConfig()->urlPath().'/status')
450 450
 		)->add('mib', array(
451 451
 			'label' => $this->translate('MIB Management'),
452
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
452
+			'url'   => $this->getModuleConfig()->urlPath().'/status/mib')
453 453
 	    )->add('uimgt', array(
454 454
 	        'label' => $this->translate('UI Configuration'),
455
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
455
+	        'url'   => $this->getModuleConfig()->urlPath().'/status/uimgt')
456 456
         )->add('services', array(
457 457
 			'label' => $this->translate('Services management'),
458
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
458
+			'url'   => $this->getModuleConfig()->urlPath().'/status/services')
459 459
 	    )->add('plugins', array(
460 460
 	        'label' => $this->translate('Plugins management'),
461
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
461
+	        'url'   => $this->getModuleConfig()->urlPath().'/status/plugins')
462 462
 	    );
463 463
 	} 
464 464
 }
@@ -466,7 +466,7 @@  discard block
 block discarded – undo
466 466
 // TODO : see if useless 
467 467
 class UploadForm extends Form
468 468
 { 
469
-    public function __construct($options = null) 
469
+    public function __construct($options=null) 
470 470
     {
471 471
         parent::__construct($options);
472 472
         $this->addElements2();
@@ -475,11 +475,11 @@  discard block
 block discarded – undo
475 475
     public function addElements2()
476 476
     {
477 477
         // File Input
478
-        $file = new File('mib-file');
478
+        $file=new File('mib-file');
479 479
         $file->setLabel('Mib upload');
480 480
              //->setAttrib('multiple', null);
481 481
         $this->addElement($file);
482
-		$button = new Submit("upload",array('ignore'=>false));
483
-		$this->addElement($button);//->setIgnore(false);
482
+		$button=new Submit("upload", array('ignore'=>false));
483
+		$this->addElement($button); //->setIgnore(false);
484 484
     }
485 485
 }
Please login to merge, or discard this patch.
Braces   +19 added lines, -29 removed lines patch added patch discarded remove patch
@@ -22,7 +22,9 @@  discard block
 block discarded – undo
22 22
 		try
23 23
 		{
24 24
 		    $dbConn = $this->getUIDatabase()->getDbConn();
25
-		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
25
+		    if ($dbConn === null) {
26
+		    	throw new \ErrorException('uncatched db error');
27
+		    }
26 28
 			$query = $dbConn->select()->from(
27 29
 				$this->getModuleConfig()->getTrapTableName(),
28 30
 				array('COUNT(*)')
@@ -41,8 +43,7 @@  discard block
 block discarded – undo
41 43
  			
42 44
 			$this->view->trap_days_delete=$this->getUIDatabase()->getDBConfigValue('db_remove_days');
43 45
 			
44
-		}
45
-		catch (Exception $e)
46
+		} catch (Exception $e)
46 47
 		{
47 48
 			$this->displayExitError('status',$e->getMessage());
48 49
 		}
@@ -56,8 +57,7 @@  discard block
 block discarded – undo
56 57
 			$this->view->currentLogFile=$this->getUIDatabase()->getDBConfigValue('log_file');
57 58
 			$this->view->logLevels=$this->getModuleConfig()->getlogLevels();
58 59
 			$this->view->currentLogLevel=$this->getUIDatabase()->getDBConfigValue('log_level');
59
-		}
60
-		catch (Exception $e)
60
+		} catch (Exception $e)
61 61
 		{
62 62
 			$this->displayExitError('status',$e->getMessage());
63 63
 		}
@@ -69,8 +69,7 @@  discard block
 block discarded – undo
69 69
 		    $this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70 70
 		    $this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
71 71
 		    
72
-		}
73
-		catch (Exception $e)
72
+		} catch (Exception $e)
74 73
 		{
75 74
 		    $this->displayExitError('status',$e->getMessage());
76 75
 		}		
@@ -120,8 +119,7 @@  discard block
 block discarded – undo
120 119
 					if ($retVal == 0)
121 120
 					{ // process is alive
122 121
 						$this->_helper->json(array('status'=>'Alive and kicking'));
123
-					}
124
-					else
122
+					} else
125 123
 					{ // process is dead
126 124
 					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
127 125
 					}
@@ -137,22 +135,19 @@  discard block
 block discarded – undo
137 135
 				if (!is_dir($destDir))
138 136
 				{
139 137
 				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
140
-				}
141
-				else
138
+				} else
142 139
 				{
143 140
 				    if (!is_writable($destDir))
144 141
 				    {
145 142
 				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
146
-				    }
147
-				    else
143
+				    } else
148 144
 				    {
149 145
 				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150 146
 				        $sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']);
151 147
 				        if (move_uploaded_file($sourceTmpNam,$destination)===false)
152 148
     				    {
153 149
     				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154
-    				    }
155
-    				    else
150
+    				    } else
156 151
     				    {
157 152
     				        $this->view->uploadStatus="File $name uploaded in $destDir";
158 153
     				    }
@@ -177,18 +172,15 @@  discard block
 block discarded – undo
177 172
 			    {		    
178 173
     				$this->view->snmptranslate='works fine';
179 174
     				$this->view->snmptranslate_state='ok';
180
-			    }
181
-			    else
175
+			    } else
182 176
 			    {
183 177
 			        $this->view->snmptranslate='works fine but missing basic MIBs';
184 178
 			    }
185
-			}
186
-			else
179
+			} else
187 180
 			{
188 181
 				$this->view->snmptranslate='Can execute but no OID to name resolution';
189 182
 			}
190
-		}
191
-		else
183
+		} else
192 184
 		{
193 185
 			$this->view->snmptranslate='Cannot execute';
194 186
 		}
@@ -209,15 +201,13 @@  discard block
 block discarded – undo
209 201
 		if ($retVal==0)
210 202
 		{
211 203
 			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
212
-		}
213
-		else
204
+		} else
214 205
 		{
215 206
 			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
216 207
 			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
217 208
 			{
218 209
 				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
219
-			}
220
-			else
210
+			} else
221 211
 			{
222 212
 				array_push($dirArray,'Install net-snmp-config to see system directories');
223 213
 			}
@@ -256,8 +246,7 @@  discard block
 block discarded – undo
256 246
 	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257 247
 	        {
258 248
 	            $this->view->setError='Max rows must be a number';
259
-	        }
260
-	        else
249
+	        } else
261 250
 	        {
262 251
 	            $this->setitemListDisplay($maxRows);
263 252
 	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
@@ -276,8 +265,9 @@  discard block
 block discarded – undo
276 265
 	        $index = $this->getRequest()->getPost('index',NULL);
277 266
 	        $newname = $this->getRequest()->getPost('newname',NULL);
278 267
 
279
-	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280
-	            $this->_helper->json(array('status'=>'Bad index'));
268
+	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1) {
269
+	        	            $this->_helper->json(array('status'=>'Bad index'));
270
+	        }
281 271
 	        
282 272
 	        switch ($type)
283 273
 	        {
Please login to merge, or discard this patch.
library/Trapdirector/TrapsActions/UIDatabase.php 3 patches
Braces   +18 added lines, -16 removed lines patch added patch discarded remove patch
@@ -126,8 +126,7 @@  discard block
 block discarded – undo
126 126
                 $this->trapController->redirectNow('trapdirector/settings?dberror=5');
127 127
                 return false;
128 128
             }
129
-        }
130
-        catch (Exception $e)
129
+        } catch (Exception $e)
131 130
         {
132 131
             if ($test === true) 
133 132
             {
@@ -152,8 +151,7 @@  discard block
 block discarded – undo
152 151
         try
153 152
         {
154 153
             $dbconn = IcingaDbConnection::fromResourceName($DBname);
155
-        }
156
-        catch (Exception $e)
154
+        } catch (Exception $e)
157 155
         {
158 156
             if ($test === true) 
159 157
             {
@@ -167,8 +165,7 @@  discard block
 block discarded – undo
167 165
         {
168 166
             $dbAdapter=$dbconn->getDbAdapter();
169 167
             
170
-        }
171
-        catch (Exception $e)
168
+        } catch (Exception $e)
172 169
         {
173 170
             if ($test === true)
174 171
             {
@@ -195,7 +192,9 @@  discard block
 block discarded – undo
195 192
      */
196 193
     public function getDb()
197 194
     {
198
-        if ( $this->trapDB != null ) return $this->trapDB;
195
+        if ( $this->trapDB != null ) {
196
+        	return $this->trapDB;
197
+        }
199 198
         
200 199
         
201 200
         $dbresource=$this->trapController->Config()->get('config', 'database');
@@ -223,7 +222,9 @@  discard block
 block discarded – undo
223 222
      */
224 223
     public function getDbConn()
225 224
     {
226
-        if ($this->getDb() == null) return null;
225
+        if ($this->getDb() == null) {
226
+        	return null;
227
+        }
227 228
         return $this->getDb()->getDbAdapter();
228 229
 //        return $this->getDb()->getConnection();
229 230
     }
@@ -254,7 +255,9 @@  discard block
 block discarded – undo
254 255
      */
255 256
     public function getIdoDb()
256 257
     {
257
-        if ( $this->idoDB != null ) return $this->idoDB;
258
+        if ( $this->idoDB != null ) {
259
+        	return $this->idoDB;
260
+        }
258 261
         // TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
259 262
         $dbresource=$this->trapController->Config()->get('config', 'IDOdatabase');;
260 263
         
@@ -267,8 +270,7 @@  discard block
 block discarded – undo
267 270
         try
268 271
         {
269 272
             $dbconn = IcingaDbConnection::fromResourceName($dbresource);
270
-        }
271
-        catch (Exception $e)
273
+        } catch (Exception $e)
272 274
         {
273 275
             $this->trapController->redirectNow('trapdirector/settings?idodberror=2');
274 276
             return null;
@@ -285,7 +287,9 @@  discard block
 block discarded – undo
285 287
      */
286 288
     public function getIdoDbConn()
287 289
     {
288
-        if ($this->getIdoDb() == null) return null;
290
+        if ($this->getIdoDb() == null) {
291
+        	return null;
292
+        }
289 293
         return $this->getIdoDb()->getConnection();
290 294
     }
291 295
     
@@ -307,8 +311,7 @@  discard block
 block discarded – undo
307 311
         try
308 312
         {
309 313
             $dbconn = IcingaDbConnection::fromResourceName($dbresource);
310
-        }
311
-        catch (Exception $e)
314
+        } catch (Exception $e)
312 315
         {
313 316
             throw new DBException( array(2,"Database $dbresource does not exists in IcingaWeb2") );
314 317
         }
@@ -322,8 +325,7 @@  discard block
 block discarded – undo
322 325
             {
323 326
                 throw new DBException( array(4,"$dbresource does not look like an IDO database"));
324 327
             }
325
-        }
326
-        catch (Exception $e)
328
+        } catch (Exception $e)
327 329
         {
328 330
             throw new DBException( array(3,"Error connecting to $dbresource : " . $e->getMessage()));
329 331
         }
Please login to merge, or discard this patch.
Indentation   +260 added lines, -260 removed lines patch added patch discarded remove patch
@@ -19,30 +19,30 @@  discard block
 block discarded – undo
19 19
  */
20 20
 class DBException extends Exception
21 21
 {
22
-    /** @var array $returnArray */
23
-    private $returnArray;
22
+	/** @var array $returnArray */
23
+	private $returnArray;
24 24
     
25
-    /**
26
-     * Buil DBException
27
-     * @param array $retarray
28
-     * @param string $message
29
-     * @param int $code
30
-     * @param Exception $previous
31
-     */
32
-    public function __construct(array $retarray, string $message = "", int $code = 0, Exception $previous = null)
33
-    {
34
-        parent::__construct($message,$code,$previous);
35
-        $this->returnArray = $retarray;
36
-    }
25
+	/**
26
+	 * Buil DBException
27
+	 * @param array $retarray
28
+	 * @param string $message
29
+	 * @param int $code
30
+	 * @param Exception $previous
31
+	 */
32
+	public function __construct(array $retarray, string $message = "", int $code = 0, Exception $previous = null)
33
+	{
34
+		parent::__construct($message,$code,$previous);
35
+		$this->returnArray = $retarray;
36
+	}
37 37
     
38
-    /**
39
-     * Get exception array
40
-     * @return array
41
-     */
42
-    public function getArray()
43
-    {
44
-        return $this->returnArray;
45
-    }
38
+	/**
39
+	 * Get exception array
40
+	 * @return array
41
+	 */
42
+	public function getArray()
43
+	{
44
+		return $this->returnArray;
45
+	}
46 46
 }
47 47
 
48 48
 /**
@@ -56,279 +56,279 @@  discard block
 block discarded – undo
56 56
  */
57 57
 class UIDatabase //extends TrapDBQuery
58 58
 {
59
-    use TrapDBQuery,IdoDBQuery;
59
+	use TrapDBQuery,IdoDBQuery;
60 60
     
61
-    /** @var TrapsController $trapController TrapController 'parent' class */
62
-    protected  $trapController=null;
61
+	/** @var TrapsController $trapController TrapController 'parent' class */
62
+	protected  $trapController=null;
63 63
     
64
-    /** @var Selectable $trapDB Trap Database*/
65
-    protected $trapDB=null;
64
+	/** @var Selectable $trapDB Trap Database*/
65
+	protected $trapDB=null;
66 66
  
67
-    /** @var Selectable $trapDB Icinga IDO database*/
68
-    protected $idoDB=null;
67
+	/** @var Selectable $trapDB Icinga IDO database*/
68
+	protected $idoDB=null;
69 69
     
70
-    /** @var array $testResult */
71
-    protected $testResult;
70
+	/** @var array $testResult */
71
+	protected $testResult;
72 72
     
73
-    /**
74
-     * 
75
-     * @param TrapsController $trapCtrl
76
-     */
77
-    function __construct(TrapsController $trapCtrl)
78
-    {
79
-        $this->trapController=$trapCtrl;
80
-    }
73
+	/**
74
+	 * 
75
+	 * @param TrapsController $trapCtrl
76
+	 */
77
+	function __construct(TrapsController $trapCtrl)
78
+	{
79
+		$this->trapController=$trapCtrl;
80
+	}
81 81
     
82
-    /**
83
-     * Get TrapsController instance
84
-     * @return TrapsController
85
-     */
86
-    protected function getTrapCtrl()
87
-    {
88
-        return $this->trapController;
89
-    }
82
+	/**
83
+	 * Get TrapsController instance
84
+	 * @return TrapsController
85
+	 */
86
+	protected function getTrapCtrl()
87
+	{
88
+		return $this->trapController;
89
+	}
90 90
     
91
-    /**
92
-     * Test if database version >= min database version
93
-     * 
94
-     * @param \Zend_Db_Adapter_Abstract $dbConn
95
-     * @param int $min Minimum version
96
-     * @param bool $test Test mode
97
-     * @param string $DBname Name of DB
98
-     * @return bool true if OK, false if version < min version
99
-     * @throws Exception if error and test = true
100
-     */
101
-    protected function testDbVersion($dbAdapter,int $min,bool $test, string $DBname)
102
-    {
103
-        try
104
-        {
105
-            $query = $dbAdapter->select()
106
-            ->from($this->trapController->getModuleConfig()->getDbConfigTableName(),'value')
107
-            ->where('name=\'db_version\'');
108
-            $version=$dbAdapter->fetchRow($query);
109
-            if ( ($version == null) || ! property_exists($version,'value') )
110
-            {
111
-                if ($test === true) 
112
-                {
113
-                    $this->testResult = array(4,$DBname);
114
-                    return false;
115
-                }
116
-                $this->trapController->redirectNow('trapdirector/settings?dberror=4');
117
-                return false;
118
-            }
119
-            if ($version->value < $min)
120
-            {
121
-                if ($test === true) 
122
-                {
123
-                    $this->testResult = array(5,$version->value,$min);
124
-                    return false;
125
-                }
126
-                $this->trapController->redirectNow('trapdirector/settings?dberror=5');
127
-                return false;
128
-            }
129
-        }
130
-        catch (Exception $e)
131
-        {
132
-            if ($test === true) 
133
-            {
134
-                $this->testResult = array(3,$DBname,$e->getMessage());
135
-                return false;
136
-            }
137
-            $this->trapController->redirectNow('trapdirector/settings?dberror=4');
138
-            return false;
139
-        }
140
-        return true;
141
-    }
91
+	/**
92
+	 * Test if database version >= min database version
93
+	 * 
94
+	 * @param \Zend_Db_Adapter_Abstract $dbConn
95
+	 * @param int $min Minimum version
96
+	 * @param bool $test Test mode
97
+	 * @param string $DBname Name of DB
98
+	 * @return bool true if OK, false if version < min version
99
+	 * @throws Exception if error and test = true
100
+	 */
101
+	protected function testDbVersion($dbAdapter,int $min,bool $test, string $DBname)
102
+	{
103
+		try
104
+		{
105
+			$query = $dbAdapter->select()
106
+			->from($this->trapController->getModuleConfig()->getDbConfigTableName(),'value')
107
+			->where('name=\'db_version\'');
108
+			$version=$dbAdapter->fetchRow($query);
109
+			if ( ($version == null) || ! property_exists($version,'value') )
110
+			{
111
+				if ($test === true) 
112
+				{
113
+					$this->testResult = array(4,$DBname);
114
+					return false;
115
+				}
116
+				$this->trapController->redirectNow('trapdirector/settings?dberror=4');
117
+				return false;
118
+			}
119
+			if ($version->value < $min)
120
+			{
121
+				if ($test === true) 
122
+				{
123
+					$this->testResult = array(5,$version->value,$min);
124
+					return false;
125
+				}
126
+				$this->trapController->redirectNow('trapdirector/settings?dberror=5');
127
+				return false;
128
+			}
129
+		}
130
+		catch (Exception $e)
131
+		{
132
+			if ($test === true) 
133
+			{
134
+				$this->testResult = array(3,$DBname,$e->getMessage());
135
+				return false;
136
+			}
137
+			$this->trapController->redirectNow('trapdirector/settings?dberror=4');
138
+			return false;
139
+		}
140
+		return true;
141
+	}
142 142
     
143
-    /**	Get Database connexion
144
-     *	@param $DBname string DB name in resource.ini_ge
145
-     *	@param $test bool if set to true, returns error code and not database
146
-     *	@param $test_version bool if set to flase, does not test database version of trapDB
147
-     *  @throws DBException if test = true and error
148
-     *	@return Selectable|null : if test=false, returns DB connexion, else array(error_num,message) or null on error.
149
-     */
150
-    protected function getDbByName($DBname , $test = false , $test_version = true)
151
-    {
152
-        try
153
-        {
154
-            $dbconn = IcingaDbConnection::fromResourceName($DBname);
155
-        }
156
-        catch (Exception $e)
157
-        {
158
-            if ($test === true) 
159
-            {
160
-                throw new DBException(array(2,$DBname));
161
-            }
162
-            $this->trapController->redirectNow('trapdirector/settings?dberror=2');
163
-            return null;
164
-        }
143
+	/**	Get Database connexion
144
+	 *	@param $DBname string DB name in resource.ini_ge
145
+	 *	@param $test bool if set to true, returns error code and not database
146
+	 *	@param $test_version bool if set to flase, does not test database version of trapDB
147
+	 *  @throws DBException if test = true and error
148
+	 *	@return Selectable|null : if test=false, returns DB connexion, else array(error_num,message) or null on error.
149
+	 */
150
+	protected function getDbByName($DBname , $test = false , $test_version = true)
151
+	{
152
+		try
153
+		{
154
+			$dbconn = IcingaDbConnection::fromResourceName($DBname);
155
+		}
156
+		catch (Exception $e)
157
+		{
158
+			if ($test === true) 
159
+			{
160
+				throw new DBException(array(2,$DBname));
161
+			}
162
+			$this->trapController->redirectNow('trapdirector/settings?dberror=2');
163
+			return null;
164
+		}
165 165
         
166
-        try
167
-        {
168
-            $dbAdapter=$dbconn->getDbAdapter();
166
+		try
167
+		{
168
+			$dbAdapter=$dbconn->getDbAdapter();
169 169
             
170
-        }
171
-        catch (Exception $e)
172
-        {
173
-            if ($test === true)
174
-            {
175
-                throw new DBException(array(3,$DBname,$e->getMessage()));
176
-            }
177
-            $this->trapController->redirectNow('trapdirector/settings?dberror=3');
178
-            return null;
179
-        }
170
+		}
171
+		catch (Exception $e)
172
+		{
173
+			if ($test === true)
174
+			{
175
+				throw new DBException(array(3,$DBname,$e->getMessage()));
176
+			}
177
+			$this->trapController->redirectNow('trapdirector/settings?dberror=3');
178
+			return null;
179
+		}
180 180
         
181
-        if ($test_version == true) {
182
-            $testRet=$this->testDbVersion($dbAdapter, $this->trapController->getModuleConfig()->getDbMinVersion(), $test, $DBname);
183
-            if ($testRet !== true) 
184
-            {
185
-                throw new DBException($this->testResult);
186
-            }
187
-        }
181
+		if ($test_version == true) {
182
+			$testRet=$this->testDbVersion($dbAdapter, $this->trapController->getModuleConfig()->getDbMinVersion(), $test, $DBname);
183
+			if ($testRet !== true) 
184
+			{
185
+				throw new DBException($this->testResult);
186
+			}
187
+		}
188 188
         
189
-        return $dbconn;
190
-    }
189
+		return $dbconn;
190
+	}
191 191
 
192
-    /**
193
-     * Get Trap database
194
-     * @return Selectable|null : returns DB connexion or null on error.
195
-     */
196
-    public function getDb()
197
-    {
198
-        if ( $this->trapDB != null ) return $this->trapDB;
192
+	/**
193
+	 * Get Trap database
194
+	 * @return Selectable|null : returns DB connexion or null on error.
195
+	 */
196
+	public function getDb()
197
+	{
198
+		if ( $this->trapDB != null ) return $this->trapDB;
199 199
         
200 200
         
201
-        $dbresource=$this->trapController->Config()->get('config', 'database');
201
+		$dbresource=$this->trapController->Config()->get('config', 'database');
202 202
         
203
-        if ( ! $dbresource )
204
-        {
205
-            $this->trapController->redirectNow('trapdirector/settings?dberror=1');
206
-            return null;
207
-        }
203
+		if ( ! $dbresource )
204
+		{
205
+			$this->trapController->redirectNow('trapdirector/settings?dberror=1');
206
+			return null;
207
+		}
208 208
 
209
-        try {
210
-            $this->trapDB = $this->getDbByName($dbresource,false,true);
211
-        } catch (DBException $e) {
212
-            return null; // Should not happen as test = false
213
-        }
209
+		try {
210
+			$this->trapDB = $this->getDbByName($dbresource,false,true);
211
+		} catch (DBException $e) {
212
+			return null; // Should not happen as test = false
213
+		}
214 214
         
215
-        //$this->trapDB->getConnection();
215
+		//$this->trapDB->getConnection();
216 216
         
217
-        return $this->trapDB;
218
-    }
217
+		return $this->trapDB;
218
+	}
219 219
 
220
-    /**
221
-     * Get Zend adapter of DB.
222
-     * @return \Zend_Db_Adapter_Abstract|null
223
-     */
224
-    public function getDbConn()
225
-    {
226
-        if ($this->getDb() == null) return null;
227
-        return $this->getDb()->getDbAdapter();
220
+	/**
221
+	 * Get Zend adapter of DB.
222
+	 * @return \Zend_Db_Adapter_Abstract|null
223
+	 */
224
+	public function getDbConn()
225
+	{
226
+		if ($this->getDb() == null) return null;
227
+		return $this->getDb()->getDbAdapter();
228 228
 //        return $this->getDb()->getConnection();
229
-    }
229
+	}
230 230
     
231
-    /**
232
-     * Test Trap database
233
-     * @param boolean $test
234
-     * @throws DBException on error.
235
-     * @return \Zend_Db_Adapter_Abstract|array|null : if test=false, returns DB connexion, else array(error_num,message) or null on error.
236
-     */
237
-    public function testGetDb()
238
-    {       
239
-        $dbresource=$this->trapController->Config()->get('config', 'database');
231
+	/**
232
+	 * Test Trap database
233
+	 * @param boolean $test
234
+	 * @throws DBException on error.
235
+	 * @return \Zend_Db_Adapter_Abstract|array|null : if test=false, returns DB connexion, else array(error_num,message) or null on error.
236
+	 */
237
+	public function testGetDb()
238
+	{       
239
+		$dbresource=$this->trapController->Config()->get('config', 'database');
240 240
         
241
-        if ( ! $dbresource )
242
-        {
243
-                throw new DBException(array(1,''));
244
-        }
241
+		if ( ! $dbresource )
242
+		{
243
+				throw new DBException(array(1,''));
244
+		}
245 245
         
246
-        $this->trapDB = $this->getDbByName($dbresource,true,true);       
247
-        return;
248
-    }
246
+		$this->trapDB = $this->getDbByName($dbresource,true,true);       
247
+		return;
248
+	}
249 249
     
250 250
 
251
-    /**
252
-     * Get IDO Database
253
-     * @return \Zend_Db_Adapter_Abstract|NULL  returns DB connexion or null on error.
254
-     */
255
-    public function getIdoDb()
256
-    {
257
-        if ( $this->idoDB != null ) return $this->idoDB;
258
-        // TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
259
-        $dbresource=$this->trapController->Config()->get('config', 'IDOdatabase');;
251
+	/**
252
+	 * Get IDO Database
253
+	 * @return \Zend_Db_Adapter_Abstract|NULL  returns DB connexion or null on error.
254
+	 */
255
+	public function getIdoDb()
256
+	{
257
+		if ( $this->idoDB != null ) return $this->idoDB;
258
+		// TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
259
+		$dbresource=$this->trapController->Config()->get('config', 'IDOdatabase');;
260 260
         
261
-        if ( ! $dbresource )
262
-        {
263
-            $this->trapController->redirectNow('trapdirector/settings?idodberror=1');
264
-            return null;
265
-        }
261
+		if ( ! $dbresource )
262
+		{
263
+			$this->trapController->redirectNow('trapdirector/settings?idodberror=1');
264
+			return null;
265
+		}
266 266
         
267
-        try
268
-        {
269
-            $dbconn = IcingaDbConnection::fromResourceName($dbresource);
270
-        }
271
-        catch (Exception $e)
272
-        {
273
-            $this->trapController->redirectNow('trapdirector/settings?idodberror=2');
274
-            return null;
275
-        }
267
+		try
268
+		{
269
+			$dbconn = IcingaDbConnection::fromResourceName($dbresource);
270
+		}
271
+		catch (Exception $e)
272
+		{
273
+			$this->trapController->redirectNow('trapdirector/settings?idodberror=2');
274
+			return null;
275
+		}
276 276
 
277
-        $this->idoDB = $dbconn;
278
-        return $this->idoDB;
279
-    }
277
+		$this->idoDB = $dbconn;
278
+		return $this->idoDB;
279
+	}
280 280
 
281 281
 
282
-    /**
283
-     * Get Zend adapter of DB.
284
-     * @return \Zend_Db_Adapter_Abstract|null
285
-     */
286
-    public function getIdoDbConn()
287
-    {
288
-        if ($this->getIdoDb() == null) return null;
289
-        return $this->getIdoDb()->getConnection();
290
-    }
282
+	/**
283
+	 * Get Zend adapter of DB.
284
+	 * @return \Zend_Db_Adapter_Abstract|null
285
+	 */
286
+	public function getIdoDbConn()
287
+	{
288
+		if ($this->getIdoDb() == null) return null;
289
+		return $this->getIdoDb()->getConnection();
290
+	}
291 291
     
292
-    /**
293
-     * Get IDO Database
294
-     * @param boolean $test
295
-     * @throws DBException on error
296
-     */
297
-    public function testGetIdoDb()
298
-    {
299
-        // TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
300
-        $dbresource=$this->trapController->Config()->get('config', 'IDOdatabase');;
292
+	/**
293
+	 * Get IDO Database
294
+	 * @param boolean $test
295
+	 * @throws DBException on error
296
+	 */
297
+	public function testGetIdoDb()
298
+	{
299
+		// TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
300
+		$dbresource=$this->trapController->Config()->get('config', 'IDOdatabase');;
301 301
         
302
-        if ( ! $dbresource )
303
-        {
304
-            throw new DBException(array(1,'No database in config.ini'));
305
-        }
302
+		if ( ! $dbresource )
303
+		{
304
+			throw new DBException(array(1,'No database in config.ini'));
305
+		}
306 306
         
307
-        try
308
-        {
309
-            $dbconn = IcingaDbConnection::fromResourceName($dbresource);
310
-        }
311
-        catch (Exception $e)
312
-        {
313
-            throw new DBException( array(2,"Database $dbresource does not exists in IcingaWeb2") );
314
-        }
307
+		try
308
+		{
309
+			$dbconn = IcingaDbConnection::fromResourceName($dbresource);
310
+		}
311
+		catch (Exception $e)
312
+		{
313
+			throw new DBException( array(2,"Database $dbresource does not exists in IcingaWeb2") );
314
+		}
315 315
                
316
-        try
317
-        {
318
-            $query = $dbconn->select()
319
-            ->from('icinga_dbversion',array('version'));
320
-            $version=$dbconn->fetchRow($query);
321
-            if ( ($version == null) || ! property_exists($version,'version') )
322
-            {
323
-                throw new DBException( array(4,"$dbresource does not look like an IDO database"));
324
-            }
325
-        }
326
-        catch (Exception $e)
327
-        {
328
-            throw new DBException( array(3,"Error connecting to $dbresource : " . $e->getMessage()));
329
-        }
316
+		try
317
+		{
318
+			$query = $dbconn->select()
319
+			->from('icinga_dbversion',array('version'));
320
+			$version=$dbconn->fetchRow($query);
321
+			if ( ($version == null) || ! property_exists($version,'version') )
322
+			{
323
+				throw new DBException( array(4,"$dbresource does not look like an IDO database"));
324
+			}
325
+		}
326
+		catch (Exception $e)
327
+		{
328
+			throw new DBException( array(3,"Error connecting to $dbresource : " . $e->getMessage()));
329
+		}
330 330
         
331
-        return;
332
-    }
331
+		return;
332
+	}
333 333
     
334 334
 }
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -29,10 +29,10 @@  discard block
 block discarded – undo
29 29
      * @param int $code
30 30
      * @param Exception $previous
31 31
      */
32
-    public function __construct(array $retarray, string $message = "", int $code = 0, Exception $previous = null)
32
+    public function __construct(array $retarray, string $message="", int $code=0, Exception $previous=null)
33 33
     {
34
-        parent::__construct($message,$code,$previous);
35
-        $this->returnArray = $retarray;
34
+        parent::__construct($message, $code, $previous);
35
+        $this->returnArray=$retarray;
36 36
     }
37 37
     
38 38
     /**
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
  */
57 57
 class UIDatabase //extends TrapDBQuery
58 58
 {
59
-    use TrapDBQuery,IdoDBQuery;
59
+    use TrapDBQuery, IdoDBQuery;
60 60
     
61 61
     /** @var TrapsController $trapController TrapController 'parent' class */
62 62
     protected  $trapController=null;
@@ -98,19 +98,19 @@  discard block
 block discarded – undo
98 98
      * @return bool true if OK, false if version < min version
99 99
      * @throws Exception if error and test = true
100 100
      */
101
-    protected function testDbVersion($dbAdapter,int $min,bool $test, string $DBname)
101
+    protected function testDbVersion($dbAdapter, int $min, bool $test, string $DBname)
102 102
     {
103 103
         try
104 104
         {
105
-            $query = $dbAdapter->select()
106
-            ->from($this->trapController->getModuleConfig()->getDbConfigTableName(),'value')
105
+            $query=$dbAdapter->select()
106
+            ->from($this->trapController->getModuleConfig()->getDbConfigTableName(), 'value')
107 107
             ->where('name=\'db_version\'');
108 108
             $version=$dbAdapter->fetchRow($query);
109
-            if ( ($version == null) || ! property_exists($version,'value') )
109
+            if (($version == null) || !property_exists($version, 'value'))
110 110
             {
111 111
                 if ($test === true) 
112 112
                 {
113
-                    $this->testResult = array(4,$DBname);
113
+                    $this->testResult=array(4, $DBname);
114 114
                     return false;
115 115
                 }
116 116
                 $this->trapController->redirectNow('trapdirector/settings?dberror=4');
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
             {
121 121
                 if ($test === true) 
122 122
                 {
123
-                    $this->testResult = array(5,$version->value,$min);
123
+                    $this->testResult=array(5, $version->value, $min);
124 124
                     return false;
125 125
                 }
126 126
                 $this->trapController->redirectNow('trapdirector/settings?dberror=5');
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
         {
132 132
             if ($test === true) 
133 133
             {
134
-                $this->testResult = array(3,$DBname,$e->getMessage());
134
+                $this->testResult=array(3, $DBname, $e->getMessage());
135 135
                 return false;
136 136
             }
137 137
             $this->trapController->redirectNow('trapdirector/settings?dberror=4');
@@ -147,17 +147,17 @@  discard block
 block discarded – undo
147 147
      *  @throws DBException if test = true and error
148 148
      *	@return Selectable|null : if test=false, returns DB connexion, else array(error_num,message) or null on error.
149 149
      */
150
-    protected function getDbByName($DBname , $test = false , $test_version = true)
150
+    protected function getDbByName($DBname, $test=false, $test_version=true)
151 151
     {
152 152
         try
153 153
         {
154
-            $dbconn = IcingaDbConnection::fromResourceName($DBname);
154
+            $dbconn=IcingaDbConnection::fromResourceName($DBname);
155 155
         }
156 156
         catch (Exception $e)
157 157
         {
158 158
             if ($test === true) 
159 159
             {
160
-                throw new DBException(array(2,$DBname));
160
+                throw new DBException(array(2, $DBname));
161 161
             }
162 162
             $this->trapController->redirectNow('trapdirector/settings?dberror=2');
163 163
             return null;
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
         {
173 173
             if ($test === true)
174 174
             {
175
-                throw new DBException(array(3,$DBname,$e->getMessage()));
175
+                throw new DBException(array(3, $DBname, $e->getMessage()));
176 176
             }
177 177
             $this->trapController->redirectNow('trapdirector/settings?dberror=3');
178 178
             return null;
@@ -195,19 +195,19 @@  discard block
 block discarded – undo
195 195
      */
196 196
     public function getDb()
197 197
     {
198
-        if ( $this->trapDB != null ) return $this->trapDB;
198
+        if ($this->trapDB != null) return $this->trapDB;
199 199
         
200 200
         
201 201
         $dbresource=$this->trapController->Config()->get('config', 'database');
202 202
         
203
-        if ( ! $dbresource )
203
+        if (!$dbresource)
204 204
         {
205 205
             $this->trapController->redirectNow('trapdirector/settings?dberror=1');
206 206
             return null;
207 207
         }
208 208
 
209 209
         try {
210
-            $this->trapDB = $this->getDbByName($dbresource,false,true);
210
+            $this->trapDB=$this->getDbByName($dbresource, false, true);
211 211
         } catch (DBException $e) {
212 212
             return null; // Should not happen as test = false
213 213
         }
@@ -238,12 +238,12 @@  discard block
 block discarded – undo
238 238
     {       
239 239
         $dbresource=$this->trapController->Config()->get('config', 'database');
240 240
         
241
-        if ( ! $dbresource )
241
+        if (!$dbresource)
242 242
         {
243
-                throw new DBException(array(1,''));
243
+                throw new DBException(array(1, ''));
244 244
         }
245 245
         
246
-        $this->trapDB = $this->getDbByName($dbresource,true,true);       
246
+        $this->trapDB=$this->getDbByName($dbresource, true, true);       
247 247
         return;
248 248
     }
249 249
     
@@ -254,11 +254,11 @@  discard block
 block discarded – undo
254 254
      */
255 255
     public function getIdoDb()
256 256
     {
257
-        if ( $this->idoDB != null ) return $this->idoDB;
257
+        if ($this->idoDB != null) return $this->idoDB;
258 258
         // TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
259
-        $dbresource=$this->trapController->Config()->get('config', 'IDOdatabase');;
259
+        $dbresource=$this->trapController->Config()->get('config', 'IDOdatabase'); ;
260 260
         
261
-        if ( ! $dbresource )
261
+        if (!$dbresource)
262 262
         {
263 263
             $this->trapController->redirectNow('trapdirector/settings?idodberror=1');
264 264
             return null;
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
         
267 267
         try
268 268
         {
269
-            $dbconn = IcingaDbConnection::fromResourceName($dbresource);
269
+            $dbconn=IcingaDbConnection::fromResourceName($dbresource);
270 270
         }
271 271
         catch (Exception $e)
272 272
         {
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
             return null;
275 275
         }
276 276
 
277
-        $this->idoDB = $dbconn;
277
+        $this->idoDB=$dbconn;
278 278
         return $this->idoDB;
279 279
     }
280 280
 
@@ -297,35 +297,35 @@  discard block
 block discarded – undo
297 297
     public function testGetIdoDb()
298 298
     {
299 299
         // TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
300
-        $dbresource=$this->trapController->Config()->get('config', 'IDOdatabase');;
300
+        $dbresource=$this->trapController->Config()->get('config', 'IDOdatabase'); ;
301 301
         
302
-        if ( ! $dbresource )
302
+        if (!$dbresource)
303 303
         {
304
-            throw new DBException(array(1,'No database in config.ini'));
304
+            throw new DBException(array(1, 'No database in config.ini'));
305 305
         }
306 306
         
307 307
         try
308 308
         {
309
-            $dbconn = IcingaDbConnection::fromResourceName($dbresource);
309
+            $dbconn=IcingaDbConnection::fromResourceName($dbresource);
310 310
         }
311 311
         catch (Exception $e)
312 312
         {
313
-            throw new DBException( array(2,"Database $dbresource does not exists in IcingaWeb2") );
313
+            throw new DBException(array(2, "Database $dbresource does not exists in IcingaWeb2"));
314 314
         }
315 315
                
316 316
         try
317 317
         {
318
-            $query = $dbconn->select()
319
-            ->from('icinga_dbversion',array('version'));
318
+            $query=$dbconn->select()
319
+            ->from('icinga_dbversion', array('version'));
320 320
             $version=$dbconn->fetchRow($query);
321
-            if ( ($version == null) || ! property_exists($version,'version') )
321
+            if (($version == null) || !property_exists($version, 'version'))
322 322
             {
323
-                throw new DBException( array(4,"$dbresource does not look like an IDO database"));
323
+                throw new DBException(array(4, "$dbresource does not look like an IDO database"));
324 324
             }
325 325
         }
326 326
         catch (Exception $e)
327 327
         {
328
-            throw new DBException( array(3,"Error connecting to $dbresource : " . $e->getMessage()));
328
+            throw new DBException(array(3, "Error connecting to $dbresource : ".$e->getMessage()));
329 329
         }
330 330
         
331 331
         return;
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/TrapConfig.php 3 patches
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -15,197 +15,197 @@
 block discarded – undo
15 15
 trait TrapConfig
16 16
 {
17 17
 
18
-    /** @return \Trapdirector\Logging   */
19
-    abstract public function getLogging();
20
-    /** @return \Trapdirector\TrapApi   */
21
-    abstract public function getTrapApi();
18
+	/** @return \Trapdirector\Logging   */
19
+	abstract public function getLogging();
20
+	/** @return \Trapdirector\TrapApi   */
21
+	abstract public function getTrapApi();
22 22
 
23
-    // TODO : Get default values from TrapModuleConfig 
24
-    /** @var bool	Use SnmpTrapAddess as source adress */
25
-    public $useSnmpTrapAddess=TRUE;
26
-    /** @var string	Special OID to get IP source address of trap emitter */
27
-    public $snmpTrapAddressOID='.1.3.6.1.6.3.18.1.3';
23
+	// TODO : Get default values from TrapModuleConfig 
24
+	/** @var bool	Use SnmpTrapAddess as source adress */
25
+	public $useSnmpTrapAddess=TRUE;
26
+	/** @var string	Special OID to get IP source address of trap emitter */
27
+	public $snmpTrapAddressOID='.1.3.6.1.6.3.18.1.3';
28 28
     
29
-    /**
30
-     * Get option from array of ini file, send message if empty
31
-     * @param string $option_array Array of ini file
32
-     * @param string $option_category category in ini file
33
-     * @param string $option_name name of option in category
34
-     * @param mixed $option_var variable to fill if found, left untouched if not found
35
-     * @param integer $log_level default 2 (warning)
36
-     * @param string $message warning message if not found
37
-     * @return boolean true if found, or false
38
-     */
39
-    protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = WARN, $message = null)
40
-    {
41
-        if (!isset($option_array[$option_category][$option_name]))
42
-        {
43
-            if ($message === null)
44
-            {
45
-                $message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
46
-            }
47
-            $this->getLogging()->log($message,$log_level);
48
-            return false;
49
-        }
50
-        else
51
-        {
52
-            $option_var=$option_array[$option_category][$option_name];
53
-            return true;
54
-        }
55
-    }
29
+	/**
30
+	 * Get option from array of ini file, send message if empty
31
+	 * @param string $option_array Array of ini file
32
+	 * @param string $option_category category in ini file
33
+	 * @param string $option_name name of option in category
34
+	 * @param mixed $option_var variable to fill if found, left untouched if not found
35
+	 * @param integer $log_level default 2 (warning)
36
+	 * @param string $message warning message if not found
37
+	 * @return boolean true if found, or false
38
+	 */
39
+	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = WARN, $message = null)
40
+	{
41
+		if (!isset($option_array[$option_category][$option_name]))
42
+		{
43
+			if ($message === null)
44
+			{
45
+				$message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
46
+			}
47
+			$this->getLogging()->log($message,$log_level);
48
+			return false;
49
+		}
50
+		else
51
+		{
52
+			$option_var=$option_array[$option_category][$option_name];
53
+			return true;
54
+		}
55
+	}
56 56
 
57
-    /**
58
-     * Get options in database
59
-     */
60
-    protected function getDatabaseOptions()
61
-    {
62
-        // Database options
63
-        if ($this->logSetup === false) // Only if logging was no setup in constructor
64
-        {
65
-            $this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
66
-            $this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
67
-            $this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
68
-        }
69
-        
70
-        $tmpVal = -1; // Get boolean coded in database as 1/0
71
-        $this->getDBConfigIfSet('use_SnmpTrapAddess', $tmpVal);
72
-        if ($tmpVal != -1) $this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
73
-        
74
-        $this->getDBConfigIfSet('SnmpTrapAddess_oid', $this->snmpTrapAddressOID); // Get oid then replace '.' with '\.' to use in regexp whrn reading traps
75
-        $this->snmpTrapAddressOID = preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
76
-    }
77
-        
78
-    /** Set $variable to value if $element found in database config table
79
-     * @param string $element
80
-     * @param string $variable
81
-     */
82
-    protected function getDBConfigIfSet($element,&$variable)
83
-    {
84
-        $value=$this->getDBConfig($element);
85
-        if ($value != null) $variable=$value;
86
-    }
57
+	/**
58
+	 * Get options in database
59
+	 */
60
+	protected function getDatabaseOptions()
61
+	{
62
+		// Database options
63
+		if ($this->logSetup === false) // Only if logging was no setup in constructor
64
+		{
65
+			$this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
66
+			$this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
67
+			$this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
68
+		}
69
+        
70
+		$tmpVal = -1; // Get boolean coded in database as 1/0
71
+		$this->getDBConfigIfSet('use_SnmpTrapAddess', $tmpVal);
72
+		if ($tmpVal != -1) $this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
73
+        
74
+		$this->getDBConfigIfSet('SnmpTrapAddess_oid', $this->snmpTrapAddressOID); // Get oid then replace '.' with '\.' to use in regexp whrn reading traps
75
+		$this->snmpTrapAddressOID = preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
76
+	}
77
+        
78
+	/** Set $variable to value if $element found in database config table
79
+	 * @param string $element
80
+	 * @param string $variable
81
+	 */
82
+	protected function getDBConfigIfSet($element,&$variable)
83
+	{
84
+		$value=$this->getDBConfig($element);
85
+		if ($value != null) $variable=$value;
86
+	}
87 87
     
88
-    /**
89
-     *   Get data from db_config
90
-     *	@param $element string name of param
91
-     *	@return mixed : value (or null)
92
-     */
93
-    protected function getDBConfig($element)  // TODO : put this in DB class
94
-    {
95
-        $db_conn=$this->trapsDB->db_connect_trap();
96
-        $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
97
-        if (($ret_code=$db_conn->query($sql)) === false) {
98
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
99
-            return null;
100
-        }
101
-        $value=$ret_code->fetch();
102
-        if ($value != null && isset($value['value']))
103
-        {
104
-            return $value['value'];
105
-        }
106
-        return null;
107
-    }
88
+	/**
89
+	 *   Get data from db_config
90
+	 *	@param $element string name of param
91
+	 *	@return mixed : value (or null)
92
+	 */
93
+	protected function getDBConfig($element)  // TODO : put this in DB class
94
+	{
95
+		$db_conn=$this->trapsDB->db_connect_trap();
96
+		$sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
97
+		if (($ret_code=$db_conn->query($sql)) === false) {
98
+			$this->logging->log('No result in query : ' . $sql,WARN,'');
99
+			return null;
100
+		}
101
+		$value=$ret_code->fetch();
102
+		if ($value != null && isset($value['value']))
103
+		{
104
+			return $value['value'];
105
+		}
106
+		return null;
107
+	}
108 108
     
109
-    /**
110
-     * Get options from ini file
111
-     * @param array $trap_config : ini file array
112
-     */
113
-    protected function getMainOptions($trapConfig)
114
-    {
115
-        
116
-        $nodeStatus='';
117
-        $this->getOptionIfSet($trapConfig,'config','node', $nodeStatus);
118
-        if ($this->getTrapApi()->setStatus($nodeStatus) === FALSE)
119
-        {
120
-            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
121
-            $this->getTrapApi()->setStatusMaster();
122
-        }
123
-        else 
124
-        {
125
-            if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
126
-            {
127
-                // Get options to connect to API
128
-                $IP = $port = $user =  $pass = null;
129
-                $this->getOptionIfSet($trapConfig,'config','masterIP', $IP, ERROR);
130
-                $this->getOptionIfSet($trapConfig,'config','masterPort', $port, ERROR);
131
-                $this->getOptionIfSet($trapConfig,'config','masterUser', $user, ERROR);
132
-                $this->getOptionIfSet($trapConfig,'config','masterPass', $pass, ERROR);
133
-                $this->getTrapApi()->setParams($IP, $port, $user, $pass);
134
-                return;
135
-            }
136
-        }
137
-        
138
-        // Snmptranslate binary path
139
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
140
-        
141
-        // mibs path
142
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
143
-        
144
-        // icinga2cmd path
145
-        $this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
146
-        
147
-        // table prefix
148
-        $this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
149
-        
150
-        // API options
151
-        if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
152
-        {
153
-            $this->apiUse=true;
154
-            // Get API options or throw exception as not configured correctly
155
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort,ERROR);
156
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername,ERROR);
157
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword,ERROR);
158
-        }
159
-    }
109
+	/**
110
+	 * Get options from ini file
111
+	 * @param array $trap_config : ini file array
112
+	 */
113
+	protected function getMainOptions($trapConfig)
114
+	{
115
+        
116
+		$nodeStatus='';
117
+		$this->getOptionIfSet($trapConfig,'config','node', $nodeStatus);
118
+		if ($this->getTrapApi()->setStatus($nodeStatus) === FALSE)
119
+		{
120
+			$this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
121
+			$this->getTrapApi()->setStatusMaster();
122
+		}
123
+		else 
124
+		{
125
+			if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
126
+			{
127
+				// Get options to connect to API
128
+				$IP = $port = $user =  $pass = null;
129
+				$this->getOptionIfSet($trapConfig,'config','masterIP', $IP, ERROR);
130
+				$this->getOptionIfSet($trapConfig,'config','masterPort', $port, ERROR);
131
+				$this->getOptionIfSet($trapConfig,'config','masterUser', $user, ERROR);
132
+				$this->getOptionIfSet($trapConfig,'config','masterPass', $pass, ERROR);
133
+				$this->getTrapApi()->setParams($IP, $port, $user, $pass);
134
+				return;
135
+			}
136
+		}
137
+        
138
+		// Snmptranslate binary path
139
+		$this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
140
+        
141
+		// mibs path
142
+		$this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
143
+        
144
+		// icinga2cmd path
145
+		$this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
146
+        
147
+		// table prefix
148
+		$this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
149
+        
150
+		// API options
151
+		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
152
+		{
153
+			$this->apiUse=true;
154
+			// Get API options or throw exception as not configured correctly
155
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort,ERROR);
156
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername,ERROR);
157
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword,ERROR);
158
+		}
159
+	}
160 160
     
161
-    /**
162
-     * Create and setup database class for trap & ido (if no api) db
163
-     * @param array $trap_config : ini file array
164
-     */
165
-    protected function setupDatabase($trapConfig)
166
-    {
167
-        // Trap database
168
-        if (!array_key_exists('database',$trapConfig['config']))
169
-        {
170
-            $this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
171
-            return;
172
-        }
173
-        $dbTrapName=$trapConfig['config']['database'];
174
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
175
-        
176
-        if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
177
-        {
178
-            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
179
-            return;
180
-        }
181
-        if (!array_key_exists($dbTrapName,$dbConfig))
182
-        {
183
-            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
184
-            return;
185
-        }
186
-        
187
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
188
-        
189
-        $this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG );
190
-        
191
-        //TODO enable this again when API queries are all done :
192
-        if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
193
-        
194
-        // IDO Database
195
-        if (!array_key_exists('IDOdatabase',$trapConfig['config']))
196
-        {
197
-            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
198
-        }
199
-        $dbIdoName=$trapConfig['config']['IDOdatabase'];
200
-        
201
-        $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
202
-        if (!array_key_exists($dbIdoName,$dbConfig))
203
-        {
204
-            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
205
-            return;
206
-        }
207
-        
208
-        $this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
209
-    }
161
+	/**
162
+	 * Create and setup database class for trap & ido (if no api) db
163
+	 * @param array $trap_config : ini file array
164
+	 */
165
+	protected function setupDatabase($trapConfig)
166
+	{
167
+		// Trap database
168
+		if (!array_key_exists('database',$trapConfig['config']))
169
+		{
170
+			$this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
171
+			return;
172
+		}
173
+		$dbTrapName=$trapConfig['config']['database'];
174
+		$this->logging->log("Found database in config file: ".$dbTrapName,INFO );
175
+        
176
+		if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
177
+		{
178
+			$this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
179
+			return;
180
+		}
181
+		if (!array_key_exists($dbTrapName,$dbConfig))
182
+		{
183
+			$this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
184
+			return;
185
+		}
186
+        
187
+		$this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
188
+        
189
+		$this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG );
190
+        
191
+		//TODO enable this again when API queries are all done :
192
+		if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
193
+        
194
+		// IDO Database
195
+		if (!array_key_exists('IDOdatabase',$trapConfig['config']))
196
+		{
197
+			$this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
198
+		}
199
+		$dbIdoName=$trapConfig['config']['IDOdatabase'];
200
+        
201
+		$this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
202
+		if (!array_key_exists($dbIdoName,$dbConfig))
203
+		{
204
+			$this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
205
+			return;
206
+		}
207
+        
208
+		$this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
209
+	}
210 210
     
211 211
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -36,15 +36,15 @@  discard block
 block discarded – undo
36 36
      * @param string $message warning message if not found
37 37
      * @return boolean true if found, or false
38 38
      */
39
-    protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = WARN, $message = null)
39
+    protected function getOptionIfSet($option_array, $option_category, $option_name, &$option_var, $log_level=WARN, $message=null)
40 40
     {
41 41
         if (!isset($option_array[$option_category][$option_name]))
42 42
         {
43 43
             if ($message === null)
44 44
             {
45
-                $message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
45
+                $message='No '.$option_name.' in config file: '.$this->trapModuleConfig;
46 46
             }
47
-            $this->getLogging()->log($message,$log_level);
47
+            $this->getLogging()->log($message, $log_level);
48 48
             return false;
49 49
         }
50 50
         else
@@ -62,24 +62,24 @@  discard block
 block discarded – undo
62 62
         // Database options
63 63
         if ($this->logSetup === false) // Only if logging was no setup in constructor
64 64
         {
65
-            $this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
66
-            $this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
67
-            $this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
65
+            $this->getDBConfigIfSet('log_level', $this->getLogging()->debugLevel);
66
+            $this->getDBConfigIfSet('log_destination', $this->getLogging()->outputMode);
67
+            $this->getDBConfigIfSet('log_file', $this->getLogging()->outputFile);
68 68
         }
69 69
         
70
-        $tmpVal = -1; // Get boolean coded in database as 1/0
70
+        $tmpVal=-1; // Get boolean coded in database as 1/0
71 71
         $this->getDBConfigIfSet('use_SnmpTrapAddess', $tmpVal);
72
-        if ($tmpVal != -1) $this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
72
+        if ($tmpVal != -1) $this->useSnmpTrapAddess=($tmpVal == 1) ? TRUE : FALSE;
73 73
         
74 74
         $this->getDBConfigIfSet('SnmpTrapAddess_oid', $this->snmpTrapAddressOID); // Get oid then replace '.' with '\.' to use in regexp whrn reading traps
75
-        $this->snmpTrapAddressOID = preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
75
+        $this->snmpTrapAddressOID=preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
76 76
     }
77 77
         
78 78
     /** Set $variable to value if $element found in database config table
79 79
      * @param string $element
80 80
      * @param string $variable
81 81
      */
82
-    protected function getDBConfigIfSet($element,&$variable)
82
+    protected function getDBConfigIfSet($element, &$variable)
83 83
     {
84 84
         $value=$this->getDBConfig($element);
85 85
         if ($value != null) $variable=$value;
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
         $db_conn=$this->trapsDB->db_connect_trap();
96 96
         $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
97 97
         if (($ret_code=$db_conn->query($sql)) === false) {
98
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
98
+            $this->logging->log('No result in query : '.$sql, WARN, '');
99 99
             return null;
100 100
         }
101 101
         $value=$ret_code->fetch();
@@ -114,10 +114,10 @@  discard block
 block discarded – undo
114 114
     {
115 115
         
116 116
         $nodeStatus='';
117
-        $this->getOptionIfSet($trapConfig,'config','node', $nodeStatus);
117
+        $this->getOptionIfSet($trapConfig, 'config', 'node', $nodeStatus);
118 118
         if ($this->getTrapApi()->setStatus($nodeStatus) === FALSE)
119 119
         {
120
-            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
120
+            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER', WARN);
121 121
             $this->getTrapApi()->setStatusMaster();
122 122
         }
123 123
         else 
@@ -125,36 +125,36 @@  discard block
 block discarded – undo
125 125
             if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
126 126
             {
127 127
                 // Get options to connect to API
128
-                $IP = $port = $user =  $pass = null;
129
-                $this->getOptionIfSet($trapConfig,'config','masterIP', $IP, ERROR);
130
-                $this->getOptionIfSet($trapConfig,'config','masterPort', $port, ERROR);
131
-                $this->getOptionIfSet($trapConfig,'config','masterUser', $user, ERROR);
132
-                $this->getOptionIfSet($trapConfig,'config','masterPass', $pass, ERROR);
128
+                $IP=$port=$user=$pass=null;
129
+                $this->getOptionIfSet($trapConfig, 'config', 'masterIP', $IP, ERROR);
130
+                $this->getOptionIfSet($trapConfig, 'config', 'masterPort', $port, ERROR);
131
+                $this->getOptionIfSet($trapConfig, 'config', 'masterUser', $user, ERROR);
132
+                $this->getOptionIfSet($trapConfig, 'config', 'masterPass', $pass, ERROR);
133 133
                 $this->getTrapApi()->setParams($IP, $port, $user, $pass);
134 134
                 return;
135 135
             }
136 136
         }
137 137
         
138 138
         // Snmptranslate binary path
139
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
139
+        $this->getOptionIfSet($trapConfig, 'config', 'snmptranslate', $this->snmptranslate);
140 140
         
141 141
         // mibs path
142
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
142
+        $this->getOptionIfSet($trapConfig, 'config', 'snmptranslate_dirs', $this->snmptranslate_dirs);
143 143
         
144 144
         // icinga2cmd path
145
-        $this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
145
+        $this->getOptionIfSet($trapConfig, 'config', 'icingacmd', $this->icinga2cmd);
146 146
         
147 147
         // table prefix
148
-        $this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
148
+        $this->getOptionIfSet($trapConfig, 'config', 'database_prefix', $this->dbPrefix);
149 149
         
150 150
         // API options
151
-        if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
151
+        if ($this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_host', $this->apiHostname))
152 152
         {
153 153
             $this->apiUse=true;
154 154
             // Get API options or throw exception as not configured correctly
155
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort,ERROR);
156
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername,ERROR);
157
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword,ERROR);
155
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_port', $this->apiPort, ERROR);
156
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_user', $this->apiUsername, ERROR);
157
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_password', $this->apiPassword, ERROR);
158 158
         }
159 159
     }
160 160
     
@@ -165,43 +165,43 @@  discard block
 block discarded – undo
165 165
     protected function setupDatabase($trapConfig)
166 166
     {
167 167
         // Trap database
168
-        if (!array_key_exists('database',$trapConfig['config']))
168
+        if (!array_key_exists('database', $trapConfig['config']))
169 169
         {
170
-            $this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
170
+            $this->logging->log("No database in config file: ".$this->trapModuleConfig, ERROR, '');
171 171
             return;
172 172
         }
173 173
         $dbTrapName=$trapConfig['config']['database'];
174
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
174
+        $this->logging->log("Found database in config file: ".$dbTrapName, INFO);
175 175
         
176
-        if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
176
+        if (($dbConfig=parse_ini_file($this->icingaweb2Ressources, true)) === false)
177 177
         {
178
-            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
178
+            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources, ERROR, '');
179 179
             return;
180 180
         }
181
-        if (!array_key_exists($dbTrapName,$dbConfig))
181
+        if (!array_key_exists($dbTrapName, $dbConfig))
182 182
         {
183
-            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
183
+            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources, ERROR, '');
184 184
             return;
185 185
         }
186 186
         
187
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
187
+        $this->trapsDB=new Database($this->logging, $dbConfig[$dbTrapName], $this->dbPrefix);
188 188
         
189
-        $this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG );
189
+        $this->logging->log("API Use : ".print_r($this->apiUse, true), DEBUG);
190 190
         
191 191
         //TODO enable this again when API queries are all done :
192 192
         if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
193 193
         
194 194
         // IDO Database
195
-        if (!array_key_exists('IDOdatabase',$trapConfig['config']))
195
+        if (!array_key_exists('IDOdatabase', $trapConfig['config']))
196 196
         {
197
-            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
197
+            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig, ERROR, '');
198 198
         }
199 199
         $dbIdoName=$trapConfig['config']['IDOdatabase'];
200 200
         
201
-        $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
202
-        if (!array_key_exists($dbIdoName,$dbConfig))
201
+        $this->logging->log("Found IDO database in config file: ".$dbIdoName, INFO);
202
+        if (!array_key_exists($dbIdoName, $dbConfig))
203 203
         {
204
-            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
204
+            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources, ERROR, '');
205 205
             return;
206 206
         }
207 207
         
Please login to merge, or discard this patch.
Braces   +15 added lines, -8 removed lines patch added patch discarded remove patch
@@ -46,8 +46,7 @@  discard block
 block discarded – undo
46 46
             }
47 47
             $this->getLogging()->log($message,$log_level);
48 48
             return false;
49
-        }
50
-        else
49
+        } else
51 50
         {
52 51
             $option_var=$option_array[$option_category][$option_name];
53 52
             return true;
@@ -60,16 +59,20 @@  discard block
 block discarded – undo
60 59
     protected function getDatabaseOptions()
61 60
     {
62 61
         // Database options
63
-        if ($this->logSetup === false) // Only if logging was no setup in constructor
62
+        if ($this->logSetup === false) {
63
+        	// Only if logging was no setup in constructor
64 64
         {
65 65
             $this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
66
+        }
66 67
             $this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
67 68
             $this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
68 69
         }
69 70
         
70 71
         $tmpVal = -1; // Get boolean coded in database as 1/0
71 72
         $this->getDBConfigIfSet('use_SnmpTrapAddess', $tmpVal);
72
-        if ($tmpVal != -1) $this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
73
+        if ($tmpVal != -1) {
74
+        	$this->useSnmpTrapAddess = ($tmpVal == 1) ? TRUE : FALSE;
75
+        }
73 76
         
74 77
         $this->getDBConfigIfSet('SnmpTrapAddess_oid', $this->snmpTrapAddressOID); // Get oid then replace '.' with '\.' to use in regexp whrn reading traps
75 78
         $this->snmpTrapAddressOID = preg_replace('/\./', '\\.', $this->snmpTrapAddressOID);
@@ -82,7 +85,9 @@  discard block
 block discarded – undo
82 85
     protected function getDBConfigIfSet($element,&$variable)
83 86
     {
84 87
         $value=$this->getDBConfig($element);
85
-        if ($value != null) $variable=$value;
88
+        if ($value != null) {
89
+        	$variable=$value;
90
+        }
86 91
     }
87 92
     
88 93
     /**
@@ -119,8 +124,7 @@  discard block
 block discarded – undo
119 124
         {
120 125
             $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
121 126
             $this->getTrapApi()->setStatusMaster();
122
-        }
123
-        else 
127
+        } else 
124 128
         {
125 129
             if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
126 130
             {
@@ -189,7 +193,10 @@  discard block
 block discarded – undo
189 193
         $this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG );
190 194
         
191 195
         //TODO enable this again when API queries are all done :
192
-        if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
196
+        if ($this->apiUse === true) {
197
+        	return;
198
+        }
199
+        // In case of API use, no IDO is necessary
193 200
         
194 201
         // IDO Database
195 202
         if (!array_key_exists('IDOdatabase',$trapConfig['config']))
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Trap.php 3 patches
Indentation   +829 added lines, -829 removed lines patch added patch discarded remove patch
@@ -17,856 +17,856 @@  discard block
 block discarded – undo
17 17
  */
18 18
 class Trap
19 19
 {
20
-    use TrapConfig;
20
+	use TrapConfig;
21 21
     
22
-    // Configuration files and dirs
23
-    /** @var string Icinga etc path */
24
-    protected $icingaweb2Etc;
25
-    /** @var string $trapModuleConfig config.ini of module */
26
-    protected $trapModuleConfig;
27
-    /** @var string $icingaweb2Ressources resources.ini of icingaweb2 */
28
-    protected $icingaweb2Ressources;
29
-    // Options from config.ini (default values)
30
-    /** @var string $snmptranslate */
31
-    protected $snmptranslate='/usr/bin/snmptranslate';
32
-    /** @var string $snmptranslate_dirs */
33
-    protected $snmptranslate_dirs='/usr/share/icingaweb2/modules/trapdirector/mibs';
34
-    /** @var string $icinga2cmd */
35
-    protected $icinga2cmd='/var/run/icinga2/cmd/icinga2.cmd';
36
-    /** @var string $dbPrefix */
37
-    protected $dbPrefix='traps_';
22
+	// Configuration files and dirs
23
+	/** @var string Icinga etc path */
24
+	protected $icingaweb2Etc;
25
+	/** @var string $trapModuleConfig config.ini of module */
26
+	protected $trapModuleConfig;
27
+	/** @var string $icingaweb2Ressources resources.ini of icingaweb2 */
28
+	protected $icingaweb2Ressources;
29
+	// Options from config.ini (default values)
30
+	/** @var string $snmptranslate */
31
+	protected $snmptranslate='/usr/bin/snmptranslate';
32
+	/** @var string $snmptranslate_dirs */
33
+	protected $snmptranslate_dirs='/usr/share/icingaweb2/modules/trapdirector/mibs';
34
+	/** @var string $icinga2cmd */
35
+	protected $icinga2cmd='/var/run/icinga2/cmd/icinga2.cmd';
36
+	/** @var string $dbPrefix */
37
+	protected $dbPrefix='traps_';
38 38
     
39
-    // API
40
-    /** @var boolean $apiUse */
41
-    protected $apiUse=false;
42
-    /** @var Icinga2API $icinga2api */
43
-    protected $icinga2api=null;
44
-    /** @var string $apiHostname */
45
-    protected $apiHostname='';
46
-    /** @var integer $apiPort */
47
-    protected $apiPort=0;
48
-    /** @var string $apiUsername */
49
-    protected $apiUsername='';
50
-    /** @var string $apiPassword */
51
-    protected $apiPassword='';
39
+	// API
40
+	/** @var boolean $apiUse */
41
+	protected $apiUse=false;
42
+	/** @var Icinga2API $icinga2api */
43
+	protected $icinga2api=null;
44
+	/** @var string $apiHostname */
45
+	protected $apiHostname='';
46
+	/** @var integer $apiPort */
47
+	protected $apiPort=0;
48
+	/** @var string $apiUsername */
49
+	protected $apiUsername='';
50
+	/** @var string $apiPassword */
51
+	protected $apiPassword='';
52 52
     
53
-    // Logs
54
-    /** @var Logging Logging class. */
55
-    public $logging;    //< Logging class.
56
-    /** @var bool true if log was setup in constructor */
57
-    protected $logSetup;   //< bool true if log was setup in constructor
53
+	// Logs
54
+	/** @var Logging Logging class. */
55
+	public $logging;    //< Logging class.
56
+	/** @var bool true if log was setup in constructor */
57
+	protected $logSetup;   //< bool true if log was setup in constructor
58 58
     
59
-    // Databases
60
-    /** @var Database $trapsDB  Database class*/
61
-    public $trapsDB = null;
59
+	// Databases
60
+	/** @var Database $trapsDB  Database class*/
61
+	public $trapsDB = null;
62 62
     
63
-    // Trap received data
64
-    protected $receivingHost;
65
-    /** @var array	Main trap data (oid, source...) */
66
-    public $trapData=array();
67
-    /** @var array $trapDataExt Additional trap data objects (oid/value).*/
68
-    public $trapDataExt=array(); 
69
-    /** @var int $trapId trap_id after sql insert*/
70
-    public $trapId=null;
71
-    /** @var string $trapAction trap action for final write*/
72
-    public $trapAction=null;
73
-    /** @var boolean $trapToDb log trap to DB */
74
-    protected $trapToDb=true;
63
+	// Trap received data
64
+	protected $receivingHost;
65
+	/** @var array	Main trap data (oid, source...) */
66
+	public $trapData=array();
67
+	/** @var array $trapDataExt Additional trap data objects (oid/value).*/
68
+	public $trapDataExt=array(); 
69
+	/** @var int $trapId trap_id after sql insert*/
70
+	public $trapId=null;
71
+	/** @var string $trapAction trap action for final write*/
72
+	public $trapAction=null;
73
+	/** @var boolean $trapToDb log trap to DB */
74
+	protected $trapToDb=true;
75 75
     
76
-    /** @var Mib mib class */
77
-    public $mibClass = null;
76
+	/** @var Mib mib class */
77
+	public $mibClass = null;
78 78
     
79
-    /** @var Rule rule class */
80
-    public $ruleClass = null;
79
+	/** @var Rule rule class */
80
+	public $ruleClass = null;
81 81
     
82
-    /** @var Plugins plugins manager **/
83
-    public $pluginClass = null;
82
+	/** @var Plugins plugins manager **/
83
+	public $pluginClass = null;
84 84
     
85
-    /** @var TrapApi $trapApiClass */
86
-    public $trapApiClass = null;
85
+	/** @var TrapApi $trapApiClass */
86
+	public $trapApiClass = null;
87 87
     
88
-    function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
89
-    {
90
-        // Paths of ini files
91
-        $this->icingaweb2Etc=$etcDir;
92
-        $this->trapModuleConfig=$this->icingaweb2Etc."/modules/trapdirector/config.ini";
93
-        $this->icingaweb2Ressources=$this->icingaweb2Etc."/resources.ini";
88
+	function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
89
+	{
90
+		// Paths of ini files
91
+		$this->icingaweb2Etc=$etcDir;
92
+		$this->trapModuleConfig=$this->icingaweb2Etc."/modules/trapdirector/config.ini";
93
+		$this->icingaweb2Ressources=$this->icingaweb2Etc."/resources.ini";
94 94
 
95
-        // Setup logging
96
-        $this->logging = new Logging();
97
-        if ($baseLogLevel != null)
98
-        {
99
-            $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
100
-            $this->logSetup=true;
101
-        }
102
-        else
103
-        {
104
-            $this->logSetup=false;
105
-        }
106
-        $this->logging->log('Loggin started', INFO);
107
-        
108
-        
109
-        // Create distributed API object
110
-        
111
-        $this->trapApiClass = new TrapApi($this->logging);
112
-        
113
-        // Get options from ini files
114
-        if (! is_file($this->trapModuleConfig))
115
-        {
116
-            throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
117
-        }
118
-        $trapConfig=parse_ini_file($this->trapModuleConfig,true);
119
-        if ($trapConfig == false)
120
-        {
121
-            $this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
122
-            throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
123
-        }
124
-        $this->getMainOptions($trapConfig); // Get main options from ini file
95
+		// Setup logging
96
+		$this->logging = new Logging();
97
+		if ($baseLogLevel != null)
98
+		{
99
+			$this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
100
+			$this->logSetup=true;
101
+		}
102
+		else
103
+		{
104
+			$this->logSetup=false;
105
+		}
106
+		$this->logging->log('Loggin started', INFO);
107
+        
108
+        
109
+		// Create distributed API object
110
+        
111
+		$this->trapApiClass = new TrapApi($this->logging);
112
+        
113
+		// Get options from ini files
114
+		if (! is_file($this->trapModuleConfig))
115
+		{
116
+			throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
117
+		}
118
+		$trapConfig=parse_ini_file($this->trapModuleConfig,true);
119
+		if ($trapConfig == false)
120
+		{
121
+			$this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
122
+			throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
123
+		}
124
+		$this->getMainOptions($trapConfig); // Get main options from ini file
125 125
         
126 126
 	try {
127
-        // Setup database class & get options
128
-        $this->setupDatabase($trapConfig);
127
+		// Setup database class & get options
128
+		$this->setupDatabase($trapConfig);
129 129
         
130
-        $this->getDatabaseOptions(); // Get options in database
130
+		$this->getDatabaseOptions(); // Get options in database
131 131
         
132
-        // Setup API
133
-        if ($this->apiUse === true) $this->getAPI(); // Setup API
132
+		// Setup API
133
+		if ($this->apiUse === true) $this->getAPI(); // Setup API
134 134
         
135
-        // Setup MIB
136
-        $this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
135
+		// Setup MIB
136
+		$this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
137 137
         
138
-        // Setup Rule
139
-        $this->ruleClass = new Rule($this); //< Create Rule class
138
+		// Setup Rule
139
+		$this->ruleClass = new Rule($this); //< Create Rule class
140 140
         
141
-        $this->trapData=array(  // TODO : put this in a reset function (DAEMON_MODE)
142
-            'source_ip'	=> 'unknown',
143
-            'source_port'	=> 'unknown',
144
-            'destination_ip'	=> 'unknown',
145
-            'destination_port'	=> 'unknown',
146
-            'trap_oid'	=> 'unknown'
147
-        );
141
+		$this->trapData=array(  // TODO : put this in a reset function (DAEMON_MODE)
142
+			'source_ip'	=> 'unknown',
143
+			'source_port'	=> 'unknown',
144
+			'destination_ip'	=> 'unknown',
145
+			'destination_port'	=> 'unknown',
146
+			'trap_oid'	=> 'unknown'
147
+		);
148 148
         
149
-        // Setup Plugins
150
-        //Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
151
-        $this->pluginClass = new Plugins($this);
149
+		// Setup Plugins
150
+		//Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
151
+		$this->pluginClass = new Plugins($this);
152 152
 	}catch (Exception $e){ return; }
153 153
             
154
-    }
154
+	}
155 155
 
156
-    /** @return \Trapdirector\Logging   */
157
-    public function getLogging()
158
-    {
159
-        return $this->logging;
160
-    }
156
+	/** @return \Trapdirector\Logging   */
157
+	public function getLogging()
158
+	{
159
+		return $this->logging;
160
+	}
161 161
 
162
-    /** @return \Trapdirector\TrapApi   */
163
-    public function getTrapApi()
164
-    {
165
-        return $this->trapApiClass;
166
-    }
162
+	/** @return \Trapdirector\TrapApi   */
163
+	public function getTrapApi()
164
+	{
165
+		return $this->trapApiClass;
166
+	}
167 167
     
168
-    /** @return \Trapdirector\Database */
169
-    public function getTrapsDB()
170
-    {
171
-        return $this->trapsDB;
172
-    }
168
+	/** @return \Trapdirector\Database */
169
+	public function getTrapsDB()
170
+	{
171
+		return $this->trapsDB;
172
+	}
173 173
     
174
-    /** OBSOLETE Send log. Throws exception on critical error
175
-     *	@param	string $message Message to log
176
-     *	@param	int $level 1=critical 2=warning 3=trace 4=debug
177
-     *	@param  string $destination file/syslog/display
178
-     *	@return void
179
-     **/
180
-    public function trapLog( $message, $level, $destination ='') // OBSOLETE
181
-    {
182
-        // TODO : replace ref with $this->logging->log
183
-        $this->logging->log($message, $level, $destination);
184
-    }
174
+	/** OBSOLETE Send log. Throws exception on critical error
175
+	 *	@param	string $message Message to log
176
+	 *	@param	int $level 1=critical 2=warning 3=trace 4=debug
177
+	 *	@param  string $destination file/syslog/display
178
+	 *	@return void
179
+	 **/
180
+	public function trapLog( $message, $level, $destination ='') // OBSOLETE
181
+	{
182
+		// TODO : replace ref with $this->logging->log
183
+		$this->logging->log($message, $level, $destination);
184
+	}
185 185
     
186
-    public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
187
-    {
188
-        $this->logging->setLogging($debugLvl, $outputType,$outputOption);
189
-    }
186
+	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
187
+	{
188
+		$this->logging->setLogging($debugLvl, $outputType,$outputOption);
189
+	}
190 190
     
191
-    /**
192
-     * Returns or create new IcingaAPI object
193
-     * @return \Icinga\Module\Trapdirector\Icinga2API
194
-     */
195
-    protected function getAPI()
196
-    {
197
-        if ($this->icinga2api == null)
198
-        {
199
-            $this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
200
-        }
201
-        return $this->icinga2api;
202
-    }
191
+	/**
192
+	 * Returns or create new IcingaAPI object
193
+	 * @return \Icinga\Module\Trapdirector\Icinga2API
194
+	 */
195
+	protected function getAPI()
196
+	{
197
+		if ($this->icinga2api == null)
198
+		{
199
+			$this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
200
+		}
201
+		return $this->icinga2api;
202
+	}
203 203
     
204 204
     
205
-    /**
206
-     * read data from stream
207
-     *	@param $stream string input stream, defaults to "php://stdin"
208
-     *	@return mixed array trap data or exception with error
209
-     */
210
-    public function read_trap($stream='php://stdin')
211
-    {
212
-        //Read data from snmptrapd from stdin
213
-        $input_stream=fopen($stream, 'r');
214
-        
215
-        if ($input_stream === false)
216
-        {
217
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
218
-            $this->logging->log("Error reading stdin !",ERROR,'');
219
-            return null; // note : exception thrown by logging
220
-        }
221
-        
222
-        // line 1 : host
223
-        $this->receivingHost=chop(fgets($input_stream));
224
-        if ($this->receivingHost === false)
225
-        {
226
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
227
-            $this->logging->log("Error reading Host !",ERROR,'');
228
-        }
229
-        // line 2 IP:port=>IP:port
230
-        $IP=chop(fgets($input_stream));
231
-        if ($IP === false)
232
-        {
233
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
234
-            $this->logging->log("Error reading IP !",ERROR,'');
235
-        }
236
-        $matches=array();
237
-        $ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
238
-        if ($ret_code===0 || $ret_code===false)
239
-        {
240
-            $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
241
-            $this->logging->log('Error parsing IP : '.$IP,ERROR,'');
242
-        }
243
-        else
244
-        {
245
-            $this->trapData['source_ip']=$matches[1];
246
-            $this->trapData['destination_ip']=$matches[3];
247
-            $this->trapData['source_port']=$matches[2];
248
-            $this->trapData['destination_port']=$matches[4];
249
-        }
250
-        
251
-        while (($vars=fgets($input_stream)) !==false)
252
-        {
253
-            $vars=chop($vars);
254
-            $ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
255
-            if ($ret_code===0 || $ret_code===false)
256
-            {
257
-                $this->logging->log('No match on trap data : '.$vars,WARN,'');
258
-                continue;
259
-            }
260
-            if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
261
-            {
262
-                $this->trapData['trap_oid']=$matches[2];
263
-                continue;
264
-            }
265
-            if ( $this->useSnmpTrapAddess === TRUE &&  preg_match('/'.$this->snmpTrapAddressOID.'/', $matches[1]) == 1)
266
-            {
267
-                $this->logging->log('Found relayed trap from ' . $matches[2] . ' relayed by ' .$this->trapData['source_ip'],DEBUG);
268
-                if (preg_match('/^[0-9\.]+$/',$matches[2]) == 0 && preg_match('/^[0-9a-fA-F:]+$/',$matches[2]) == 0)
269
-                {
270
-                    $this->logging->log('Value of SnmpTrapAddess ('.$this->snmpTrapAddressOID.') is not IP : ' .$matches[2],WARN,'');
271
-                    continue;
272
-                }
273
-                $this->trapData['source_ip'] = $matches[2];
274
-                continue;
275
-            }
276
-            $object= new stdClass;
277
-            $object->oid =$matches[1];
278
-            $object->value = $matches[2];
279
-            array_push($this->trapDataExt,$object);
280
-        }
281
-        
282
-        if ($this->trapData['trap_oid']=='unknown')
283
-        {
284
-            $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trapData['source_ip']);
285
-            $this->logging->log('no trap oid found',ERROR,'');
286
-        }
287
-        
288
-        // Translate oids.
289
-        
290
-        $retArray=$this->translateOID($this->trapData['trap_oid']);
291
-        if ($retArray != null)
292
-        {
293
-            $this->trapData['trap_name']=$retArray['trap_name'];
294
-            $this->trapData['trap_name_mib']=$retArray['trap_name_mib'];
295
-        }
296
-        foreach ($this->trapDataExt as $key => $val)
297
-        {
298
-            $retArray=$this->translateOID($val->oid);
299
-            if ($retArray != null)
300
-            {
301
-                $this->trapDataExt[$key]->oid_name=$retArray['trap_name'];
302
-                $this->trapDataExt[$key]->oid_name_mib=$retArray['trap_name_mib'];
303
-            }
304
-        }
305
-        
306
-        
307
-        $this->trapData['status']= 'waiting';
308
-        
309
-        return $this->trapData;
310
-    }
205
+	/**
206
+	 * read data from stream
207
+	 *	@param $stream string input stream, defaults to "php://stdin"
208
+	 *	@return mixed array trap data or exception with error
209
+	 */
210
+	public function read_trap($stream='php://stdin')
211
+	{
212
+		//Read data from snmptrapd from stdin
213
+		$input_stream=fopen($stream, 'r');
214
+        
215
+		if ($input_stream === false)
216
+		{
217
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
218
+			$this->logging->log("Error reading stdin !",ERROR,'');
219
+			return null; // note : exception thrown by logging
220
+		}
221
+        
222
+		// line 1 : host
223
+		$this->receivingHost=chop(fgets($input_stream));
224
+		if ($this->receivingHost === false)
225
+		{
226
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
227
+			$this->logging->log("Error reading Host !",ERROR,'');
228
+		}
229
+		// line 2 IP:port=>IP:port
230
+		$IP=chop(fgets($input_stream));
231
+		if ($IP === false)
232
+		{
233
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
234
+			$this->logging->log("Error reading IP !",ERROR,'');
235
+		}
236
+		$matches=array();
237
+		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
238
+		if ($ret_code===0 || $ret_code===false)
239
+		{
240
+			$this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
241
+			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
242
+		}
243
+		else
244
+		{
245
+			$this->trapData['source_ip']=$matches[1];
246
+			$this->trapData['destination_ip']=$matches[3];
247
+			$this->trapData['source_port']=$matches[2];
248
+			$this->trapData['destination_port']=$matches[4];
249
+		}
250
+        
251
+		while (($vars=fgets($input_stream)) !==false)
252
+		{
253
+			$vars=chop($vars);
254
+			$ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
255
+			if ($ret_code===0 || $ret_code===false)
256
+			{
257
+				$this->logging->log('No match on trap data : '.$vars,WARN,'');
258
+				continue;
259
+			}
260
+			if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
261
+			{
262
+				$this->trapData['trap_oid']=$matches[2];
263
+				continue;
264
+			}
265
+			if ( $this->useSnmpTrapAddess === TRUE &&  preg_match('/'.$this->snmpTrapAddressOID.'/', $matches[1]) == 1)
266
+			{
267
+				$this->logging->log('Found relayed trap from ' . $matches[2] . ' relayed by ' .$this->trapData['source_ip'],DEBUG);
268
+				if (preg_match('/^[0-9\.]+$/',$matches[2]) == 0 && preg_match('/^[0-9a-fA-F:]+$/',$matches[2]) == 0)
269
+				{
270
+					$this->logging->log('Value of SnmpTrapAddess ('.$this->snmpTrapAddressOID.') is not IP : ' .$matches[2],WARN,'');
271
+					continue;
272
+				}
273
+				$this->trapData['source_ip'] = $matches[2];
274
+				continue;
275
+			}
276
+			$object= new stdClass;
277
+			$object->oid =$matches[1];
278
+			$object->value = $matches[2];
279
+			array_push($this->trapDataExt,$object);
280
+		}
281
+        
282
+		if ($this->trapData['trap_oid']=='unknown')
283
+		{
284
+			$this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trapData['source_ip']);
285
+			$this->logging->log('no trap oid found',ERROR,'');
286
+		}
287
+        
288
+		// Translate oids.
289
+        
290
+		$retArray=$this->translateOID($this->trapData['trap_oid']);
291
+		if ($retArray != null)
292
+		{
293
+			$this->trapData['trap_name']=$retArray['trap_name'];
294
+			$this->trapData['trap_name_mib']=$retArray['trap_name_mib'];
295
+		}
296
+		foreach ($this->trapDataExt as $key => $val)
297
+		{
298
+			$retArray=$this->translateOID($val->oid);
299
+			if ($retArray != null)
300
+			{
301
+				$this->trapDataExt[$key]->oid_name=$retArray['trap_name'];
302
+				$this->trapDataExt[$key]->oid_name_mib=$retArray['trap_name_mib'];
303
+			}
304
+		}
305
+        
306
+        
307
+		$this->trapData['status']= 'waiting';
308
+        
309
+		return $this->trapData;
310
+	}
311 311
     
312
-    /**
313
-     * Translate oid into array(MIB,Name)
314
-     * @param $oid string oid to translate
315
-     * @return mixed : null if not found or array(MIB,Name)
316
-     */
317
-    public function translateOID($oid)
318
-    {
319
-        // try from database
320
-        $db_conn=$this->trapsDB->db_connect_trap();
321
-        
322
-        $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
323
-        $this->logging->log('SQL query : '.$sql,DEBUG );
324
-        if (($ret_code=$db_conn->query($sql)) === false) {
325
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
326
-        }
327
-        else {
328
-            if (($name=$ret_code->fetch()) !== false)
329
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
330
-        }
331
-        
332
-        // Also check if it is an instance of OID
333
-        $oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
334
-        
335
-        $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
336
-        $this->logging->log('SQL query : '.$sql,DEBUG );
337
-        if (($ret_code=$db_conn->query($sql)) === false) {
338
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
339
-        }
340
-        else {
341
-            if (($name=$ret_code->fetch()) !== false)
342
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
343
-        }
344
-        
345
-        // Try to get oid name from snmptranslate
346
-        $translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
347
-            ' '.$oid);
348
-        $matches=array();
349
-        $ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
350
-        if ($ret_code===0 || $ret_code === false) {
351
-            return NULL;
352
-        } else {
353
-            $this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
354
-            return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
355
-        }
356
-    }
312
+	/**
313
+	 * Translate oid into array(MIB,Name)
314
+	 * @param $oid string oid to translate
315
+	 * @return mixed : null if not found or array(MIB,Name)
316
+	 */
317
+	public function translateOID($oid)
318
+	{
319
+		// try from database
320
+		$db_conn=$this->trapsDB->db_connect_trap();
321
+        
322
+		$sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
323
+		$this->logging->log('SQL query : '.$sql,DEBUG );
324
+		if (($ret_code=$db_conn->query($sql)) === false) {
325
+			$this->logging->log('No result in query : ' . $sql,ERROR,'');
326
+		}
327
+		else {
328
+			if (($name=$ret_code->fetch()) !== false)
329
+				return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
330
+		}
331
+        
332
+		// Also check if it is an instance of OID
333
+		$oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
334
+        
335
+		$sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
336
+		$this->logging->log('SQL query : '.$sql,DEBUG );
337
+		if (($ret_code=$db_conn->query($sql)) === false) {
338
+			$this->logging->log('No result in query : ' . $sql,ERROR,'');
339
+		}
340
+		else {
341
+			if (($name=$ret_code->fetch()) !== false)
342
+				return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
343
+		}
344
+        
345
+		// Try to get oid name from snmptranslate
346
+		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
347
+			' '.$oid);
348
+		$matches=array();
349
+		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
350
+		if ($ret_code===0 || $ret_code === false) {
351
+			return NULL;
352
+		} else {
353
+			$this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
354
+			return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
355
+		}
356
+	}
357 357
     
358
-    /**
359
-     * Erase old trap records
360
-     *	@param integer $days : erase traps when more than $days old
361
-     *	@return integer : number of lines deleted
362
-     **/
363
-    public function eraseOldTraps($days=0)
364
-    {
365
-        if ($days==0)
366
-        {
367
-            if (($days=$this->getDBConfig('db_remove_days')) == null)
368
-            {
369
-                $this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
370
-                return;
371
-            }
372
-        }
373
-        $db_conn=$this->trapsDB->db_connect_trap();
374
-        $daysago = strtotime("-".$days." day");
375
-        $sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
376
-        if ($db_conn->query($sql) === false) {
377
-            $this->logging->log('Error erasing traps : '.$sql,ERROR,'');
378
-        }
379
-        $this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
380
-    }
358
+	/**
359
+	 * Erase old trap records
360
+	 *	@param integer $days : erase traps when more than $days old
361
+	 *	@return integer : number of lines deleted
362
+	 **/
363
+	public function eraseOldTraps($days=0)
364
+	{
365
+		if ($days==0)
366
+		{
367
+			if (($days=$this->getDBConfig('db_remove_days')) == null)
368
+			{
369
+				$this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
370
+				return;
371
+			}
372
+		}
373
+		$db_conn=$this->trapsDB->db_connect_trap();
374
+		$daysago = strtotime("-".$days." day");
375
+		$sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
376
+		if ($db_conn->query($sql) === false) {
377
+			$this->logging->log('Error erasing traps : '.$sql,ERROR,'');
378
+		}
379
+		$this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
380
+	}
381 381
     
382
-    /** Write error to received trap database
383
-     */
384
-    public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
385
-    {
386
-        
387
-        $db_conn=$this->trapsDB->db_connect_trap();
388
-        
389
-        // add date time
390
-        $insert_col ='date_received,status';
391
-        $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
392
-        
393
-        if ($sourceIP !=null)
394
-        {
395
-            $insert_col .=',source_ip';
396
-            $insert_val .=",'". $sourceIP ."'";
397
-        }
398
-        if ($trapoid !=null)
399
-        {
400
-            $insert_col .=',trap_oid';
401
-            $insert_val .=",'". $trapoid ."'";
402
-        }
403
-        $insert_col .=',status_detail';
404
-        $insert_val .=",'". $message ."'";
405
-        
406
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
407
-        
408
-        switch ($this->trapsDB->trapDBType)
409
-        {
410
-            case 'pgsql':
411
-                $sql .= ' RETURNING id;';
412
-                $this->logging->log('sql : '.$sql,INFO);
413
-                if (($ret_code=$db_conn->query($sql)) === false) {
414
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
415
-                }
416
-                $this->logging->log('SQL insertion OK',INFO );
417
-                // Get last id to insert oid/values in secondary table
418
-                if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
382
+	/** Write error to received trap database
383
+	 */
384
+	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
385
+	{
386
+        
387
+		$db_conn=$this->trapsDB->db_connect_trap();
388
+        
389
+		// add date time
390
+		$insert_col ='date_received,status';
391
+		$insert_val = "'" . date("Y-m-d H:i:s")."','error'";
392
+        
393
+		if ($sourceIP !=null)
394
+		{
395
+			$insert_col .=',source_ip';
396
+			$insert_val .=",'". $sourceIP ."'";
397
+		}
398
+		if ($trapoid !=null)
399
+		{
400
+			$insert_col .=',trap_oid';
401
+			$insert_val .=",'". $trapoid ."'";
402
+		}
403
+		$insert_col .=',status_detail';
404
+		$insert_val .=",'". $message ."'";
405
+        
406
+		$sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
407
+        
408
+		switch ($this->trapsDB->trapDBType)
409
+		{
410
+			case 'pgsql':
411
+				$sql .= ' RETURNING id;';
412
+				$this->logging->log('sql : '.$sql,INFO);
413
+				if (($ret_code=$db_conn->query($sql)) === false) {
414
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
415
+				}
416
+				$this->logging->log('SQL insertion OK',INFO );
417
+				// Get last id to insert oid/values in secondary table
418
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
419 419
                     
420
-                    $this->logging->log('Erreur recuperation id',1,'');
421
-                }
422
-                if (! isset($inserted_id_ret['id'])) {
423
-                    $this->logging->log('Error getting id',1,'');
424
-                }
425
-                $this->trapId=$inserted_id_ret['id'];
426
-                break;
427
-            case 'mysql':
428
-                $sql .= ';';
429
-                $this->logging->log('sql : '.$sql,INFO );
430
-                if ($db_conn->query($sql) === false) {
431
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
432
-                }
433
-                $this->logging->log('SQL insertion OK',INFO );
434
-                // Get last id to insert oid/values in secondary table
435
-                $sql='SELECT LAST_INSERT_ID();';
436
-                if (($ret_code=$db_conn->query($sql)) === false) {
437
-                    $this->logging->log('Erreur recuperation id',1,'');
438
-                }
420
+					$this->logging->log('Erreur recuperation id',1,'');
421
+				}
422
+				if (! isset($inserted_id_ret['id'])) {
423
+					$this->logging->log('Error getting id',1,'');
424
+				}
425
+				$this->trapId=$inserted_id_ret['id'];
426
+				break;
427
+			case 'mysql':
428
+				$sql .= ';';
429
+				$this->logging->log('sql : '.$sql,INFO );
430
+				if ($db_conn->query($sql) === false) {
431
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
432
+				}
433
+				$this->logging->log('SQL insertion OK',INFO );
434
+				// Get last id to insert oid/values in secondary table
435
+				$sql='SELECT LAST_INSERT_ID();';
436
+				if (($ret_code=$db_conn->query($sql)) === false) {
437
+					$this->logging->log('Erreur recuperation id',1,'');
438
+				}
439 439
                 
440
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
441
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
442
-                $this->trapId=$inserted_id;
443
-                break;
444
-            default:
445
-                $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
446
-        }
447
-        
448
-        $this->logging->log('id found: '. $this->trapId,INFO );
449
-    }
440
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
441
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
442
+				$this->trapId=$inserted_id;
443
+				break;
444
+			default:
445
+				$this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
446
+		}
447
+        
448
+		$this->logging->log('id found: '. $this->trapId,INFO );
449
+	}
450 450
     
451
-    /** Write trap data to trap database
452
-     */
453
-    public function writeTrapToDB()
454
-    {
455
-        
456
-        // If action is ignore -> don't send t DB
457
-        if ($this->trapToDb === false) return;
458
-        
459
-        
460
-        $db_conn=$this->trapsDB->db_connect_trap();
461
-        
462
-        $insert_col='';
463
-        $insert_val='';
464
-        // add date time
465
-        $this->trapData['date_received'] = date("Y-m-d H:i:s");
466
-        
467
-        $firstcol=1;
468
-        foreach ($this->trapData as $col => $val)
469
-        {
470
-            if ($firstcol==0)
471
-            {
472
-                $insert_col .=',';
473
-                $insert_val .=',';
474
-            }
475
-            $insert_col .= $col ;
476
-            $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
477
-            $firstcol=0;
478
-        }
479
-        
480
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
481
-        switch ($this->trapsDB->trapDBType)
482
-        {
483
-            case 'pgsql':
484
-                $sql .= ' RETURNING id;';
485
-                $this->logging->log('sql : '.$sql,INFO );
486
-                if (($ret_code=$db_conn->query($sql)) === false) {
487
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
488
-                }
489
-                $this->logging->log('SQL insertion OK',INFO );
490
-                // Get last id to insert oid/values in secondary table
491
-                if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
451
+	/** Write trap data to trap database
452
+	 */
453
+	public function writeTrapToDB()
454
+	{
455
+        
456
+		// If action is ignore -> don't send t DB
457
+		if ($this->trapToDb === false) return;
458
+        
459
+        
460
+		$db_conn=$this->trapsDB->db_connect_trap();
461
+        
462
+		$insert_col='';
463
+		$insert_val='';
464
+		// add date time
465
+		$this->trapData['date_received'] = date("Y-m-d H:i:s");
466
+        
467
+		$firstcol=1;
468
+		foreach ($this->trapData as $col => $val)
469
+		{
470
+			if ($firstcol==0)
471
+			{
472
+				$insert_col .=',';
473
+				$insert_val .=',';
474
+			}
475
+			$insert_col .= $col ;
476
+			$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
477
+			$firstcol=0;
478
+		}
479
+        
480
+		$sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
481
+		switch ($this->trapsDB->trapDBType)
482
+		{
483
+			case 'pgsql':
484
+				$sql .= ' RETURNING id;';
485
+				$this->logging->log('sql : '.$sql,INFO );
486
+				if (($ret_code=$db_conn->query($sql)) === false) {
487
+					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
488
+				}
489
+				$this->logging->log('SQL insertion OK',INFO );
490
+				// Get last id to insert oid/values in secondary table
491
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
492 492
                     
493
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
494
-                }
495
-                if (! isset($inserted_id_ret['id'])) {
496
-                    $this->logging->log('Error getting id',ERROR,'');
497
-                }
498
-                $this->trapId=$inserted_id_ret['id'];
499
-                break;
500
-            case 'mysql':
501
-                $sql .= ';';
502
-                $this->logging->log('sql : '.$sql,INFO );
503
-                if ($db_conn->query($sql) === false) {
504
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
505
-                }
506
-                $this->logging->log('SQL insertion OK',INFO );
507
-                // Get last id to insert oid/values in secondary table
508
-                $sql='SELECT LAST_INSERT_ID();';
509
-                if (($ret_code=$db_conn->query($sql)) === false) {
510
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
511
-                }
493
+					$this->logging->log('Erreur recuperation id',ERROR,'');
494
+				}
495
+				if (! isset($inserted_id_ret['id'])) {
496
+					$this->logging->log('Error getting id',ERROR,'');
497
+				}
498
+				$this->trapId=$inserted_id_ret['id'];
499
+				break;
500
+			case 'mysql':
501
+				$sql .= ';';
502
+				$this->logging->log('sql : '.$sql,INFO );
503
+				if ($db_conn->query($sql) === false) {
504
+					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
505
+				}
506
+				$this->logging->log('SQL insertion OK',INFO );
507
+				// Get last id to insert oid/values in secondary table
508
+				$sql='SELECT LAST_INSERT_ID();';
509
+				if (($ret_code=$db_conn->query($sql)) === false) {
510
+					$this->logging->log('Erreur recuperation id',ERROR,'');
511
+				}
512 512
                 
513
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
514
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
515
-                $this->trapId=$inserted_id;
516
-                break;
517
-            default:
518
-                $this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
519
-        }
520
-        $this->logging->log('id found: '.$this->trapId,INFO );
521
-        
522
-        // Fill trap extended data table
523
-        foreach ($this->trapDataExt as $value) {
524
-            // TODO : detect if trap value is encoded and decode it to UTF-8 for database
525
-            $firstcol=1;
526
-            $value->trap_id = $this->trapId;
527
-            $insert_col='';
528
-            $insert_val='';
529
-            foreach ($value as $col => $val)
530
-            {
531
-                if ($firstcol==0)
532
-                {
533
-                    $insert_col .=',';
534
-                    $insert_val .=',';
535
-                }
536
-                $insert_col .= $col;
537
-                $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
538
-                $firstcol=0;
539
-            }
513
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
514
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
515
+				$this->trapId=$inserted_id;
516
+				break;
517
+			default:
518
+				$this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
519
+		}
520
+		$this->logging->log('id found: '.$this->trapId,INFO );
521
+        
522
+		// Fill trap extended data table
523
+		foreach ($this->trapDataExt as $value) {
524
+			// TODO : detect if trap value is encoded and decode it to UTF-8 for database
525
+			$firstcol=1;
526
+			$value->trap_id = $this->trapId;
527
+			$insert_col='';
528
+			$insert_val='';
529
+			foreach ($value as $col => $val)
530
+			{
531
+				if ($firstcol==0)
532
+				{
533
+					$insert_col .=',';
534
+					$insert_val .=',';
535
+				}
536
+				$insert_col .= $col;
537
+				$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
538
+				$firstcol=0;
539
+			}
540 540
             
541
-            $sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
541
+			$sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
542 542
             
543
-            if ($db_conn->query($sql) === false) {
544
-                $this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
545
-            }
546
-        }
547
-    }
543
+			if ($db_conn->query($sql) === false) {
544
+				$this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
545
+			}
546
+		}
547
+	}
548 548
     
549
-    /** Get rules from rule database with ip and oid
550
-     *	@param $ip string ipv4 or ipv6
551
-     *	@param $oid string oid in numeric
552
-     *	@return mixed|boolean : PDO object or false
553
-     */
554
-    protected function getRules($ip,$oid)
555
-    {
556
-        $db_conn=$this->trapsDB->db_connect_trap();
557
-        // fetch rules based on IP in rule and OID
558
-        $sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
559
-        $this->logging->log('SQL query : '.$sql,DEBUG );
560
-        if (($ret_code=$db_conn->query($sql)) === false) {
561
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
562
-            return false;
563
-        }
564
-        $rules_all=$ret_code->fetchAll();
565
-        //echo "rule all :\n";print_r($rules_all);echo "\n";
566
-        $rules_ret=array();
567
-        $rule_ret_key=0;
568
-        foreach ($rules_all as $key => $rule)
569
-        {
570
-            if ($rule['ip4']==$ip || $rule['ip6']==$ip)
571
-            {
572
-                $rules_ret[$rule_ret_key]=$rules_all[$key];
573
-                //TODO : get host name by API (and check if correct in rule).
574
-                $rule_ret_key++;
575
-                continue;
576
-            }
549
+	/** Get rules from rule database with ip and oid
550
+	 *	@param $ip string ipv4 or ipv6
551
+	 *	@param $oid string oid in numeric
552
+	 *	@return mixed|boolean : PDO object or false
553
+	 */
554
+	protected function getRules($ip,$oid)
555
+	{
556
+		$db_conn=$this->trapsDB->db_connect_trap();
557
+		// fetch rules based on IP in rule and OID
558
+		$sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
559
+		$this->logging->log('SQL query : '.$sql,DEBUG );
560
+		if (($ret_code=$db_conn->query($sql)) === false) {
561
+			$this->logging->log('No result in query : ' . $sql,WARN,'');
562
+			return false;
563
+		}
564
+		$rules_all=$ret_code->fetchAll();
565
+		//echo "rule all :\n";print_r($rules_all);echo "\n";
566
+		$rules_ret=array();
567
+		$rule_ret_key=0;
568
+		foreach ($rules_all as $key => $rule)
569
+		{
570
+			if ($rule['ip4']==$ip || $rule['ip6']==$ip)
571
+			{
572
+				$rules_ret[$rule_ret_key]=$rules_all[$key];
573
+				//TODO : get host name by API (and check if correct in rule).
574
+				$rule_ret_key++;
575
+				continue;
576
+			}
577 577
 
578
-            if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
579
-            { // get ips of group members by oid
580
-                if ($this->apiUse === false)
581
-                {
582
-                    $db_conn2=$this->trapsDB->db_connect_ido();
583
-                    $sql="SELECT m.host_object_id, a.address, a.address6, b.name1 as name
578
+			if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
579
+			{ // get ips of group members by oid
580
+				if ($this->apiUse === false)
581
+				{
582
+					$db_conn2=$this->trapsDB->db_connect_ido();
583
+					$sql="SELECT m.host_object_id, a.address, a.address6, b.name1 as name
584 584
 						FROM icinga_objects as o
585 585
 						LEFT JOIN icinga_hostgroups as h ON o.object_id=h.hostgroup_object_id
586 586
 						LEFT JOIN icinga_hostgroup_members as m ON h.hostgroup_id=m.hostgroup_id
587 587
 						LEFT JOIN icinga_hosts as a ON a.host_object_id = m.host_object_id
588 588
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
589 589
 						WHERE o.name1='".$rule['host_group_name']."';";
590
-                    if (($ret_code2=$db_conn2->query($sql)) === false) {
591
-                        $this->logging->log('No result in query : ' . $sql,WARN,'');
592
-                        continue;
593
-                    }
594
-                    $grouphosts=$ret_code2->fetchAll();
595
-                }else{
596
-                    $api = $this->getAPI();
597
-                    $api->setCredentials($this->apiUsername, $this->apiPassword);
598
-                    $grouphosts=$api->getHostsIPByHostGroup($rule['host_group_name']);
599
-                }
600
-                //echo "rule grp :\n";print_r($grouphosts);echo "\n";
601
-                foreach ( $grouphosts as $host)
602
-                {
603
-                    if( is_object( $host ) ) $host=(array)$host;
604
-                    //echo $host['address']."\n";
605
-                    if ($host['address']==$ip || $host['address6']==$ip)
606
-                    {
607
-                        //echo "Rule added \n";
608
-                        $rules_ret[$rule_ret_key]=$rules_all[$key];
609
-                        $rules_ret[$rule_ret_key]['host_name']=$host['name'];
610
-                        $rule_ret_key++;
611
-                    }
612
-                }
613
-            }
590
+					if (($ret_code2=$db_conn2->query($sql)) === false) {
591
+						$this->logging->log('No result in query : ' . $sql,WARN,'');
592
+						continue;
593
+					}
594
+					$grouphosts=$ret_code2->fetchAll();
595
+				}else{
596
+					$api = $this->getAPI();
597
+					$api->setCredentials($this->apiUsername, $this->apiPassword);
598
+					$grouphosts=$api->getHostsIPByHostGroup($rule['host_group_name']);
599
+				}
600
+				//echo "rule grp :\n";print_r($grouphosts);echo "\n";
601
+				foreach ( $grouphosts as $host)
602
+				{
603
+					if( is_object( $host ) ) $host=(array)$host;
604
+					//echo $host['address']."\n";
605
+					if ($host['address']==$ip || $host['address6']==$ip)
606
+					{
607
+						//echo "Rule added \n";
608
+						$rules_ret[$rule_ret_key]=$rules_all[$key];
609
+						$rules_ret[$rule_ret_key]['host_name']=$host['name'];
610
+						$rule_ret_key++;
611
+					}
612
+				}
613
+			}
614 614
 
615
-        }
616
-        //echo "rule rest :\n";print_r($rules_ret);echo "\n";exit(0);
617
-        return $rules_ret;
618
-    }
615
+		}
616
+		//echo "rule rest :\n";print_r($rules_ret);echo "\n";exit(0);
617
+		return $rules_ret;
618
+	}
619 619
     
620
-    /** Add rule match to rule
621
-     *	@param id int : rule id
622
-     *   @param set int : value to set
623
-     */
624
-    protected function add_rule_match($id, $set)
625
-    {
626
-        $db_conn=$this->trapsDB->db_connect_trap();
627
-        $sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
628
-        if ($db_conn->query($sql) === false) {
629
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
630
-        }
631
-    }
620
+	/** Add rule match to rule
621
+	 *	@param id int : rule id
622
+	 *   @param set int : value to set
623
+	 */
624
+	protected function add_rule_match($id, $set)
625
+	{
626
+		$db_conn=$this->trapsDB->db_connect_trap();
627
+		$sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
628
+		if ($db_conn->query($sql) === false) {
629
+			$this->logging->log('Error in update query : ' . $sql,WARN,'');
630
+		}
631
+	}
632 632
     
633
-    /** Send SERVICE_CHECK_RESULT with icinga2cmd or API
634
-     *
635
-     * @param string $host
636
-     * @param string $service
637
-     * @param integer $state numerical staus
638
-     * @param string $display
639
-     * @returnn bool true is service check was sent without error
640
-     */
641
-    public function serviceCheckResult($host,$service,$state,$display)
642
-    {
643
-        if ($this->apiUse === false)
644
-        {
645
-            $send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
646
-                $host.';' .$service .';' . $state . ';'.$display;
647
-                $this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
633
+	/** Send SERVICE_CHECK_RESULT with icinga2cmd or API
634
+	 *
635
+	 * @param string $host
636
+	 * @param string $service
637
+	 * @param integer $state numerical staus
638
+	 * @param string $display
639
+	 * @returnn bool true is service check was sent without error
640
+	 */
641
+	public function serviceCheckResult($host,$service,$state,$display)
642
+	{
643
+		if ($this->apiUse === false)
644
+		{
645
+			$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
646
+				$host.';' .$service .';' . $state . ';'.$display;
647
+				$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
648 648
                 
649
-                // TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
650
-                exec('echo "'.$send.'" > ' .$this->icinga2cmd);
651
-                return true;
652
-        }
653
-        else
654
-        {
655
-            // Get perfdata if found
656
-            $matches=array();
657
-            if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
658
-            {
659
-                $display=$matches[1];
660
-                $perfdata=$matches[2];
661
-            }
662
-            else
663
-            {
664
-                $perfdata='';
665
-            }
649
+				// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
650
+				exec('echo "'.$send.'" > ' .$this->icinga2cmd);
651
+				return true;
652
+		}
653
+		else
654
+		{
655
+			// Get perfdata if found
656
+			$matches=array();
657
+			if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
658
+			{
659
+				$display=$matches[1];
660
+				$perfdata=$matches[2];
661
+			}
662
+			else
663
+			{
664
+				$perfdata='';
665
+			}
666 666
             
667
-            $api = $this->getAPI();
668
-            $api->setCredentials($this->apiUsername, $this->apiPassword);
669
-            list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
670
-            if ($retcode == false)
671
-            {
672
-                $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
673
-                return false;
674
-            }
675
-            else
676
-            {
677
-                $this->logging->log( "Sent result : " .$retmessage,INFO );
678
-                return true;
679
-            }
680
-        }
681
-    }
667
+			$api = $this->getAPI();
668
+			$api->setCredentials($this->apiUsername, $this->apiPassword);
669
+			list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
670
+			if ($retcode == false)
671
+			{
672
+				$this->logging->log( "Error sending result : " .$retmessage,WARN,'');
673
+				return false;
674
+			}
675
+			else
676
+			{
677
+				$this->logging->log( "Sent result : " .$retmessage,INFO );
678
+				return true;
679
+			}
680
+		}
681
+	}
682 682
     
683
-    public function getHostByIP($ip)
684
-    {
685
-        $api = $this->getAPI();
686
-        $api->setCredentials($this->apiUsername, $this->apiPassword);
687
-        return $api->getHostByIP($ip);
688
-    }
683
+	public function getHostByIP($ip)
684
+	{
685
+		$api = $this->getAPI();
686
+		$api->setCredentials($this->apiUsername, $this->apiPassword);
687
+		return $api->getHostByIP($ip);
688
+	}
689 689
     
690
-    /** Resolve display.
691
-     *	Changes _OID(<oid>) to value if found or text "<not in trap>"
692
-     *	@param $display string
693
-     *	@return string display
694
-     */
695
-    protected function applyDisplay($display)
696
-    {
697
-        $matches=array();
698
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$display,$matches) == 1)
699
-        {
700
-            $oid=$matches[1];
701
-            $found=0;
702
-            // Test and transform regexp
703
-            $oidR = $this->ruleClass->regexp_eval($oid);
690
+	/** Resolve display.
691
+	 *	Changes _OID(<oid>) to value if found or text "<not in trap>"
692
+	 *	@param $display string
693
+	 *	@return string display
694
+	 */
695
+	protected function applyDisplay($display)
696
+	{
697
+		$matches=array();
698
+		while (preg_match('/_OID\(([0-9\.\*]+)\)/',$display,$matches) == 1)
699
+		{
700
+			$oid=$matches[1];
701
+			$found=0;
702
+			// Test and transform regexp
703
+			$oidR = $this->ruleClass->regexp_eval($oid);
704 704
             
705
-            foreach($this->trapDataExt as $val)
706
-            {
707
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
708
-                {
709
-                    $val->value=preg_replace('/"/','',$val->value);
710
-                    $rep=0;
711
-                    $display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
712
-                    if ($rep==0)
713
-                    {
714
-                        $this->logging->log("Error in display",WARN,'');
715
-                        return $display;
716
-                    }
717
-                    $found=1;
718
-                    break;
719
-                }
720
-            }
721
-            if ($found==0)
722
-            {
723
-                $display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
724
-                if ($rep==0)
725
-                {
726
-                    $this->logging->log("Error in display",WARN,'');
727
-                    return $display;
728
-                }
729
-            }
730
-        }
731
-        return $display;
732
-    }
705
+			foreach($this->trapDataExt as $val)
706
+			{
707
+				if (preg_match("/^$oidR$/",$val->oid) == 1)
708
+				{
709
+					$val->value=preg_replace('/"/','',$val->value);
710
+					$rep=0;
711
+					$display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
712
+					if ($rep==0)
713
+					{
714
+						$this->logging->log("Error in display",WARN,'');
715
+						return $display;
716
+					}
717
+					$found=1;
718
+					break;
719
+				}
720
+			}
721
+			if ($found==0)
722
+			{
723
+				$display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
724
+				if ($rep==0)
725
+				{
726
+					$this->logging->log("Error in display",WARN,'');
727
+					return $display;
728
+				}
729
+			}
730
+		}
731
+		return $display;
732
+	}
733 733
     
734
-    /** Match rules for current trap and do action
735
-     */
736
-    public function applyRules()
737
-    {
738
-        $rules = $this->getRules($this->trapData['source_ip'],$this->trapData['trap_oid']);
739
-        
740
-        if ($rules===false || count($rules)==0)
741
-        {
742
-            $this->logging->log('No rules found for this trap',INFO );
743
-            $this->trapData['status']='unknown';
744
-            $this->trapToDb=true;
745
-            return;
746
-        }
747
-        //print_r($rules);
748
-        // Evaluate all rules in sequence
749
-        $this->trapAction=null;
750
-        foreach ($rules as $rule)
751
-        {
734
+	/** Match rules for current trap and do action
735
+	 */
736
+	public function applyRules()
737
+	{
738
+		$rules = $this->getRules($this->trapData['source_ip'],$this->trapData['trap_oid']);
739
+        
740
+		if ($rules===false || count($rules)==0)
741
+		{
742
+			$this->logging->log('No rules found for this trap',INFO );
743
+			$this->trapData['status']='unknown';
744
+			$this->trapToDb=true;
745
+			return;
746
+		}
747
+		//print_r($rules);
748
+		// Evaluate all rules in sequence
749
+		$this->trapAction=null;
750
+		foreach ($rules as $rule)
751
+		{
752 752
             
753
-            $host_name=$rule['host_name'];
754
-            $service_name=$rule['service_name'];
753
+			$host_name=$rule['host_name'];
754
+			$service_name=$rule['service_name'];
755 755
             
756
-            $display=$this->applyDisplay($rule['display']);
757
-            $this->trapAction = ($this->trapAction==null)? '' : $this->trapAction . ', ';
758
-            try
759
-            {
760
-                $this->logging->log('Rule to eval : '.$rule['rule'],INFO );
761
-                $evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt) ;
762
-                //->eval_rule($rule['rule']);
756
+			$display=$this->applyDisplay($rule['display']);
757
+			$this->trapAction = ($this->trapAction==null)? '' : $this->trapAction . ', ';
758
+			try
759
+			{
760
+				$this->logging->log('Rule to eval : '.$rule['rule'],INFO );
761
+				$evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt) ;
762
+				//->eval_rule($rule['rule']);
763 763
                 
764
-                if ($evalr == true)
765
-                {
766
-                    //$this->logging->log('rules OOK: '.print_r($rule),INFO );
767
-                    $action=$rule['action_match'];
768
-                    $this->logging->log('action OK : '.$action,INFO );
769
-                    if ($action >= 0)
770
-                    {
771
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
772
-                        {
773
-                            $this->trapAction.='Error sending status : check cmd/API';
774
-                        }
775
-                        else
776
-                        {
777
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
778
-                            $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
779
-                        }
780
-                    }
781
-                    else
782
-                    {
783
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
784
-                    }
785
-                    $this->trapToDb=($action==-2)?false:true;
786
-                }
787
-                else
788
-                {
789
-                    //$this->logging->log('rules KOO : '.print_r($rule),INFO );
764
+				if ($evalr == true)
765
+				{
766
+					//$this->logging->log('rules OOK: '.print_r($rule),INFO );
767
+					$action=$rule['action_match'];
768
+					$this->logging->log('action OK : '.$action,INFO );
769
+					if ($action >= 0)
770
+					{
771
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
772
+						{
773
+							$this->trapAction.='Error sending status : check cmd/API';
774
+						}
775
+						else
776
+						{
777
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
778
+							$this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
779
+						}
780
+					}
781
+					else
782
+					{
783
+						$this->add_rule_match($rule['id'],$rule['num_match']+1);
784
+					}
785
+					$this->trapToDb=($action==-2)?false:true;
786
+				}
787
+				else
788
+				{
789
+					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
790 790
                     
791
-                    $action=$rule['action_nomatch'];
792
-                    $this->logging->log('action NOK : '.$action,INFO );
793
-                    if ($action >= 0)
794
-                    {
795
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
796
-                        {
797
-                            $this->trapAction.='Error sending status : check cmd/API';
798
-                        }
799
-                        else
800
-                        {
801
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
802
-                            $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
803
-                        }
804
-                    }
805
-                    else
806
-                    {
807
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
808
-                    }
809
-                    $this->trapToDb=($action==-2)?false:true;
810
-                }
811
-                // Put name in source_name
812
-                if (!isset($this->trapData['source_name']))
813
-                {
814
-                    $this->trapData['source_name']=$rule['host_name'];
815
-                }
816
-                else
817
-                {
818
-                    if (!preg_match('/'.$rule['host_name'].'/',$this->trapData['source_name']))
819
-                    { // only add if not present
820
-                        $this->trapData['source_name'].=','.$rule['host_name'];
821
-                    }
822
-                }
823
-            }
824
-            catch (Exception $e)
825
-            {
826
-                $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
827
-                $this->trapAction.=' ERR : '.$e->getMessage();
828
-                $this->trapData['status']='error';
829
-            }
791
+					$action=$rule['action_nomatch'];
792
+					$this->logging->log('action NOK : '.$action,INFO );
793
+					if ($action >= 0)
794
+					{
795
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
796
+						{
797
+							$this->trapAction.='Error sending status : check cmd/API';
798
+						}
799
+						else
800
+						{
801
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
802
+							$this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
803
+						}
804
+					}
805
+					else
806
+					{
807
+						$this->add_rule_match($rule['id'],$rule['num_match']+1);
808
+					}
809
+					$this->trapToDb=($action==-2)?false:true;
810
+				}
811
+				// Put name in source_name
812
+				if (!isset($this->trapData['source_name']))
813
+				{
814
+					$this->trapData['source_name']=$rule['host_name'];
815
+				}
816
+				else
817
+				{
818
+					if (!preg_match('/'.$rule['host_name'].'/',$this->trapData['source_name']))
819
+					{ // only add if not present
820
+						$this->trapData['source_name'].=','.$rule['host_name'];
821
+					}
822
+				}
823
+			}
824
+			catch (Exception $e)
825
+			{
826
+				$this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
827
+				$this->trapAction.=' ERR : '.$e->getMessage();
828
+				$this->trapData['status']='error';
829
+			}
830 830
             
831
-        }
832
-        if ($this->trapData['status']=='error')
833
-        {
834
-            $this->trapToDb=true; // Always put errors in DB for the use can see
835
-        }
836
-        else
837
-        {
838
-            $this->trapData['status']='done';
839
-        }
840
-    }
831
+		}
832
+		if ($this->trapData['status']=='error')
833
+		{
834
+			$this->trapToDb=true; // Always put errors in DB for the use can see
835
+		}
836
+		else
837
+		{
838
+			$this->trapData['status']='done';
839
+		}
840
+	}
841 841
     
842
-    /** Add Time a action to rule
843
-     *	@param string $time : time to process to insert in SQL
844
-     */
845
-    public function add_rule_final($time)
846
-    {
847
-        $db_conn=$this->trapsDB->db_connect_trap();
848
-        if ($this->trapAction==null)
849
-        {
850
-            $this->trapAction='No action';
851
-        }
852
-        $sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trapAction."'  WHERE (id = '".$this->trapId."');";
853
-        if ($db_conn->query($sql) === false) {
854
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
855
-        }
856
-    }
842
+	/** Add Time a action to rule
843
+	 *	@param string $time : time to process to insert in SQL
844
+	 */
845
+	public function add_rule_final($time)
846
+	{
847
+		$db_conn=$this->trapsDB->db_connect_trap();
848
+		if ($this->trapAction==null)
849
+		{
850
+			$this->trapAction='No action';
851
+		}
852
+		$sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trapAction."'  WHERE (id = '".$this->trapId."');";
853
+		if ($db_conn->query($sql) === false) {
854
+			$this->logging->log('Error in update query : ' . $sql,WARN,'');
855
+		}
856
+	}
857 857
     
858
-    /*********** UTILITIES *********************/
858
+	/*********** UTILITIES *********************/
859 859
     
860
-    /** reset service to OK after time defined in rule
861
-     *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better
862
-     *	@return integer : not in use
863
-     **/
864
-    public function reset_services()
865
-    {
866
-        // Get all services not in 'ok' state
867
-        if ($this->apiUse === false)
868
-        {
869
-            $sql_query="SELECT s.service_object_id,
860
+	/** reset service to OK after time defined in rule
861
+	 *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better
862
+	 *	@return integer : not in use
863
+	 **/
864
+	public function reset_services()
865
+	{
866
+		// Get all services not in 'ok' state
867
+		if ($this->apiUse === false)
868
+		{
869
+			$sql_query="SELECT s.service_object_id,
870 870
                                 UNIX_TIMESTAMP(s.last_check) AS last_check,
871 871
                                 s.current_state as state,
872 872
                                 v.name1 as host_name,
@@ -874,49 +874,49 @@  discard block
 block discarded – undo
874 874
                                 FROM icinga_servicestatus AS s
875 875
                                 LEFT JOIN icinga_objects as v ON s.service_object_id=v.object_id
876 876
                                 WHERE s.current_state != 0;";
877
-            $db_conn=$this->trapsDB->db_connect_ido();
878
-            if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
879
-                $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
880
-                return 0;
881
-            }
882
-            $services=$services_db->fetchAll();
883
-        }else{
884
-            $api = $this->getAPI();
885
-            $api->setCredentials($this->apiUsername, $this->apiPassword);
886
-            $services=$api->getNOKservice();
887
-        }
888
-        
889
-        // Get all rules
890
-        $sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
891
-        $db_conn2=$this->trapsDB->db_connect_trap();
892
-        if (($rules_db=$db_conn2->query($sql_query)) === false) {
893
-            $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
894
-            return 0;
895
-        }
896
-        $rules=$rules_db->fetchAll();
897
-        
898
-        $now=date('U');
899
-        
900
-        $numreset=0;
901
-        foreach ($rules as $rule)
902
-        {
903
-            if( is_object( $services ) ) $services=(array)$services;
904
-            foreach ($services as $service)
905
-            {
906
-                if ($service['name'] == $rule['service_name'] &&
907
-                    $service['host_name'] == $rule['host_name'] &&
908
-                    ($service['last_check'] + $rule['revert_ok']) < $now)
909
-                {
910
-                    $this->serviceCheckResult($service['host_name'],$service['name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
911
-                    $numreset++;
912
-                }
913
-            }
914
-        }
915
-        echo "\n";
916
-        echo $numreset . " service(s) reset to OK\n";
917
-        return 0;
918
-        
919
-    }
877
+			$db_conn=$this->trapsDB->db_connect_ido();
878
+			if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
879
+				$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
880
+				return 0;
881
+			}
882
+			$services=$services_db->fetchAll();
883
+		}else{
884
+			$api = $this->getAPI();
885
+			$api->setCredentials($this->apiUsername, $this->apiPassword);
886
+			$services=$api->getNOKservice();
887
+		}
888
+        
889
+		// Get all rules
890
+		$sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
891
+		$db_conn2=$this->trapsDB->db_connect_trap();
892
+		if (($rules_db=$db_conn2->query($sql_query)) === false) {
893
+			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
894
+			return 0;
895
+		}
896
+		$rules=$rules_db->fetchAll();
897
+        
898
+		$now=date('U');
899
+        
900
+		$numreset=0;
901
+		foreach ($rules as $rule)
902
+		{
903
+			if( is_object( $services ) ) $services=(array)$services;
904
+			foreach ($services as $service)
905
+			{
906
+				if ($service['name'] == $rule['service_name'] &&
907
+					$service['host_name'] == $rule['host_name'] &&
908
+					($service['last_check'] + $rule['revert_ok']) < $now)
909
+				{
910
+					$this->serviceCheckResult($service['host_name'],$service['name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
911
+					$numreset++;
912
+				}
913
+			}
914
+		}
915
+		echo "\n";
916
+		echo $numreset . " service(s) reset to OK\n";
917
+		return 0;
918
+        
919
+	}
920 920
     
921 921
     
922 922
 }
Please login to merge, or discard this patch.
Spacing   +184 added lines, -184 removed lines patch added patch discarded remove patch
@@ -52,13 +52,13 @@  discard block
 block discarded – undo
52 52
     
53 53
     // Logs
54 54
     /** @var Logging Logging class. */
55
-    public $logging;    //< Logging class.
55
+    public $logging; //< Logging class.
56 56
     /** @var bool true if log was setup in constructor */
57
-    protected $logSetup;   //< bool true if log was setup in constructor
57
+    protected $logSetup; //< bool true if log was setup in constructor
58 58
     
59 59
     // Databases
60 60
     /** @var Database $trapsDB  Database class*/
61
-    public $trapsDB = null;
61
+    public $trapsDB=null;
62 62
     
63 63
     // Trap received data
64 64
     protected $receivingHost;
@@ -74,18 +74,18 @@  discard block
 block discarded – undo
74 74
     protected $trapToDb=true;
75 75
     
76 76
     /** @var Mib mib class */
77
-    public $mibClass = null;
77
+    public $mibClass=null;
78 78
     
79 79
     /** @var Rule rule class */
80
-    public $ruleClass = null;
80
+    public $ruleClass=null;
81 81
     
82 82
     /** @var Plugins plugins manager **/
83
-    public $pluginClass = null;
83
+    public $pluginClass=null;
84 84
     
85 85
     /** @var TrapApi $trapApiClass */
86
-    public $trapApiClass = null;
86
+    public $trapApiClass=null;
87 87
     
88
-    function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
88
+    function __construct($etcDir='/etc/icingaweb2', $baseLogLevel=null, $baseLogMode='syslog', $baseLogFile='')
89 89
     {
90 90
         // Paths of ini files
91 91
         $this->icingaweb2Etc=$etcDir;
@@ -93,10 +93,10 @@  discard block
 block discarded – undo
93 93
         $this->icingaweb2Ressources=$this->icingaweb2Etc."/resources.ini";
94 94
 
95 95
         // Setup logging
96
-        $this->logging = new Logging();
96
+        $this->logging=new Logging();
97 97
         if ($baseLogLevel != null)
98 98
         {
99
-            $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
99
+            $this->logging->setLogging($baseLogLevel, $baseLogMode, $baseLogFile);
100 100
             $this->logSetup=true;
101 101
         }
102 102
         else
@@ -108,17 +108,17 @@  discard block
 block discarded – undo
108 108
         
109 109
         // Create distributed API object
110 110
         
111
-        $this->trapApiClass = new TrapApi($this->logging);
111
+        $this->trapApiClass=new TrapApi($this->logging);
112 112
         
113 113
         // Get options from ini files
114
-        if (! is_file($this->trapModuleConfig))
114
+        if (!is_file($this->trapModuleConfig))
115 115
         {
116 116
             throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
117 117
         }
118
-        $trapConfig=parse_ini_file($this->trapModuleConfig,true);
118
+        $trapConfig=parse_ini_file($this->trapModuleConfig, true);
119 119
         if ($trapConfig == false)
120 120
         {
121
-            $this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
121
+            $this->logging->log("Error reading ini file : ".$this->trapModuleConfig, ERROR, 'syslog');
122 122
             throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
123 123
         }
124 124
         $this->getMainOptions($trapConfig); // Get main options from ini file
@@ -133,10 +133,10 @@  discard block
 block discarded – undo
133 133
         if ($this->apiUse === true) $this->getAPI(); // Setup API
134 134
         
135 135
         // Setup MIB
136
-        $this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
136
+        $this->mibClass=new Mib($this->logging, $this->trapsDB, $this->snmptranslate, $this->snmptranslate_dirs); // Create Mib class
137 137
         
138 138
         // Setup Rule
139
-        $this->ruleClass = new Rule($this); //< Create Rule class
139
+        $this->ruleClass=new Rule($this); //< Create Rule class
140 140
         
141 141
         $this->trapData=array(  // TODO : put this in a reset function (DAEMON_MODE)
142 142
             'source_ip'	=> 'unknown',
@@ -148,8 +148,8 @@  discard block
 block discarded – undo
148 148
         
149 149
         // Setup Plugins
150 150
         //Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
151
-        $this->pluginClass = new Plugins($this);
152
-	}catch (Exception $e){ return; }
151
+        $this->pluginClass=new Plugins($this);
152
+	} catch (Exception $e) { return; }
153 153
             
154 154
     }
155 155
 
@@ -177,15 +177,15 @@  discard block
 block discarded – undo
177 177
      *	@param  string $destination file/syslog/display
178 178
      *	@return void
179 179
      **/
180
-    public function trapLog( $message, $level, $destination ='') // OBSOLETE
180
+    public function trapLog($message, $level, $destination='') // OBSOLETE
181 181
     {
182 182
         // TODO : replace ref with $this->logging->log
183 183
         $this->logging->log($message, $level, $destination);
184 184
     }
185 185
     
186
-    public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
186
+    public function setLogging($debugLvl, $outputType, $outputOption=null)  // OBSOLETE
187 187
     {
188
-        $this->logging->setLogging($debugLvl, $outputType,$outputOption);
188
+        $this->logging->setLogging($debugLvl, $outputType, $outputOption);
189 189
     }
190 190
     
191 191
     /**
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
     {
197 197
         if ($this->icinga2api == null)
198 198
         {
199
-            $this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
199
+            $this->icinga2api=new Icinga2API($this->apiHostname, $this->apiPort);
200 200
         }
201 201
         return $this->icinga2api;
202 202
     }
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
         if ($input_stream === false)
216 216
         {
217 217
             $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
218
-            $this->logging->log("Error reading stdin !",ERROR,'');
218
+            $this->logging->log("Error reading stdin !", ERROR, '');
219 219
             return null; // note : exception thrown by logging
220 220
         }
221 221
         
@@ -224,21 +224,21 @@  discard block
 block discarded – undo
224 224
         if ($this->receivingHost === false)
225 225
         {
226 226
             $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
227
-            $this->logging->log("Error reading Host !",ERROR,'');
227
+            $this->logging->log("Error reading Host !", ERROR, '');
228 228
         }
229 229
         // line 2 IP:port=>IP:port
230 230
         $IP=chop(fgets($input_stream));
231 231
         if ($IP === false)
232 232
         {
233 233
             $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
234
-            $this->logging->log("Error reading IP !",ERROR,'');
234
+            $this->logging->log("Error reading IP !", ERROR, '');
235 235
         }
236 236
         $matches=array();
237
-        $ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
238
-        if ($ret_code===0 || $ret_code===false)
237
+        $ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/', $IP, $matches);
238
+        if ($ret_code === 0 || $ret_code === false)
239 239
         {
240 240
             $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
241
-            $this->logging->log('Error parsing IP : '.$IP,ERROR,'');
241
+            $this->logging->log('Error parsing IP : '.$IP, ERROR, '');
242 242
         }
243 243
         else
244 244
         {
@@ -248,41 +248,41 @@  discard block
 block discarded – undo
248 248
             $this->trapData['destination_port']=$matches[4];
249 249
         }
250 250
         
251
-        while (($vars=fgets($input_stream)) !==false)
251
+        while (($vars=fgets($input_stream)) !== false)
252 252
         {
253 253
             $vars=chop($vars);
254
-            $ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
255
-            if ($ret_code===0 || $ret_code===false)
254
+            $ret_code=preg_match('/^([^ ]+) (.*)$/', $vars, $matches);
255
+            if ($ret_code === 0 || $ret_code === false)
256 256
             {
257
-                $this->logging->log('No match on trap data : '.$vars,WARN,'');
257
+                $this->logging->log('No match on trap data : '.$vars, WARN, '');
258 258
                 continue;
259 259
             }
260
-            if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
260
+            if (($matches[1] == '.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1] == '.1.3.6.1.6.3.1.1.4.1'))
261 261
             {
262 262
                 $this->trapData['trap_oid']=$matches[2];
263 263
                 continue;
264 264
             }
265
-            if ( $this->useSnmpTrapAddess === TRUE &&  preg_match('/'.$this->snmpTrapAddressOID.'/', $matches[1]) == 1)
265
+            if ($this->useSnmpTrapAddess === TRUE && preg_match('/'.$this->snmpTrapAddressOID.'/', $matches[1]) == 1)
266 266
             {
267
-                $this->logging->log('Found relayed trap from ' . $matches[2] . ' relayed by ' .$this->trapData['source_ip'],DEBUG);
268
-                if (preg_match('/^[0-9\.]+$/',$matches[2]) == 0 && preg_match('/^[0-9a-fA-F:]+$/',$matches[2]) == 0)
267
+                $this->logging->log('Found relayed trap from '.$matches[2].' relayed by '.$this->trapData['source_ip'], DEBUG);
268
+                if (preg_match('/^[0-9\.]+$/', $matches[2]) == 0 && preg_match('/^[0-9a-fA-F:]+$/', $matches[2]) == 0)
269 269
                 {
270
-                    $this->logging->log('Value of SnmpTrapAddess ('.$this->snmpTrapAddressOID.') is not IP : ' .$matches[2],WARN,'');
270
+                    $this->logging->log('Value of SnmpTrapAddess ('.$this->snmpTrapAddressOID.') is not IP : '.$matches[2], WARN, '');
271 271
                     continue;
272 272
                 }
273
-                $this->trapData['source_ip'] = $matches[2];
273
+                $this->trapData['source_ip']=$matches[2];
274 274
                 continue;
275 275
             }
276
-            $object= new stdClass;
277
-            $object->oid =$matches[1];
278
-            $object->value = $matches[2];
279
-            array_push($this->trapDataExt,$object);
276
+            $object=new stdClass;
277
+            $object->oid=$matches[1];
278
+            $object->value=$matches[2];
279
+            array_push($this->trapDataExt, $object);
280 280
         }
281 281
         
282
-        if ($this->trapData['trap_oid']=='unknown')
282
+        if ($this->trapData['trap_oid'] == 'unknown')
283 283
         {
284
-            $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trapData['source_ip']);
285
-            $this->logging->log('no trap oid found',ERROR,'');
284
+            $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)", $this->trapData['source_ip']);
285
+            $this->logging->log('no trap oid found', ERROR, '');
286 286
         }
287 287
         
288 288
         // Translate oids.
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
         }
305 305
         
306 306
         
307
-        $this->trapData['status']= 'waiting';
307
+        $this->trapData['status']='waiting';
308 308
         
309 309
         return $this->trapData;
310 310
     }
@@ -320,38 +320,38 @@  discard block
 block discarded – undo
320 320
         $db_conn=$this->trapsDB->db_connect_trap();
321 321
         
322 322
         $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
323
-        $this->logging->log('SQL query : '.$sql,DEBUG );
323
+        $this->logging->log('SQL query : '.$sql, DEBUG);
324 324
         if (($ret_code=$db_conn->query($sql)) === false) {
325
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
325
+            $this->logging->log('No result in query : '.$sql, ERROR, '');
326 326
         }
327 327
         else {
328 328
             if (($name=$ret_code->fetch()) !== false)
329
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
329
+                return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
330 330
         }
331 331
         
332 332
         // Also check if it is an instance of OID
333
-        $oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
333
+        $oid_instance=preg_replace('/\.[0-9]+$/', '', $oid);
334 334
         
335 335
         $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
336
-        $this->logging->log('SQL query : '.$sql,DEBUG );
336
+        $this->logging->log('SQL query : '.$sql, DEBUG);
337 337
         if (($ret_code=$db_conn->query($sql)) === false) {
338
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
338
+            $this->logging->log('No result in query : '.$sql, ERROR, '');
339 339
         }
340 340
         else {
341 341
             if (($name=$ret_code->fetch()) !== false)
342
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
342
+                return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
343 343
         }
344 344
         
345 345
         // Try to get oid name from snmptranslate
346
-        $translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
346
+        $translate=exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
347 347
             ' '.$oid);
348 348
         $matches=array();
349
-        $ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
350
-        if ($ret_code===0 || $ret_code === false) {
349
+        $ret_code=preg_match('/(.*)::(.*)/', $translate, $matches);
350
+        if ($ret_code === 0 || $ret_code === false) {
351 351
             return NULL;
352 352
         } else {
353
-            $this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
354
-            return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
353
+            $this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid, INFO);
354
+            return array('trap_name_mib'=>$matches[1], 'trap_name'=>$matches[2]);
355 355
         }
356 356
     }
357 357
     
@@ -362,90 +362,90 @@  discard block
 block discarded – undo
362 362
      **/
363 363
     public function eraseOldTraps($days=0)
364 364
     {
365
-        if ($days==0)
365
+        if ($days == 0)
366 366
         {
367 367
             if (($days=$this->getDBConfig('db_remove_days')) == null)
368 368
             {
369
-                $this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
369
+                $this->logging->log('No days specified & no db value : no tap erase', WARN, '');
370 370
                 return;
371 371
             }
372 372
         }
373 373
         $db_conn=$this->trapsDB->db_connect_trap();
374
-        $daysago = strtotime("-".$days." day");
375
-        $sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
374
+        $daysago=strtotime("-".$days." day");
375
+        $sql='delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s", $daysago).'\';';
376 376
         if ($db_conn->query($sql) === false) {
377
-            $this->logging->log('Error erasing traps : '.$sql,ERROR,'');
377
+            $this->logging->log('Error erasing traps : '.$sql, ERROR, '');
378 378
         }
379
-        $this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
379
+        $this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql, INFO);
380 380
     }
381 381
     
382 382
     /** Write error to received trap database
383 383
      */
384
-    public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
384
+    public function writeTrapErrorToDB($message, $sourceIP=null, $trapoid=null)
385 385
     {
386 386
         
387 387
         $db_conn=$this->trapsDB->db_connect_trap();
388 388
         
389 389
         // add date time
390
-        $insert_col ='date_received,status';
391
-        $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
390
+        $insert_col='date_received,status';
391
+        $insert_val="'".date("Y-m-d H:i:s")."','error'";
392 392
         
393
-        if ($sourceIP !=null)
393
+        if ($sourceIP != null)
394 394
         {
395
-            $insert_col .=',source_ip';
396
-            $insert_val .=",'". $sourceIP ."'";
395
+            $insert_col.=',source_ip';
396
+            $insert_val.=",'".$sourceIP."'";
397 397
         }
398
-        if ($trapoid !=null)
398
+        if ($trapoid != null)
399 399
         {
400
-            $insert_col .=',trap_oid';
401
-            $insert_val .=",'". $trapoid ."'";
400
+            $insert_col.=',trap_oid';
401
+            $insert_val.=",'".$trapoid."'";
402 402
         }
403
-        $insert_col .=',status_detail';
404
-        $insert_val .=",'". $message ."'";
403
+        $insert_col.=',status_detail';
404
+        $insert_val.=",'".$message."'";
405 405
         
406
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
406
+        $sql='INSERT INTO '.$this->dbPrefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
407 407
         
408 408
         switch ($this->trapsDB->trapDBType)
409 409
         {
410 410
             case 'pgsql':
411
-                $sql .= ' RETURNING id;';
412
-                $this->logging->log('sql : '.$sql,INFO);
411
+                $sql.=' RETURNING id;';
412
+                $this->logging->log('sql : '.$sql, INFO);
413 413
                 if (($ret_code=$db_conn->query($sql)) === false) {
414
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
414
+                    $this->logging->log('Error SQL insert : '.$sql, 1, '');
415 415
                 }
416
-                $this->logging->log('SQL insertion OK',INFO );
416
+                $this->logging->log('SQL insertion OK', INFO);
417 417
                 // Get last id to insert oid/values in secondary table
418 418
                 if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
419 419
                     
420
-                    $this->logging->log('Erreur recuperation id',1,'');
420
+                    $this->logging->log('Erreur recuperation id', 1, '');
421 421
                 }
422
-                if (! isset($inserted_id_ret['id'])) {
423
-                    $this->logging->log('Error getting id',1,'');
422
+                if (!isset($inserted_id_ret['id'])) {
423
+                    $this->logging->log('Error getting id', 1, '');
424 424
                 }
425 425
                 $this->trapId=$inserted_id_ret['id'];
426 426
                 break;
427 427
             case 'mysql':
428
-                $sql .= ';';
429
-                $this->logging->log('sql : '.$sql,INFO );
428
+                $sql.=';';
429
+                $this->logging->log('sql : '.$sql, INFO);
430 430
                 if ($db_conn->query($sql) === false) {
431
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
431
+                    $this->logging->log('Error SQL insert : '.$sql, 1, '');
432 432
                 }
433
-                $this->logging->log('SQL insertion OK',INFO );
433
+                $this->logging->log('SQL insertion OK', INFO);
434 434
                 // Get last id to insert oid/values in secondary table
435 435
                 $sql='SELECT LAST_INSERT_ID();';
436 436
                 if (($ret_code=$db_conn->query($sql)) === false) {
437
-                    $this->logging->log('Erreur recuperation id',1,'');
437
+                    $this->logging->log('Erreur recuperation id', 1, '');
438 438
                 }
439 439
                 
440 440
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
441
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
441
+                if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
442 442
                 $this->trapId=$inserted_id;
443 443
                 break;
444 444
             default:
445
-                $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
445
+                $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType, 1, '');
446 446
         }
447 447
         
448
-        $this->logging->log('id found: '. $this->trapId,INFO );
448
+        $this->logging->log('id found: '.$this->trapId, INFO);
449 449
     }
450 450
     
451 451
     /** Write trap data to trap database
@@ -462,86 +462,86 @@  discard block
 block discarded – undo
462 462
         $insert_col='';
463 463
         $insert_val='';
464 464
         // add date time
465
-        $this->trapData['date_received'] = date("Y-m-d H:i:s");
465
+        $this->trapData['date_received']=date("Y-m-d H:i:s");
466 466
         
467 467
         $firstcol=1;
468 468
         foreach ($this->trapData as $col => $val)
469 469
         {
470
-            if ($firstcol==0)
470
+            if ($firstcol == 0)
471 471
             {
472
-                $insert_col .=',';
473
-                $insert_val .=',';
472
+                $insert_col.=',';
473
+                $insert_val.=',';
474 474
             }
475
-            $insert_col .= $col ;
476
-            $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
475
+            $insert_col.=$col;
476
+            $insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
477 477
             $firstcol=0;
478 478
         }
479 479
         
480
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
480
+        $sql='INSERT INTO '.$this->dbPrefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
481 481
         switch ($this->trapsDB->trapDBType)
482 482
         {
483 483
             case 'pgsql':
484
-                $sql .= ' RETURNING id;';
485
-                $this->logging->log('sql : '.$sql,INFO );
484
+                $sql.=' RETURNING id;';
485
+                $this->logging->log('sql : '.$sql, INFO);
486 486
                 if (($ret_code=$db_conn->query($sql)) === false) {
487
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
487
+                    $this->logging->log('Error SQL insert : '.$sql, ERROR, '');
488 488
                 }
489
-                $this->logging->log('SQL insertion OK',INFO );
489
+                $this->logging->log('SQL insertion OK', INFO);
490 490
                 // Get last id to insert oid/values in secondary table
491 491
                 if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
492 492
                     
493
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
493
+                    $this->logging->log('Erreur recuperation id', ERROR, '');
494 494
                 }
495
-                if (! isset($inserted_id_ret['id'])) {
496
-                    $this->logging->log('Error getting id',ERROR,'');
495
+                if (!isset($inserted_id_ret['id'])) {
496
+                    $this->logging->log('Error getting id', ERROR, '');
497 497
                 }
498 498
                 $this->trapId=$inserted_id_ret['id'];
499 499
                 break;
500 500
             case 'mysql':
501
-                $sql .= ';';
502
-                $this->logging->log('sql : '.$sql,INFO );
501
+                $sql.=';';
502
+                $this->logging->log('sql : '.$sql, INFO);
503 503
                 if ($db_conn->query($sql) === false) {
504
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
504
+                    $this->logging->log('Error SQL insert : '.$sql, ERROR, '');
505 505
                 }
506
-                $this->logging->log('SQL insertion OK',INFO );
506
+                $this->logging->log('SQL insertion OK', INFO);
507 507
                 // Get last id to insert oid/values in secondary table
508 508
                 $sql='SELECT LAST_INSERT_ID();';
509 509
                 if (($ret_code=$db_conn->query($sql)) === false) {
510
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
510
+                    $this->logging->log('Erreur recuperation id', ERROR, '');
511 511
                 }
512 512
                 
513 513
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
514
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
514
+                if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
515 515
                 $this->trapId=$inserted_id;
516 516
                 break;
517 517
             default:
518
-                $this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
518
+                $this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType, ERROR, '');
519 519
         }
520
-        $this->logging->log('id found: '.$this->trapId,INFO );
520
+        $this->logging->log('id found: '.$this->trapId, INFO);
521 521
         
522 522
         // Fill trap extended data table
523 523
         foreach ($this->trapDataExt as $value) {
524 524
             // TODO : detect if trap value is encoded and decode it to UTF-8 for database
525 525
             $firstcol=1;
526
-            $value->trap_id = $this->trapId;
526
+            $value->trap_id=$this->trapId;
527 527
             $insert_col='';
528 528
             $insert_val='';
529 529
             foreach ($value as $col => $val)
530 530
             {
531
-                if ($firstcol==0)
531
+                if ($firstcol == 0)
532 532
                 {
533
-                    $insert_col .=',';
534
-                    $insert_val .=',';
533
+                    $insert_col.=',';
534
+                    $insert_val.=',';
535 535
                 }
536
-                $insert_col .= $col;
537
-                $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
536
+                $insert_col.=$col;
537
+                $insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
538 538
                 $firstcol=0;
539 539
             }
540 540
             
541
-            $sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
541
+            $sql='INSERT INTO '.$this->dbPrefix.'received_data ('.$insert_col.') VALUES ('.$insert_val.');';
542 542
             
543 543
             if ($db_conn->query($sql) === false) {
544
-                $this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
544
+                $this->logging->log('Erreur insertion data : '.$sql, WARN, '');
545 545
             }
546 546
         }
547 547
     }
@@ -551,14 +551,14 @@  discard block
 block discarded – undo
551 551
      *	@param $oid string oid in numeric
552 552
      *	@return mixed|boolean : PDO object or false
553 553
      */
554
-    protected function getRules($ip,$oid)
554
+    protected function getRules($ip, $oid)
555 555
     {
556 556
         $db_conn=$this->trapsDB->db_connect_trap();
557 557
         // fetch rules based on IP in rule and OID
558 558
         $sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
559
-        $this->logging->log('SQL query : '.$sql,DEBUG );
559
+        $this->logging->log('SQL query : '.$sql, DEBUG);
560 560
         if (($ret_code=$db_conn->query($sql)) === false) {
561
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
561
+            $this->logging->log('No result in query : '.$sql, WARN, '');
562 562
             return false;
563 563
         }
564 564
         $rules_all=$ret_code->fetchAll();
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
         $rule_ret_key=0;
568 568
         foreach ($rules_all as $key => $rule)
569 569
         {
570
-            if ($rule['ip4']==$ip || $rule['ip6']==$ip)
570
+            if ($rule['ip4'] == $ip || $rule['ip6'] == $ip)
571 571
             {
572 572
                 $rules_ret[$rule_ret_key]=$rules_all[$key];
573 573
                 //TODO : get host name by API (and check if correct in rule).
@@ -575,7 +575,7 @@  discard block
 block discarded – undo
575 575
                 continue;
576 576
             }
577 577
 
578
-            if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
578
+            if (isset($rule['host_group_name']) && $rule['host_group_name'] != null)
579 579
             { // get ips of group members by oid
580 580
                 if ($this->apiUse === false)
581 581
                 {
@@ -588,21 +588,21 @@  discard block
 block discarded – undo
588 588
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
589 589
 						WHERE o.name1='".$rule['host_group_name']."';";
590 590
                     if (($ret_code2=$db_conn2->query($sql)) === false) {
591
-                        $this->logging->log('No result in query : ' . $sql,WARN,'');
591
+                        $this->logging->log('No result in query : '.$sql, WARN, '');
592 592
                         continue;
593 593
                     }
594 594
                     $grouphosts=$ret_code2->fetchAll();
595
-                }else{
596
-                    $api = $this->getAPI();
595
+                } else {
596
+                    $api=$this->getAPI();
597 597
                     $api->setCredentials($this->apiUsername, $this->apiPassword);
598 598
                     $grouphosts=$api->getHostsIPByHostGroup($rule['host_group_name']);
599 599
                 }
600 600
                 //echo "rule grp :\n";print_r($grouphosts);echo "\n";
601
-                foreach ( $grouphosts as $host)
601
+                foreach ($grouphosts as $host)
602 602
                 {
603
-                    if( is_object( $host ) ) $host=(array)$host;
603
+                    if (is_object($host)) $host=(array) $host;
604 604
                     //echo $host['address']."\n";
605
-                    if ($host['address']==$ip || $host['address6']==$ip)
605
+                    if ($host['address'] == $ip || $host['address6'] == $ip)
606 606
                     {
607 607
                         //echo "Rule added \n";
608 608
                         $rules_ret[$rule_ret_key]=$rules_all[$key];
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
         $db_conn=$this->trapsDB->db_connect_trap();
627 627
         $sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
628 628
         if ($db_conn->query($sql) === false) {
629
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
629
+            $this->logging->log('Error in update query : '.$sql, WARN, '');
630 630
         }
631 631
     }
632 632
     
@@ -638,23 +638,23 @@  discard block
 block discarded – undo
638 638
      * @param string $display
639 639
      * @returnn bool true is service check was sent without error
640 640
      */
641
-    public function serviceCheckResult($host,$service,$state,$display)
641
+    public function serviceCheckResult($host, $service, $state, $display)
642 642
     {
643 643
         if ($this->apiUse === false)
644 644
         {
645
-            $send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
646
-                $host.';' .$service .';' . $state . ';'.$display;
647
-                $this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
645
+            $send='['.date('U').'] PROCESS_SERVICE_CHECK_RESULT;'.
646
+                $host.';'.$service.';'.$state.';'.$display;
647
+                $this->logging->log($send." : to : ".$this->icinga2cmd, INFO);
648 648
                 
649 649
                 // TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
650
-                exec('echo "'.$send.'" > ' .$this->icinga2cmd);
650
+                exec('echo "'.$send.'" > '.$this->icinga2cmd);
651 651
                 return true;
652 652
         }
653 653
         else
654 654
         {
655 655
             // Get perfdata if found
656 656
             $matches=array();
657
-            if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
657
+            if (preg_match('/(.*)\|(.*)/', $display, $matches) == 1)
658 658
             {
659 659
                 $display=$matches[1];
660 660
                 $perfdata=$matches[2];
@@ -664,17 +664,17 @@  discard block
 block discarded – undo
664 664
                 $perfdata='';
665 665
             }
666 666
             
667
-            $api = $this->getAPI();
667
+            $api=$this->getAPI();
668 668
             $api->setCredentials($this->apiUsername, $this->apiPassword);
669
-            list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
669
+            list($retcode, $retmessage)=$api->serviceCheckResult($host, $service, $state, $display, $perfdata);
670 670
             if ($retcode == false)
671 671
             {
672
-                $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
672
+                $this->logging->log("Error sending result : ".$retmessage, WARN, '');
673 673
                 return false;
674 674
             }
675 675
             else
676 676
             {
677
-                $this->logging->log( "Sent result : " .$retmessage,INFO );
677
+                $this->logging->log("Sent result : ".$retmessage, INFO);
678 678
                 return true;
679 679
             }
680 680
         }
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
     
683 683
     public function getHostByIP($ip)
684 684
     {
685
-        $api = $this->getAPI();
685
+        $api=$this->getAPI();
686 686
         $api->setCredentials($this->apiUsername, $this->apiPassword);
687 687
         return $api->getHostByIP($ip);
688 688
     }
@@ -695,35 +695,35 @@  discard block
 block discarded – undo
695 695
     protected function applyDisplay($display)
696 696
     {
697 697
         $matches=array();
698
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$display,$matches) == 1)
698
+        while (preg_match('/_OID\(([0-9\.\*]+)\)/', $display, $matches) == 1)
699 699
         {
700 700
             $oid=$matches[1];
701 701
             $found=0;
702 702
             // Test and transform regexp
703
-            $oidR = $this->ruleClass->regexp_eval($oid);
703
+            $oidR=$this->ruleClass->regexp_eval($oid);
704 704
             
705
-            foreach($this->trapDataExt as $val)
705
+            foreach ($this->trapDataExt as $val)
706 706
             {
707
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
707
+                if (preg_match("/^$oidR$/", $val->oid) == 1)
708 708
                 {
709
-                    $val->value=preg_replace('/"/','',$val->value);
709
+                    $val->value=preg_replace('/"/', '', $val->value);
710 710
                     $rep=0;
711
-                    $display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
712
-                    if ($rep==0)
711
+                    $display=preg_replace('/_OID\('.$oid.'\)/', $val->value, $display, -1, $rep);
712
+                    if ($rep == 0)
713 713
                     {
714
-                        $this->logging->log("Error in display",WARN,'');
714
+                        $this->logging->log("Error in display", WARN, '');
715 715
                         return $display;
716 716
                     }
717 717
                     $found=1;
718 718
                     break;
719 719
                 }
720 720
             }
721
-            if ($found==0)
721
+            if ($found == 0)
722 722
             {
723
-                $display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
724
-                if ($rep==0)
723
+                $display=preg_replace('/_OID\('.$oid.'\)/', '<not in trap>', $display, -1, $rep);
724
+                if ($rep == 0)
725 725
                 {
726
-                    $this->logging->log("Error in display",WARN,'');
726
+                    $this->logging->log("Error in display", WARN, '');
727 727
                     return $display;
728 728
                 }
729 729
             }
@@ -735,11 +735,11 @@  discard block
 block discarded – undo
735 735
      */
736 736
     public function applyRules()
737 737
     {
738
-        $rules = $this->getRules($this->trapData['source_ip'],$this->trapData['trap_oid']);
738
+        $rules=$this->getRules($this->trapData['source_ip'], $this->trapData['trap_oid']);
739 739
         
740
-        if ($rules===false || count($rules)==0)
740
+        if ($rules === false || count($rules) == 0)
741 741
         {
742
-            $this->logging->log('No rules found for this trap',INFO );
742
+            $this->logging->log('No rules found for this trap', INFO);
743 743
             $this->trapData['status']='unknown';
744 744
             $this->trapToDb=true;
745 745
             return;
@@ -754,59 +754,59 @@  discard block
 block discarded – undo
754 754
             $service_name=$rule['service_name'];
755 755
             
756 756
             $display=$this->applyDisplay($rule['display']);
757
-            $this->trapAction = ($this->trapAction==null)? '' : $this->trapAction . ', ';
757
+            $this->trapAction=($this->trapAction == null) ? '' : $this->trapAction.', ';
758 758
             try
759 759
             {
760
-                $this->logging->log('Rule to eval : '.$rule['rule'],INFO );
761
-                $evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt) ;
760
+                $this->logging->log('Rule to eval : '.$rule['rule'], INFO);
761
+                $evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt);
762 762
                 //->eval_rule($rule['rule']);
763 763
                 
764 764
                 if ($evalr == true)
765 765
                 {
766 766
                     //$this->logging->log('rules OOK: '.print_r($rule),INFO );
767 767
                     $action=$rule['action_match'];
768
-                    $this->logging->log('action OK : '.$action,INFO );
768
+                    $this->logging->log('action OK : '.$action, INFO);
769 769
                     if ($action >= 0)
770 770
                     {
771
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
771
+                        if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
772 772
                         {
773 773
                             $this->trapAction.='Error sending status : check cmd/API';
774 774
                         }
775 775
                         else
776 776
                         {
777
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
777
+                            $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
778 778
                             $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
779 779
                         }
780 780
                     }
781 781
                     else
782 782
                     {
783
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
783
+                        $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
784 784
                     }
785
-                    $this->trapToDb=($action==-2)?false:true;
785
+                    $this->trapToDb=($action == -2) ?false:true;
786 786
                 }
787 787
                 else
788 788
                 {
789 789
                     //$this->logging->log('rules KOO : '.print_r($rule),INFO );
790 790
                     
791 791
                     $action=$rule['action_nomatch'];
792
-                    $this->logging->log('action NOK : '.$action,INFO );
792
+                    $this->logging->log('action NOK : '.$action, INFO);
793 793
                     if ($action >= 0)
794 794
                     {
795
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
795
+                        if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
796 796
                         {
797 797
                             $this->trapAction.='Error sending status : check cmd/API';
798 798
                         }
799 799
                         else
800 800
                         {
801
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
801
+                            $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
802 802
                             $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
803 803
                         }
804 804
                     }
805 805
                     else
806 806
                     {
807
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
807
+                        $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
808 808
                     }
809
-                    $this->trapToDb=($action==-2)?false:true;
809
+                    $this->trapToDb=($action == -2) ?false:true;
810 810
                 }
811 811
                 // Put name in source_name
812 812
                 if (!isset($this->trapData['source_name']))
@@ -815,7 +815,7 @@  discard block
 block discarded – undo
815 815
                 }
816 816
                 else
817 817
                 {
818
-                    if (!preg_match('/'.$rule['host_name'].'/',$this->trapData['source_name']))
818
+                    if (!preg_match('/'.$rule['host_name'].'/', $this->trapData['source_name']))
819 819
                     { // only add if not present
820 820
                         $this->trapData['source_name'].=','.$rule['host_name'];
821 821
                     }
@@ -823,13 +823,13 @@  discard block
 block discarded – undo
823 823
             }
824 824
             catch (Exception $e)
825 825
             {
826
-                $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
826
+                $this->logging->log('Error in rule eval : '.$e->getMessage(), WARN, '');
827 827
                 $this->trapAction.=' ERR : '.$e->getMessage();
828 828
                 $this->trapData['status']='error';
829 829
             }
830 830
             
831 831
         }
832
-        if ($this->trapData['status']=='error')
832
+        if ($this->trapData['status'] == 'error')
833 833
         {
834 834
             $this->trapToDb=true; // Always put errors in DB for the use can see
835 835
         }
@@ -845,13 +845,13 @@  discard block
 block discarded – undo
845 845
     public function add_rule_final($time)
846 846
     {
847 847
         $db_conn=$this->trapsDB->db_connect_trap();
848
-        if ($this->trapAction==null)
848
+        if ($this->trapAction == null)
849 849
         {
850 850
             $this->trapAction='No action';
851 851
         }
852 852
         $sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trapAction."'  WHERE (id = '".$this->trapId."');";
853 853
         if ($db_conn->query($sql) === false) {
854
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
854
+            $this->logging->log('Error in update query : '.$sql, WARN, '');
855 855
         }
856 856
     }
857 857
     
@@ -876,12 +876,12 @@  discard block
 block discarded – undo
876 876
                                 WHERE s.current_state != 0;";
877 877
             $db_conn=$this->trapsDB->db_connect_ido();
878 878
             if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
879
-                $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
879
+                $this->logging->log('No result in query : '.$sql_query, ERROR, '');
880 880
                 return 0;
881 881
             }
882 882
             $services=$services_db->fetchAll();
883
-        }else{
884
-            $api = $this->getAPI();
883
+        } else {
884
+            $api=$this->getAPI();
885 885
             $api->setCredentials($this->apiUsername, $this->apiPassword);
886 886
             $services=$api->getNOKservice();
887 887
         }
@@ -890,7 +890,7 @@  discard block
 block discarded – undo
890 890
         $sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
891 891
         $db_conn2=$this->trapsDB->db_connect_trap();
892 892
         if (($rules_db=$db_conn2->query($sql_query)) === false) {
893
-            $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
893
+            $this->logging->log('No result in query : '.$sql_query, ERROR, '');
894 894
             return 0;
895 895
         }
896 896
         $rules=$rules_db->fetchAll();
@@ -900,20 +900,20 @@  discard block
 block discarded – undo
900 900
         $numreset=0;
901 901
         foreach ($rules as $rule)
902 902
         {
903
-            if( is_object( $services ) ) $services=(array)$services;
903
+            if (is_object($services)) $services=(array) $services;
904 904
             foreach ($services as $service)
905 905
             {
906 906
                 if ($service['name'] == $rule['service_name'] &&
907 907
                     $service['host_name'] == $rule['host_name'] &&
908 908
                     ($service['last_check'] + $rule['revert_ok']) < $now)
909 909
                 {
910
-                    $this->serviceCheckResult($service['host_name'],$service['name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
910
+                    $this->serviceCheckResult($service['host_name'], $service['name'], 0, 'Reset service to OK after '.$rule['revert_ok'].' seconds');
911 911
                     $numreset++;
912 912
                 }
913 913
             }
914 914
         }
915 915
         echo "\n";
916
-        echo $numreset . " service(s) reset to OK\n";
916
+        echo $numreset." service(s) reset to OK\n";
917 917
         return 0;
918 918
         
919 919
     }
Please login to merge, or discard this patch.
Braces   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -98,8 +98,7 @@  discard block
 block discarded – undo
98 98
         {
99 99
             $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
100 100
             $this->logSetup=true;
101
-        }
102
-        else
101
+        } else
103 102
         {
104 103
             $this->logSetup=false;
105 104
         }
@@ -130,7 +129,10 @@  discard block
 block discarded – undo
130 129
         $this->getDatabaseOptions(); // Get options in database
131 130
         
132 131
         // Setup API
133
-        if ($this->apiUse === true) $this->getAPI(); // Setup API
132
+        if ($this->apiUse === true) {
133
+        	$this->getAPI();
134
+        }
135
+        // Setup API
134 136
         
135 137
         // Setup MIB
136 138
         $this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
@@ -149,7 +151,7 @@  discard block
 block discarded – undo
149 151
         // Setup Plugins
150 152
         //Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
151 153
         $this->pluginClass = new Plugins($this);
152
-	}catch (Exception $e){ return; }
154
+	} catch (Exception $e){ return; }
153 155
             
154 156
     }
155 157
 
@@ -239,8 +241,7 @@  discard block
 block discarded – undo
239 241
         {
240 242
             $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
241 243
             $this->logging->log('Error parsing IP : '.$IP,ERROR,'');
242
-        }
243
-        else
244
+        } else
244 245
         {
245 246
             $this->trapData['source_ip']=$matches[1];
246 247
             $this->trapData['destination_ip']=$matches[3];
@@ -323,10 +324,10 @@  discard block
 block discarded – undo
323 324
         $this->logging->log('SQL query : '.$sql,DEBUG );
324 325
         if (($ret_code=$db_conn->query($sql)) === false) {
325 326
             $this->logging->log('No result in query : ' . $sql,ERROR,'');
326
-        }
327
-        else {
328
-            if (($name=$ret_code->fetch()) !== false)
329
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
327
+        } else {
328
+            if (($name=$ret_code->fetch()) !== false) {
329
+                            return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
330
+            }
330 331
         }
331 332
         
332 333
         // Also check if it is an instance of OID
@@ -336,10 +337,10 @@  discard block
 block discarded – undo
336 337
         $this->logging->log('SQL query : '.$sql,DEBUG );
337 338
         if (($ret_code=$db_conn->query($sql)) === false) {
338 339
             $this->logging->log('No result in query : ' . $sql,ERROR,'');
339
-        }
340
-        else {
341
-            if (($name=$ret_code->fetch()) !== false)
342
-                return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
340
+        } else {
341
+            if (($name=$ret_code->fetch()) !== false) {
342
+                            return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
343
+            }
343 344
         }
344 345
         
345 346
         // Try to get oid name from snmptranslate
@@ -438,7 +439,9 @@  discard block
 block discarded – undo
438 439
                 }
439 440
                 
440 441
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
441
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
442
+                if ($inserted_id==false) {
443
+                	throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
444
+                }
442 445
                 $this->trapId=$inserted_id;
443 446
                 break;
444 447
             default:
@@ -454,7 +457,9 @@  discard block
 block discarded – undo
454 457
     {
455 458
         
456 459
         // If action is ignore -> don't send t DB
457
-        if ($this->trapToDb === false) return;
460
+        if ($this->trapToDb === false) {
461
+        	return;
462
+        }
458 463
         
459 464
         
460 465
         $db_conn=$this->trapsDB->db_connect_trap();
@@ -511,7 +516,9 @@  discard block
 block discarded – undo
511 516
                 }
512 517
                 
513 518
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
514
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
519
+                if ($inserted_id==false) {
520
+                	throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
521
+                }
515 522
                 $this->trapId=$inserted_id;
516 523
                 break;
517 524
             default:
@@ -592,7 +599,7 @@  discard block
 block discarded – undo
592 599
                         continue;
593 600
                     }
594 601
                     $grouphosts=$ret_code2->fetchAll();
595
-                }else{
602
+                } else{
596 603
                     $api = $this->getAPI();
597 604
                     $api->setCredentials($this->apiUsername, $this->apiPassword);
598 605
                     $grouphosts=$api->getHostsIPByHostGroup($rule['host_group_name']);
@@ -600,7 +607,9 @@  discard block
 block discarded – undo
600 607
                 //echo "rule grp :\n";print_r($grouphosts);echo "\n";
601 608
                 foreach ( $grouphosts as $host)
602 609
                 {
603
-                    if( is_object( $host ) ) $host=(array)$host;
610
+                    if( is_object( $host ) ) {
611
+                    	$host=(array)$host;
612
+                    }
604 613
                     //echo $host['address']."\n";
605 614
                     if ($host['address']==$ip || $host['address6']==$ip)
606 615
                     {
@@ -649,8 +658,7 @@  discard block
 block discarded – undo
649 658
                 // TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
650 659
                 exec('echo "'.$send.'" > ' .$this->icinga2cmd);
651 660
                 return true;
652
-        }
653
-        else
661
+        } else
654 662
         {
655 663
             // Get perfdata if found
656 664
             $matches=array();
@@ -658,8 +666,7 @@  discard block
 block discarded – undo
658 666
             {
659 667
                 $display=$matches[1];
660 668
                 $perfdata=$matches[2];
661
-            }
662
-            else
669
+            } else
663 670
             {
664 671
                 $perfdata='';
665 672
             }
@@ -671,8 +678,7 @@  discard block
 block discarded – undo
671 678
             {
672 679
                 $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
673 680
                 return false;
674
-            }
675
-            else
681
+            } else
676 682
             {
677 683
                 $this->logging->log( "Sent result : " .$retmessage,INFO );
678 684
                 return true;
@@ -771,20 +777,17 @@  discard block
 block discarded – undo
771 777
                         if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
772 778
                         {
773 779
                             $this->trapAction.='Error sending status : check cmd/API';
774
-                        }
775
-                        else
780
+                        } else
776 781
                         {
777 782
                             $this->add_rule_match($rule['id'],$rule['num_match']+1);
778 783
                             $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
779 784
                         }
780
-                    }
781
-                    else
785
+                    } else
782 786
                     {
783 787
                         $this->add_rule_match($rule['id'],$rule['num_match']+1);
784 788
                     }
785 789
                     $this->trapToDb=($action==-2)?false:true;
786
-                }
787
-                else
790
+                } else
788 791
                 {
789 792
                     //$this->logging->log('rules KOO : '.print_r($rule),INFO );
790 793
                     
@@ -795,14 +798,12 @@  discard block
 block discarded – undo
795 798
                         if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
796 799
                         {
797 800
                             $this->trapAction.='Error sending status : check cmd/API';
798
-                        }
799
-                        else
801
+                        } else
800 802
                         {
801 803
                             $this->add_rule_match($rule['id'],$rule['num_match']+1);
802 804
                             $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
803 805
                         }
804
-                    }
805
-                    else
806
+                    } else
806 807
                     {
807 808
                         $this->add_rule_match($rule['id'],$rule['num_match']+1);
808 809
                     }
@@ -812,16 +813,14 @@  discard block
 block discarded – undo
812 813
                 if (!isset($this->trapData['source_name']))
813 814
                 {
814 815
                     $this->trapData['source_name']=$rule['host_name'];
815
-                }
816
-                else
816
+                } else
817 817
                 {
818 818
                     if (!preg_match('/'.$rule['host_name'].'/',$this->trapData['source_name']))
819 819
                     { // only add if not present
820 820
                         $this->trapData['source_name'].=','.$rule['host_name'];
821 821
                     }
822 822
                 }
823
-            }
824
-            catch (Exception $e)
823
+            } catch (Exception $e)
825 824
             {
826 825
                 $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
827 826
                 $this->trapAction.=' ERR : '.$e->getMessage();
@@ -832,8 +831,7 @@  discard block
 block discarded – undo
832 831
         if ($this->trapData['status']=='error')
833 832
         {
834 833
             $this->trapToDb=true; // Always put errors in DB for the use can see
835
-        }
836
-        else
834
+        } else
837 835
         {
838 836
             $this->trapData['status']='done';
839 837
         }
@@ -880,7 +878,7 @@  discard block
 block discarded – undo
880 878
                 return 0;
881 879
             }
882 880
             $services=$services_db->fetchAll();
883
-        }else{
881
+        } else{
884 882
             $api = $this->getAPI();
885 883
             $api->setCredentials($this->apiUsername, $this->apiPassword);
886 884
             $services=$api->getNOKservice();
@@ -900,7 +898,9 @@  discard block
 block discarded – undo
900 898
         $numreset=0;
901 899
         foreach ($rules as $rule)
902 900
         {
903
-            if( is_object( $services ) ) $services=(array)$services;
901
+            if( is_object( $services ) ) {
902
+            	$services=(array)$services;
903
+            }
904 904
             foreach ($services as $service)
905 905
             {
906 906
                 if ($service['name'] == $rule['service_name'] &&
Please login to merge, or discard this patch.