Passed
Push — master ( 6af608...f4805a )
by Patrick
03:21
created
library/Trapdirector/Icinga2Api.php 3 patches
Spacing   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -8,19 +8,19 @@  discard block
 block discarded – undo
8 8
 
9 9
 class Icinga2API 
10 10
 {
11
-    protected $version = 'v1';      //< icinga2 api version
11
+    protected $version='v1'; //< icinga2 api version
12 12
     
13
-    protected $host;                //< icinga2 host name or IP
14
-    protected $port;                //< icinga2 api port
13
+    protected $host; //< icinga2 host name or IP
14
+    protected $port; //< icinga2 api port
15 15
     
16
-    protected $user;                //< user name
17
-    protected $pass;                //< user password
18
-    protected $usercert;            //< user key for certificate auth (NOT IMPLEMENTED)
19
-    protected $authmethod='pass';   //< Authentication : 'pass' or 'cert'
16
+    protected $user; //< user name
17
+    protected $pass; //< user password
18
+    protected $usercert; //< user key for certificate auth (NOT IMPLEMENTED)
19
+    protected $authmethod='pass'; //< Authentication : 'pass' or 'cert'
20 20
 
21 21
     protected $curl;
22 22
     // http://php.net/manual/de/function.json-last-error.php#119985
23
-    protected $errorReference = [
23
+    protected $errorReference=[
24 24
         JSON_ERROR_NONE => 'No error has occurred.',
25 25
         JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
26 26
         JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
         JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
32 32
         JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
33 33
     ];
34
-    const JSON_UNKNOWN_ERROR = 'Unknown error.';
34
+    const JSON_UNKNOWN_ERROR='Unknown error.';
35 35
     
36 36
     /**
37 37
      * Creates Icinga2API object
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
      * @param string $host host name or IP
40 40
      * @param number $port API port
41 41
      */
42
-    public function __construct($host, $port = 5665)
42
+    public function __construct($host, $port=5665)
43 43
     {
44 44
         $this->host=$host;
45 45
         $this->port=$port;
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
      * @param string $user
50 50
      * @param string $pass
51 51
      */
52
-    public function setCredentials($user,$pass)
52
+    public function setCredentials($user, $pass)
53 53
     {
54 54
         $this->user=$user;
55 55
         $this->pass=$pass;
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
      * @param string $user
62 62
      * @param string $usercert
63 63
      */
64
-    public function setCredentialskey($user,$usercert)
64
+    public function setCredentialskey($user, $usercert)
65 65
     {
66 66
         $this->user=$user;
67 67
         $this->usercert=$usercert;
@@ -84,13 +84,13 @@  discard block
 block discarded – undo
84 84
         if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
85 85
         {
86 86
             
87
-            foreach ( $permissions as $mustPermission)
87
+            foreach ($permissions as $mustPermission)
88 88
             {
89 89
                 $curPermOK=0;
90
-                foreach ( $result->results[0]->permissions as $curPermission)
90
+                foreach ($result->results[0]->permissions as $curPermission)
91 91
                 {
92
-                    $curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
93
-                    if (preg_match('#'.$curPermission.'#',$mustPermission))
92
+                    $curPermission=preg_replace('/\*/', '.*', $curPermission); // put * as .* to created a regexp
93
+                    if (preg_match('#'.$curPermission.'#', $mustPermission))
94 94
                     {
95 95
                         $curPermOK=1;
96 96
                         break;
@@ -105,12 +105,12 @@  discard block
 block discarded – undo
105 105
             }
106 106
             if ($permOk == 0)
107 107
             {
108
-                return array(true,'API connection OK, but missing permission : '.$permMissing);
108
+                return array(true, 'API connection OK, but missing permission : '.$permMissing);
109 109
             }
110
-            return array(false,'API connection OK');
110
+            return array(false, 'API connection OK');
111 111
             
112 112
         }
113
-        return array(true,'API connection OK, but cannot get permissions');
113
+        return array(true, 'API connection OK, but cannot get permissions');
114 114
     }
115 115
     
116 116
     
@@ -125,9 +125,9 @@  discard block
 block discarded – undo
125 125
      */
126 126
     protected function curl() {
127 127
         if ($this->curl === null) {
128
-            $this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
128
+            $this->curl=curl_init(sprintf('https://%s:%d', $this->host, $this->port));
129 129
             if (!$this->curl) {
130
-                throw new Exception('CURL INIT ERROR: ' . curl_error($this->curl));
130
+                throw new Exception('CURL INIT ERROR: '.curl_error($this->curl));
131 131
             }
132 132
         }
133 133
         return $this->curl;
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
      * @param string $display : service passive check output
142 142
      * @return array (status = true (oK) or false (nok), string message)
143 143
      */
144
-    public function serviceCheckResult($host,$service,$state,$display)
144
+    public function serviceCheckResult($host, $service, $state, $display)
145 145
     {
146 146
         //Send a POST request to the URL endpoint /v1/actions/process-check-result
147 147
         //actions/process-check-result?service=example.localdomain!passive-ping6
@@ -159,9 +159,9 @@  discard block
 block discarded – undo
159 159
         {
160 160
             return array(false, $e->getMessage());
161 161
         }
162
-        if (property_exists($result,'error') )
162
+        if (property_exists($result, 'error'))
163 163
         {
164
-            if (property_exists($result,'status'))
164
+            if (property_exists($result, 'status'))
165 165
             {
166 166
                 $message=$result->status;
167 167
             }
@@ -169,21 +169,21 @@  discard block
 block discarded – undo
169 169
             {
170 170
                 $message="Unkown status";
171 171
             }
172
-            return array(false , 'Ret code ' .$result->error.' : '.$message);
172
+            return array(false, 'Ret code '.$result->error.' : '.$message);
173 173
         }
174 174
         if (property_exists($result, 'results'))
175 175
         {
176 176
             if (isset($result->results[0]))
177 177
             {
178
-                return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
178
+                return array(true, 'code '.$result->results[0]->code.' : '.$result->results[0]->status);
179 179
             }
180 180
             else
181 181
             {
182
-                return array(false,'Service not found');
182
+                return array(false, 'Service not found');
183 183
             }
184 184
             
185 185
         }
186
-        return array(false,'Unkown result, open issue with this : '.print_r($result,true));
186
+        return array(false, 'Unkown result, open issue with this : '.print_r($result, true));
187 187
     }
188 188
  
189 189
     /**
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
         $url='objects/hosts';
205 205
         $body=array(
206 206
             "filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
207
-            "attrs"         => array('__name','name','display_name')
207
+            "attrs"         => array('__name', 'name', 'display_name')
208 208
         );
209 209
         try
210 210
         {
@@ -214,24 +214,24 @@  discard block
 block discarded – undo
214 214
             throw new Exception($e->getMessage());
215 215
         }
216 216
         
217
-        if (property_exists($result,'error') )
217
+        if (property_exists($result, 'error'))
218 218
         {
219
-            if (property_exists($result,'status'))
219
+            if (property_exists($result, 'status'))
220 220
             {
221
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
221
+                throw new Exception('Ret code '.$result->error.' : '.$result->status);
222 222
             }
223 223
             else
224 224
             {
225
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
225
+                throw new Exception('Ret code '.$result->error.' : Unkown status');
226 226
             }
227 227
         }
228 228
         if (property_exists($result, 'results'))
229 229
         {
230 230
             $numHost=0;
231 231
             $hostArray=array();
232
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
232
+            while (isset($result->results[$numHost]) && property_exists($result->results[$numHost], 'attrs'))
233 233
             {
234
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
234
+                $hostArray[$numHost]=$result->results[$numHost]->attrs;
235 235
                 $numHost++;
236 236
             }
237 237
             return $hostArray;            
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
         $url='objects/hosts';
251 251
         $body=array(
252 252
             "filter"        => '\"'.$hostGroup.'\" in host.groups',
253
-            "attrs"         => array('address','address','name')
253
+            "attrs"         => array('address', 'address', 'name')
254 254
         );
255 255
         try
256 256
         {
@@ -260,25 +260,25 @@  discard block
 block discarded – undo
260 260
             throw new Exception($e->getMessage());
261 261
         }
262 262
         
263
-        if (property_exists($result,'error') )
263
+        if (property_exists($result, 'error'))
264 264
         {
265
-            if (property_exists($result,'status'))
265
+            if (property_exists($result, 'status'))
266 266
             {
267
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
267
+                throw new Exception('Ret code '.$result->error.' : '.$result->status);
268 268
             }
269 269
             else
270 270
             {
271
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
271
+                throw new Exception('Ret code '.$result->error.' : Unkown status');
272 272
             }
273 273
         }
274 274
         if (property_exists($result, 'results'))
275 275
         {
276 276
             $numHost=0;
277 277
             $hostArray=array();
278
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
278
+            while (isset($result->results[$numHost]) && property_exists($result->results[$numHost], 'attrs'))
279 279
             {
280
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
281
-                $hostArray[$numHost]->name = $result->results[$numHost]->name;
280
+                $hostArray[$numHost]=$result->results[$numHost]->attrs;
281
+                $hostArray[$numHost]->name=$result->results[$numHost]->name;
282 282
                 $numHost++;
283 283
             }
284 284
             return $hostArray;
@@ -296,23 +296,23 @@  discard block
 block discarded – undo
296 296
      * @return array
297 297
      */
298 298
     public function request($method, $url, $headers, $body) {
299
-        $auth = sprintf('%s:%s', $this->user, $this->pass);
300
-        $curlHeaders = array("Accept: application/json");
299
+        $auth=sprintf('%s:%s', $this->user, $this->pass);
300
+        $curlHeaders=array("Accept: application/json");
301 301
         if ($body !== null) {
302
-            $body = json_encode($body);
302
+            $body=json_encode($body);
303 303
             array_push($curlHeaders, 'Content-Type: application/json');
304 304
             //array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
305 305
         }
306 306
         //var_dump($body);
307 307
         //var_dump($this->url($url));
308 308
         if ($headers !== null) {
309
-            $curlFinalHeaders = array_merge($curlHeaders, $headers);
309
+            $curlFinalHeaders=array_merge($curlHeaders, $headers);
310 310
         } else 
311 311
         {
312 312
             $curlFinalHeaders=$curlHeaders;
313 313
         }
314
-        $curl = $this->curl();
315
-        $opts = array(
314
+        $curl=$this->curl();
315
+        $opts=array(
316 316
             CURLOPT_URL		=> $this->url($url),
317 317
             CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
318 318
             CURLOPT_USERPWD		=> $auth,
@@ -323,14 +323,14 @@  discard block
 block discarded – undo
323 323
             CURLOPT_SSL_VERIFYPEER 	=> false,
324 324
         );
325 325
         if ($body !== null) {
326
-            $opts[CURLOPT_POSTFIELDS] = $body;
326
+            $opts[CURLOPT_POSTFIELDS]=$body;
327 327
         }
328 328
         curl_setopt_array($curl, $opts);
329
-        $res = curl_exec($curl);
329
+        $res=curl_exec($curl);
330 330
         if ($res === false) {
331
-            throw new Exception('CURL ERROR: ' . curl_error($curl));
331
+            throw new Exception('CURL ERROR: '.curl_error($curl));
332 332
         }
333
-        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
333
+        $statusCode=curl_getinfo($curl, CURLINFO_HTTP_CODE);
334 334
         if ($statusCode === 401) {
335 335
             throw new Exception('Unable to authenticate, please check your API credentials');
336 336
         }
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
      * @return array json decoded
345 345
      */
346 346
     protected function fromJsonResult($json) {
347
-        $result = @json_decode($json);
347
+        $result=@json_decode($json);
348 348
         //var_dump($json);
349 349
         if ($result === null) {
350 350
             throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
Please login to merge, or discard this patch.
Indentation   +330 added lines, -330 removed lines patch added patch discarded remove patch
@@ -8,361 +8,361 @@
 block discarded – undo
8 8
 
9 9
 class Icinga2API 
10 10
 {
11
-    protected $version = 'v1';      //< icinga2 api version
11
+	protected $version = 'v1';      //< icinga2 api version
12 12
     
13
-    protected $host;                //< icinga2 host name or IP
14
-    protected $port;                //< icinga2 api port
13
+	protected $host;                //< icinga2 host name or IP
14
+	protected $port;                //< icinga2 api port
15 15
     
16
-    protected $user;                //< user name
17
-    protected $pass;                //< user password
18
-    protected $usercert;            //< user key for certificate auth (NOT IMPLEMENTED)
19
-    protected $authmethod='pass';   //< Authentication : 'pass' or 'cert'
16
+	protected $user;                //< user name
17
+	protected $pass;                //< user password
18
+	protected $usercert;            //< user key for certificate auth (NOT IMPLEMENTED)
19
+	protected $authmethod='pass';   //< Authentication : 'pass' or 'cert'
20 20
 
21
-    protected $curl;
22
-    // http://php.net/manual/de/function.json-last-error.php#119985
23
-    protected $errorReference = [
24
-        JSON_ERROR_NONE => 'No error has occurred.',
25
-        JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
26
-        JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
27
-        JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded.',
28
-        JSON_ERROR_SYNTAX => 'Syntax error.',
29
-        JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded.',
30
-        JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded.',
31
-        JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
32
-        JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
33
-    ];
34
-    const JSON_UNKNOWN_ERROR = 'Unknown error.';
21
+	protected $curl;
22
+	// http://php.net/manual/de/function.json-last-error.php#119985
23
+	protected $errorReference = [
24
+		JSON_ERROR_NONE => 'No error has occurred.',
25
+		JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
26
+		JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
27
+		JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded.',
28
+		JSON_ERROR_SYNTAX => 'Syntax error.',
29
+		JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded.',
30
+		JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded.',
31
+		JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
32
+		JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
33
+	];
34
+	const JSON_UNKNOWN_ERROR = 'Unknown error.';
35 35
     
36
-    /**
37
-     * Creates Icinga2API object
38
-     * 
39
-     * @param string $host host name or IP
40
-     * @param number $port API port
41
-     */
42
-    public function __construct($host, $port = 5665)
43
-    {
44
-        $this->host=$host;
45
-        $this->port=$port;
46
-    }
47
-    /**
48
-     * Set user & pass
49
-     * @param string $user
50
-     * @param string $pass
51
-     */
52
-    public function setCredentials($user,$pass)
53
-    {
54
-        $this->user=$user;
55
-        $this->pass=$pass;
56
-        $this->authmethod='pass';
57
-    }
36
+	/**
37
+	 * Creates Icinga2API object
38
+	 * 
39
+	 * @param string $host host name or IP
40
+	 * @param number $port API port
41
+	 */
42
+	public function __construct($host, $port = 5665)
43
+	{
44
+		$this->host=$host;
45
+		$this->port=$port;
46
+	}
47
+	/**
48
+	 * Set user & pass
49
+	 * @param string $user
50
+	 * @param string $pass
51
+	 */
52
+	public function setCredentials($user,$pass)
53
+	{
54
+		$this->user=$user;
55
+		$this->pass=$pass;
56
+		$this->authmethod='pass';
57
+	}
58 58
     
59
-    /**
60
-     * Set user & certificate (NOT IMPLEMENTED @throws RuntimeException)
61
-     * @param string $user
62
-     * @param string $usercert
63
-     */
64
-    public function setCredentialskey($user,$usercert)
65
-    {
66
-        $this->user=$user;
67
-        $this->usercert=$usercert;
68
-        $this->authmethod='cert';
69
-        throw new RuntimeException('Certificate auth not implemented');
70
-    }
59
+	/**
60
+	 * Set user & certificate (NOT IMPLEMENTED @throws RuntimeException)
61
+	 * @param string $user
62
+	 * @param string $usercert
63
+	 */
64
+	public function setCredentialskey($user,$usercert)
65
+	{
66
+		$this->user=$user;
67
+		$this->usercert=$usercert;
68
+		$this->authmethod='cert';
69
+		throw new RuntimeException('Certificate auth not implemented');
70
+	}
71 71
 
72
-    public function test(array $permissions)
73
-    {
74
-       try
75
-        {
76
-            $result=$this->request('GET', "", NULL, NULL);
77
-        } 
78
-        catch (Exception $e)
79
-        {
80
-            return array(true, 'Error with API : '.$e->getMessage());
81
-        }
82
-        //var_dump($result);
83
-        $permOk=1;
84
-        $permMissing='';
85
-        if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
86
-        {
72
+	public function test(array $permissions)
73
+	{
74
+	   try
75
+		{
76
+			$result=$this->request('GET', "", NULL, NULL);
77
+		} 
78
+		catch (Exception $e)
79
+		{
80
+			return array(true, 'Error with API : '.$e->getMessage());
81
+		}
82
+		//var_dump($result);
83
+		$permOk=1;
84
+		$permMissing='';
85
+		if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
86
+		{
87 87
             
88
-            foreach ( $permissions as $mustPermission)
89
-            {
90
-                $curPermOK=0;
91
-                foreach ( $result->results[0]->permissions as $curPermission)
92
-                {
93
-                    $curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
94
-                    if (preg_match('#'.$curPermission.'#',$mustPermission))
95
-                    {
96
-                        $curPermOK=1;
97
-                        break;
98
-                    }
99
-                }
100
-                if ($curPermOK == 0)
101
-                {
102
-                    $permOk=0;
103
-                    $permMissing=$mustPermission;
104
-                    break;
105
-                }
106
-            }
107
-            if ($permOk == 0)
108
-            {
109
-                return array(true,'API connection OK, but missing permission : '.$permMissing);
110
-            }
111
-            return array(false,'API connection OK');
88
+			foreach ( $permissions as $mustPermission)
89
+			{
90
+				$curPermOK=0;
91
+				foreach ( $result->results[0]->permissions as $curPermission)
92
+				{
93
+					$curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
94
+					if (preg_match('#'.$curPermission.'#',$mustPermission))
95
+					{
96
+						$curPermOK=1;
97
+						break;
98
+					}
99
+				}
100
+				if ($curPermOK == 0)
101
+				{
102
+					$permOk=0;
103
+					$permMissing=$mustPermission;
104
+					break;
105
+				}
106
+			}
107
+			if ($permOk == 0)
108
+			{
109
+				return array(true,'API connection OK, but missing permission : '.$permMissing);
110
+			}
111
+			return array(false,'API connection OK');
112 112
             
113
-        }
114
-        return array(true,'API connection OK, but cannot get permissions');
115
-    }
113
+		}
114
+		return array(true,'API connection OK, but cannot get permissions');
115
+	}
116 116
     
117 117
     
118
-    protected function url($url) {
119
-        return sprintf('https://%s:%d/%s/%s', $this->host, $this->port, $this->version, $url);
120
-    }
118
+	protected function url($url) {
119
+		return sprintf('https://%s:%d/%s/%s', $this->host, $this->port, $this->version, $url);
120
+	}
121 121
     
122
-    /**
123
-     * Create or return curl ressource
124
-     * @throws Exception
125
-     * @return resource
126
-     */
127
-    protected function curl() {
128
-        if ($this->curl === null) {
129
-            $this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
130
-            if (!$this->curl) {
131
-                throw new Exception('CURL INIT ERROR: ' . curl_error($this->curl));
132
-            }
133
-        }
134
-        return $this->curl;
135
-    }
122
+	/**
123
+	 * Create or return curl ressource
124
+	 * @throws Exception
125
+	 * @return resource
126
+	 */
127
+	protected function curl() {
128
+		if ($this->curl === null) {
129
+			$this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
130
+			if (!$this->curl) {
131
+				throw new Exception('CURL INIT ERROR: ' . curl_error($this->curl));
132
+			}
133
+		}
134
+		return $this->curl;
135
+	}
136 136
 
137
-    /**
138
-     * Send a passive service check
139
-     * @param string $host : host name 
140
-     * @param string $service : service name
141
-     * @param int $state : state of service
142
-     * @param string $display : service passive check output
143
-     * @return array (status = true (oK) or false (nok), string message)
144
-     */
145
-    public function serviceCheckResult($host,$service,$state,$display)
146
-    {
147
-        //Send a POST request to the URL endpoint /v1/actions/process-check-result
148
-        //actions/process-check-result?service=example.localdomain!passive-ping6
149
-        $url='actions/process-check-result';
150
-        $body=array(
151
-            "filter"        => 'service.name=="'.$service.'" && service.host_name=="'.$host.'"',
152
-            'type'          => 'Service',
153
-            "exit_status"   => $state,
154
-            "plugin_output" => $display
155
-        );
156
-        try 
157
-        {
158
-            $result=$this->request('POST', $url, null, $body);
159
-        } catch (Exception $e) 
160
-        {
161
-            return array(false, $e->getMessage());
162
-        }
163
-        if (property_exists($result,'error') )
164
-        {
165
-            if (property_exists($result,'status'))
166
-            {
167
-                $message=$result->status;
168
-            }
169
-            else 
170
-            {
171
-                $message="Unkown status";
172
-            }
173
-            return array(false , 'Ret code ' .$result->error.' : '.$message);
174
-        }
175
-        if (property_exists($result, 'results'))
176
-        {
177
-            if (isset($result->results[0]))
178
-            {
179
-                return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
180
-            }
181
-            else
182
-            {
183
-                return array(false,'Service not found');
184
-            }
137
+	/**
138
+	 * Send a passive service check
139
+	 * @param string $host : host name 
140
+	 * @param string $service : service name
141
+	 * @param int $state : state of service
142
+	 * @param string $display : service passive check output
143
+	 * @return array (status = true (oK) or false (nok), string message)
144
+	 */
145
+	public function serviceCheckResult($host,$service,$state,$display)
146
+	{
147
+		//Send a POST request to the URL endpoint /v1/actions/process-check-result
148
+		//actions/process-check-result?service=example.localdomain!passive-ping6
149
+		$url='actions/process-check-result';
150
+		$body=array(
151
+			"filter"        => 'service.name=="'.$service.'" && service.host_name=="'.$host.'"',
152
+			'type'          => 'Service',
153
+			"exit_status"   => $state,
154
+			"plugin_output" => $display
155
+		);
156
+		try 
157
+		{
158
+			$result=$this->request('POST', $url, null, $body);
159
+		} catch (Exception $e) 
160
+		{
161
+			return array(false, $e->getMessage());
162
+		}
163
+		if (property_exists($result,'error') )
164
+		{
165
+			if (property_exists($result,'status'))
166
+			{
167
+				$message=$result->status;
168
+			}
169
+			else 
170
+			{
171
+				$message="Unkown status";
172
+			}
173
+			return array(false , 'Ret code ' .$result->error.' : '.$message);
174
+		}
175
+		if (property_exists($result, 'results'))
176
+		{
177
+			if (isset($result->results[0]))
178
+			{
179
+				return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
180
+			}
181
+			else
182
+			{
183
+				return array(false,'Service not found');
184
+			}
185 185
             
186
-        }
187
-        return array(false,'Unkown result, open issue with this : '.print_r($result,true));
188
-    }
186
+		}
187
+		return array(false,'Unkown result, open issue with this : '.print_r($result,true));
188
+	}
189 189
  
190
-    /**
191
-     * return array of host by IP (4 or 6)
192
-     * @param string $ip
193
-     * @throws Exception
194
-     * @return array objects : array('__name','name','display_name')
195
-     */
196
-    public function getHostByIP($ip) 
197
-    {
198
-        /*
190
+	/**
191
+	 * return array of host by IP (4 or 6)
192
+	 * @param string $ip
193
+	 * @throws Exception
194
+	 * @return array objects : array('__name','name','display_name')
195
+	 */
196
+	public function getHostByIP($ip) 
197
+	{
198
+		/*
199 199
          *  curl -k -s -u  trapdirector:trapdirector -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts' 
200 200
          *  -d '{"filter":"host.group==\"test_trap\"","attrs": ["address" ,"address6"]}'
201 201
             
202 202
             {"results":[{"attrs":{"__name":"Icinga host","address":"127.0.0.1","display_name":"Icinga host","name":"Icinga host"},"joins":{},"meta":{},"name":"Icinga host","type":"Host"}]}
203 203
          */
204 204
         
205
-        $url='objects/hosts';
206
-        $body=array(
207
-            "filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
208
-            "attrs"         => array('__name','name','display_name')
209
-        );
210
-        try
211
-        {
212
-            $result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
213
-        } catch (Exception $e)
214
-        {
215
-            throw new Exception($e->getMessage());
216
-        }
205
+		$url='objects/hosts';
206
+		$body=array(
207
+			"filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
208
+			"attrs"         => array('__name','name','display_name')
209
+		);
210
+		try
211
+		{
212
+			$result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
213
+		} catch (Exception $e)
214
+		{
215
+			throw new Exception($e->getMessage());
216
+		}
217 217
         
218
-        if (property_exists($result,'error') )
219
-        {
220
-            if (property_exists($result,'status'))
221
-            {
222
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
223
-            }
224
-            else
225
-            {
226
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
227
-            }
228
-        }
229
-        if (property_exists($result, 'results'))
230
-        {
231
-            $numHost=0;
232
-            $hostArray=array();
233
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
234
-            {
235
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
236
-                $numHost++;
237
-            }
238
-            return $hostArray;            
239
-        }
240
-        throw new Exception('Unkown result');
241
-    }
218
+		if (property_exists($result,'error') )
219
+		{
220
+			if (property_exists($result,'status'))
221
+			{
222
+				throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
223
+			}
224
+			else
225
+			{
226
+				throw new Exception('Ret code ' .$result->error.' : Unkown status');
227
+			}
228
+		}
229
+		if (property_exists($result, 'results'))
230
+		{
231
+			$numHost=0;
232
+			$hostArray=array();
233
+			while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
234
+			{
235
+				$hostArray[$numHost] = $result->results[$numHost]->attrs;
236
+				$numHost++;
237
+			}
238
+			return $hostArray;            
239
+		}
240
+		throw new Exception('Unkown result');
241
+	}
242 242
 
243
-    /**
244
-     * Get all host and IP from hostgroup
245
-     * @param string $hostGroup
246
-     * @throws Exception
247
-     * @return array : attributes : address, address6, name
248
-     */
249
-    public function getHostsIPByHostGroup($hostGroup)
250
-    {        
251
-        $url='objects/hosts';
252
-        $body=array(
253
-            "filter"        => '\"'.$hostGroup.'\" in host.groups',
254
-            "attrs"         => array('address','address','name')
255
-        );
256
-        try
257
-        {
258
-            $result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
259
-        } catch (Exception $e)
260
-        {
261
-            throw new Exception($e->getMessage());
262
-        }
243
+	/**
244
+	 * Get all host and IP from hostgroup
245
+	 * @param string $hostGroup
246
+	 * @throws Exception
247
+	 * @return array : attributes : address, address6, name
248
+	 */
249
+	public function getHostsIPByHostGroup($hostGroup)
250
+	{        
251
+		$url='objects/hosts';
252
+		$body=array(
253
+			"filter"        => '\"'.$hostGroup.'\" in host.groups',
254
+			"attrs"         => array('address','address','name')
255
+		);
256
+		try
257
+		{
258
+			$result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
259
+		} catch (Exception $e)
260
+		{
261
+			throw new Exception($e->getMessage());
262
+		}
263 263
         
264
-        if (property_exists($result,'error') )
265
-        {
266
-            if (property_exists($result,'status'))
267
-            {
268
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
269
-            }
270
-            else
271
-            {
272
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
273
-            }
274
-        }
275
-        if (property_exists($result, 'results'))
276
-        {
277
-            $numHost=0;
278
-            $hostArray=array();
279
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
280
-            {
281
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
282
-                $hostArray[$numHost]->name = $result->results[$numHost]->name;
283
-                $numHost++;
284
-            }
285
-            return $hostArray;
286
-        }
287
-        throw new Exception('Unkown result');
288
-    }
264
+		if (property_exists($result,'error') )
265
+		{
266
+			if (property_exists($result,'status'))
267
+			{
268
+				throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
269
+			}
270
+			else
271
+			{
272
+				throw new Exception('Ret code ' .$result->error.' : Unkown status');
273
+			}
274
+		}
275
+		if (property_exists($result, 'results'))
276
+		{
277
+			$numHost=0;
278
+			$hostArray=array();
279
+			while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
280
+			{
281
+				$hostArray[$numHost] = $result->results[$numHost]->attrs;
282
+				$hostArray[$numHost]->name = $result->results[$numHost]->name;
283
+				$numHost++;
284
+			}
285
+			return $hostArray;
286
+		}
287
+		throw new Exception('Unkown result');
288
+	}
289 289
     
290
-    /**
291
-     * Send request to API
292
-     * @param string $method get/post/...
293
-     * @param string $url (after /v1/ )
294
-     * @param array $headers
295
-     * @param array $body 
296
-     * @throws Exception
297
-     * @return array
298
-     */
299
-    public function request($method, $url, $headers, $body) {
300
-        $auth = sprintf('%s:%s', $this->user, $this->pass);
301
-        $curlHeaders = array("Accept: application/json");
302
-        if ($body !== null) {
303
-            $body = json_encode($body);
304
-            array_push($curlHeaders, 'Content-Type: application/json');
305
-            //array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
306
-        }
307
-        //var_dump($body);
308
-        //var_dump($this->url($url));
309
-        if ($headers !== null) {
310
-            $curlFinalHeaders = array_merge($curlHeaders, $headers);
311
-        } else 
312
-        {
313
-            $curlFinalHeaders=$curlHeaders;
314
-        }
315
-        $curl = $this->curl();
316
-        $opts = array(
317
-            CURLOPT_URL		=> $this->url($url),
318
-            CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
319
-            CURLOPT_USERPWD		=> $auth,
320
-            CURLOPT_CUSTOMREQUEST	=> strtoupper($method),
321
-            CURLOPT_RETURNTRANSFER 	=> true,
322
-            CURLOPT_CONNECTTIMEOUT 	=> 10,
323
-            CURLOPT_SSL_VERIFYHOST 	=> false,
324
-            CURLOPT_SSL_VERIFYPEER 	=> false,
325
-        );
326
-        if ($body !== null) {
327
-            $opts[CURLOPT_POSTFIELDS] = $body;
328
-        }
329
-        curl_setopt_array($curl, $opts);
330
-        $res = curl_exec($curl);
331
-        if ($res === false) {
332
-            throw new Exception('CURL ERROR: ' . curl_error($curl));
333
-        }
334
-        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
335
-        if ($statusCode === 401) {
336
-            throw new Exception('Unable to authenticate, please check your API credentials');
337
-        }
338
-        return $this->fromJsonResult($res);
339
-    }
290
+	/**
291
+	 * Send request to API
292
+	 * @param string $method get/post/...
293
+	 * @param string $url (after /v1/ )
294
+	 * @param array $headers
295
+	 * @param array $body 
296
+	 * @throws Exception
297
+	 * @return array
298
+	 */
299
+	public function request($method, $url, $headers, $body) {
300
+		$auth = sprintf('%s:%s', $this->user, $this->pass);
301
+		$curlHeaders = array("Accept: application/json");
302
+		if ($body !== null) {
303
+			$body = json_encode($body);
304
+			array_push($curlHeaders, 'Content-Type: application/json');
305
+			//array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
306
+		}
307
+		//var_dump($body);
308
+		//var_dump($this->url($url));
309
+		if ($headers !== null) {
310
+			$curlFinalHeaders = array_merge($curlHeaders, $headers);
311
+		} else 
312
+		{
313
+			$curlFinalHeaders=$curlHeaders;
314
+		}
315
+		$curl = $this->curl();
316
+		$opts = array(
317
+			CURLOPT_URL		=> $this->url($url),
318
+			CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
319
+			CURLOPT_USERPWD		=> $auth,
320
+			CURLOPT_CUSTOMREQUEST	=> strtoupper($method),
321
+			CURLOPT_RETURNTRANSFER 	=> true,
322
+			CURLOPT_CONNECTTIMEOUT 	=> 10,
323
+			CURLOPT_SSL_VERIFYHOST 	=> false,
324
+			CURLOPT_SSL_VERIFYPEER 	=> false,
325
+		);
326
+		if ($body !== null) {
327
+			$opts[CURLOPT_POSTFIELDS] = $body;
328
+		}
329
+		curl_setopt_array($curl, $opts);
330
+		$res = curl_exec($curl);
331
+		if ($res === false) {
332
+			throw new Exception('CURL ERROR: ' . curl_error($curl));
333
+		}
334
+		$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
335
+		if ($statusCode === 401) {
336
+			throw new Exception('Unable to authenticate, please check your API credentials');
337
+		}
338
+		return $this->fromJsonResult($res);
339
+	}
340 340
     
341
-    /**
342
-     * 
343
-     * @param string $json json encoded 
344
-     * @throws Exception
345
-     * @return array json decoded
346
-     */
347
-    protected function fromJsonResult($json) {
348
-        $result = @json_decode($json);
349
-        //var_dump($json);
350
-        if ($result === null) {
351
-            throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
352
-        }
353
-        return $result;
354
-    }
341
+	/**
342
+	 * 
343
+	 * @param string $json json encoded 
344
+	 * @throws Exception
345
+	 * @return array json decoded
346
+	 */
347
+	protected function fromJsonResult($json) {
348
+		$result = @json_decode($json);
349
+		//var_dump($json);
350
+		if ($result === null) {
351
+			throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
352
+		}
353
+		return $result;
354
+	}
355 355
     
356
-    /**
357
-     * Return text error no json error
358
-     * @param string $errorCode
359
-     * @return string
360
-     */
361
-    protected function getLastJsonErrorMessage($errorCode) {
362
-        if (!array_key_exists($errorCode, $this->errorReference)) {
363
-            return self::JSON_UNKNOWN_ERROR;
364
-        }
365
-        return $this->errorReference[$errorCode];
366
-    }
356
+	/**
357
+	 * Return text error no json error
358
+	 * @param string $errorCode
359
+	 * @return string
360
+	 */
361
+	protected function getLastJsonErrorMessage($errorCode) {
362
+		if (!array_key_exists($errorCode, $this->errorReference)) {
363
+			return self::JSON_UNKNOWN_ERROR;
364
+		}
365
+		return $this->errorReference[$errorCode];
366
+	}
367 367
 }
368 368
 
Please login to merge, or discard this patch.
Braces   +5 added lines, -10 removed lines patch added patch discarded remove patch
@@ -74,8 +74,7 @@  discard block
 block discarded – undo
74 74
        try
75 75
         {
76 76
             $result=$this->request('GET', "", NULL, NULL);
77
-        } 
78
-        catch (Exception $e)
77
+        } catch (Exception $e)
79 78
         {
80 79
             return array(true, 'Error with API : '.$e->getMessage());
81 80
         }
@@ -165,8 +164,7 @@  discard block
 block discarded – undo
165 164
             if (property_exists($result,'status'))
166 165
             {
167 166
                 $message=$result->status;
168
-            }
169
-            else 
167
+            } else 
170 168
             {
171 169
                 $message="Unkown status";
172 170
             }
@@ -177,8 +175,7 @@  discard block
 block discarded – undo
177 175
             if (isset($result->results[0]))
178 176
             {
179 177
                 return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
180
-            }
181
-            else
178
+            } else
182 179
             {
183 180
                 return array(false,'Service not found');
184 181
             }
@@ -220,8 +217,7 @@  discard block
 block discarded – undo
220 217
             if (property_exists($result,'status'))
221 218
             {
222 219
                 throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
223
-            }
224
-            else
220
+            } else
225 221
             {
226 222
                 throw new Exception('Ret code ' .$result->error.' : Unkown status');
227 223
             }
@@ -266,8 +262,7 @@  discard block
 block discarded – undo
266 262
             if (property_exists($result,'status'))
267 263
             {
268 264
                 throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
269
-            }
270
-            else
265
+            } else
271 266
             {
272 267
                 throw new Exception('Ret code ' .$result->error.' : Unkown status');
273 268
             }
Please login to merge, or discard this patch.
library/Trapdirector/Config/TrapModuleConfig.php 2 patches
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -4,9 +4,9 @@  discard block
 block discarded – undo
4 4
 
5 5
 class TrapModuleConfig
6 6
 {
7
-    /********** Database configuration ***********************/
7
+	/********** Database configuration ***********************/
8 8
 	// Database prefix for tables 
9
-    protected $table_prefix; //< Database prefix for tables 	
9
+	protected $table_prefix; //< Database prefix for tables 	
10 10
 	protected $DBConfigDefaults=array(
11 11
 		'db_remove_days' => 60, // number of days before removing traps
12 12
 		'log_destination' => 'syslog', // Log destination for trap handler
@@ -113,27 +113,27 @@  discard block
 block discarded – undo
113 113
 	// Note : must have 'source_ip' and 'last_sent'
114 114
 	public function getTrapHostListDisplayColumns()
115 115
 	{
116
-	    return array(
117
-	        'source_name'  =>  't.source_name',
118
-	        'source_ip'    =>  't.source_ip',
119
-	        'trap_oid'     =>  't.trap_oid',
120
-	        'count'        =>  'count(*)',
121
-	        'last_sent'    =>  'UNIX_TIMESTAMP(max(t.date_received))'
122
-	    );
116
+		return array(
117
+			'source_name'  =>  't.source_name',
118
+			'source_ip'    =>  't.source_ip',
119
+			'trap_oid'     =>  't.trap_oid',
120
+			'count'        =>  'count(*)',
121
+			'last_sent'    =>  'UNIX_TIMESTAMP(max(t.date_received))'
122
+		);
123 123
 	}
124 124
 
125 125
 	public function getTrapHostListSearchColumns()
126 126
 	{
127
-	    return array(); // No search needed on this table
127
+		return array(); // No search needed on this table
128 128
 	}
129 129
 	// Titles display in Trap List table
130 130
 	public function getTrapHostListTitles()
131 131
 	{
132
-	    return array(
133
-	        'trap_oid'		=> 'Trap OID',
134
-	        'count'		    => 'Number of traps received',
135
-	        'last_sent'     => 'Last trap received'
136
-	    );
132
+		return array(
133
+			'trap_oid'		=> 'Trap OID',
134
+			'count'		    => 'Number of traps received',
135
+			'last_sent'     => 'Last trap received'
136
+		);
137 137
 	}
138 138
 	
139 139
 	
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 			'revert_ok'		=> 'r.revert_ok',
189 189
 			'display'		=> 'r.display',
190 190
 			'modified'		=> 'UNIX_TIMESTAMP(r.modified)',
191
-            'modifier'		=> 'r.modifier'
191
+			'modifier'		=> 'r.modifier'
192 192
 		);
193 193
 	}	
194 194
 		
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -14,22 +14,22 @@  discard block
 block discarded – undo
14 14
 		'log_level' => 2, // log level
15 15
 	);
16 16
 	// get default values for dbconfig
17
-	public function getDBConfigDefaults() { return $this->DBConfigDefaults;}
17
+	public function getDBConfigDefaults() { return $this->DBConfigDefaults; }
18 18
 	// Minimum DB version
19
-	static public function getDbMinVersion() { return 2;}	
19
+	static public function getDbMinVersion() { return 2; }	
20 20
 	// Current DB version
21
-	static public function getDbCurVersion() { return 2;}
21
+	static public function getDbCurVersion() { return 2; }
22 22
 
23 23
 	/************ Module configuration **********************/
24 24
 	// Module base path
25 25
 	static public function urlPath() { return 'trapdirector'; }
26
-	static public function getapiUserPermissions() { return array("status", "objects/query/Host", "objects/query/Service" , "actions/process-check-result"); } //< api user permissions required
26
+	static public function getapiUserPermissions() { return array("status", "objects/query/Host", "objects/query/Service", "actions/process-check-result"); } //< api user permissions required
27 27
 	
28 28
 	/*********** Log configuration *************************/
29 29
 	protected $logLevels=array(0=>'No output', 1=>'critical', 2=>'warning', 3=>'trace', 4=>'ALL');
30
-	public function getlogLevels() { return $this->logLevels;}
31
-	protected $logDestinations=array('syslog'=>'syslog','file'=>'file','display'=>'display');
32
-	public function getLogDestinations() { return $this->logDestinations;}
30
+	public function getlogLevels() { return $this->logLevels; }
31
+	protected $logDestinations=array('syslog'=>'syslog', 'file'=>'file', 'display'=>'display');
32
+	public function getLogDestinations() { return $this->logDestinations; }
33 33
 	
34 34
 	function __construct($prefix)
35 35
 	{
@@ -40,29 +40,29 @@  discard block
 block discarded – undo
40 40
 	// DB table name of trap received list : prefix 't'
41 41
 	public function getTrapTableName() 
42 42
 	{ 
43
-		return array('t' => $this->table_prefix . 'received'); 
43
+		return array('t' => $this->table_prefix.'received'); 
44 44
 	}
45 45
 	// DB table name of trap data  list : prefix 'd'
46 46
 	public function getTrapDataTableName() 
47 47
 	{ 
48
-		return array('d' => $this->table_prefix . 'received_data'); 
48
+		return array('d' => $this->table_prefix.'received_data'); 
49 49
 	}	
50 50
 
51 51
 	// DB table name of rules : prefix 'r'
52 52
 	public function getTrapRuleName() 
53 53
 	{ 
54
-		return array('r' => $this->table_prefix . 'rules'); 
54
+		return array('r' => $this->table_prefix.'rules'); 
55 55
 	}		
56 56
 	
57 57
 	// DB table name of db config : prefix 'c'
58 58
 	public function getDbConfigTableName() 
59 59
 	{ 
60
-		return array('c' => $this->table_prefix . 'db_config');
60
+		return array('c' => $this->table_prefix.'db_config');
61 61
 	}
62 62
 	
63 63
 	// Mib cache tables
64
-	public function getMIBCacheTableName() { return $this->table_prefix . 'mib_cache'; }
65
-	public function getMIBCacheTableTrapObjName() { return $this->table_prefix . 'mib_cache_trap_object'; }
64
+	public function getMIBCacheTableName() { return $this->table_prefix.'mib_cache'; }
65
+	public function getMIBCacheTableTrapObjName() { return $this->table_prefix.'mib_cache_trap_object'; }
66 66
 	
67 67
 	
68 68
 	/****************** Database queries *******************/
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 	public function getHandlerListDisplayColumns()
144 144
 	{
145 145
 		return array(
146
-			'host_name'		=> 'r.host_name',//'UNIX_TIMESTAMP(t.date_received)',
146
+			'host_name'		=> 'r.host_name', //'UNIX_TIMESTAMP(t.date_received)',
147 147
 			'host_group_name'=> 'r.host_group_name',
148 148
 			'source_ip'		=> "CASE WHEN r.ip4 IS NULL THEN r.ip6 ELSE r.ip4 END",
149 149
 			'trap_oid'		=> 'r.trap_oid',
@@ -196,32 +196,32 @@  discard block
 block discarded – undo
196 196
 	public function trapDetailQuery()
197 197
 	{
198 198
 		return array(
199
-			'timestamp'			=> array('Date','UNIX_TIMESTAMP(t.date_received)'),
200
-			'source_ip'			=> array('Source IP','t.source_ip'),
201
-			'source_name'		=> array('Source name','t.source_name'),
202
-			'source_port'		=> array('Source port','t.source_port'),
203
-			'destination_ip'	=> array('Destination IP','t.destination_ip'),
204
-			'destination_port'	=> array('Destination port','t.destination_port'),			
205
-			'trap_oid'			=> array('Numeric OID','t.trap_oid'),
206
-			'trap_name'			=> array('Trap name','t.trap_name'),
207
-			'trap_name_mib'		=> array('Trap MIB','t.trap_name_mib'),
208
-			'status'			=> array('Processing status','t.status'),
209
-			'status_detail'		=> array('Status details','t.status_detail'),
210
-			'process_time'		=> array('Trap processing time','t.process_time'),			
199
+			'timestamp'			=> array('Date', 'UNIX_TIMESTAMP(t.date_received)'),
200
+			'source_ip'			=> array('Source IP', 't.source_ip'),
201
+			'source_name'		=> array('Source name', 't.source_name'),
202
+			'source_port'		=> array('Source port', 't.source_port'),
203
+			'destination_ip'	=> array('Destination IP', 't.destination_ip'),
204
+			'destination_port'	=> array('Destination port', 't.destination_port'),			
205
+			'trap_oid'			=> array('Numeric OID', 't.trap_oid'),
206
+			'trap_name'			=> array('Trap name', 't.trap_name'),
207
+			'trap_name_mib'		=> array('Trap MIB', 't.trap_name_mib'),
208
+			'status'			=> array('Processing status', 't.status'),
209
+			'status_detail'		=> array('Status details', 't.status_detail'),
210
+			'process_time'		=> array('Trap processing time', 't.process_time'),			
211 211
 		);
212 212
 	}
213 213
 	// Trap detail : additional data (<key> => <title> <sql select>)
214 214
 	public function trapDataDetailQuery()
215 215
 	{
216 216
 		return array(
217
-			'oid'				=> array('Numeric OID','d.oid'),
218
-			'oid_name'			=> array('Text OID','d.oid_name'),
219
-			'oid_name_mib'		=> array('MIB','d.oid_name_mib'),
220
-			'value'				=> array('Value','d.value'),
217
+			'oid'				=> array('Numeric OID', 'd.oid'),
218
+			'oid_name'			=> array('Text OID', 'd.oid_name'),
219
+			'oid_name_mib'		=> array('MIB', 'd.oid_name_mib'),
220
+			'value'				=> array('Value', 'd.value'),
221 221
 		);
222 222
 	}
223 223
 	// foreign key of trap data table
224
-	public function trapDataFK() { return 'trap_id';}
224
+	public function trapDataFK() { return 'trap_id'; }
225 225
 	
226 226
 	// Max items in a list
227 227
 	public function itemListDisplay() { return 25; }
Please login to merge, or discard this patch.
bin/trap_in.php 3 patches
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -30,15 +30,13 @@
 block discarded – undo
30 30
 
31 31
 	$Trap->add_rule_final(microtime(true) - $time1);
32 32
 	
33
-}
34
-catch (Exception $e) 
33
+} catch (Exception $e) 
35 34
 {
36 35
     if ($Trap == null)
37 36
     {  // Exception in trap creation : log in display & syslog
38 37
         $logging = new Logging();
39 38
         $logging->log("Caught exception creating Trap class",2);
40
-    }
41
-    else
39
+    } else
42 40
     {
43 41
 	   $Trap->trapLog("Exception : ". $e->getMessage(),2,0);
44 42
     }
Please login to merge, or discard this patch.
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -15,13 +15,13 @@  discard block
 block discarded – undo
15 15
 
16 16
 try
17 17
 {
18
-    //$Trap = new Trap($icingaweb2_etc);
19
-    //$Trap = new Trap($icingaweb2_etc,4,'display'); // For debug
20
-    $Trap = new Trap($icingaweb2_etc,4,'syslog'); // For debug
21
-    //$Trap->setLogging(4,'syslog'); 
18
+	//$Trap = new Trap($icingaweb2_etc);
19
+	//$Trap = new Trap($icingaweb2_etc,4,'display'); // For debug
20
+	$Trap = new Trap($icingaweb2_etc,4,'syslog'); // For debug
21
+	//$Trap->setLogging(4,'syslog'); 
22 22
     
23
-    // TODO : tranfer this to reset_trap cli command
24
-    $Trap->eraseOldTraps();
23
+	// TODO : tranfer this to reset_trap cli command
24
+	$Trap->eraseOldTraps();
25 25
 
26 26
 	$Trap->read_trap('php://stdin');
27 27
 
@@ -34,15 +34,15 @@  discard block
 block discarded – undo
34 34
 }
35 35
 catch (Exception $e) 
36 36
 {
37
-    if ($Trap == null)
38
-    {  // Exception in trap creation : log in display & syslog
39
-        $logging = new Logging();
40
-        $logging->log("Caught exception creating Trap class",2);
41
-    }
42
-    else
43
-    {
37
+	if ($Trap == null)
38
+	{  // Exception in trap creation : log in display & syslog
39
+		$logging = new Logging();
40
+		$logging->log("Caught exception creating Trap class",2);
41
+	}
42
+	else
43
+	{
44 44
 	   $Trap->trapLog("Exception : ". $e->getMessage(),2,0);
45
-    }
45
+	}
46 46
 }
47 47
 
48 48
 //end
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 use Trapdirector\Logging;
4 4
 
5 5
 // start
6
-$time1 = microtime(true);
6
+$time1=microtime(true);
7 7
 
8 8
 require_once ('trap_class.php');
9 9
 
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
 {
18 18
     //$Trap = new Trap($icingaweb2_etc);
19 19
     //$Trap = new Trap($icingaweb2_etc,4,'display'); // For debug
20
-    $Trap = new Trap($icingaweb2_etc,4,'syslog'); // For debug
20
+    $Trap=new Trap($icingaweb2_etc, 4, 'syslog'); // For debug
21 21
     //$Trap->setLogging(4,'syslog'); 
22 22
     
23 23
     // TODO : tranfer this to reset_trap cli command
@@ -36,12 +36,12 @@  discard block
 block discarded – undo
36 36
 {
37 37
     if ($Trap == null)
38 38
     {  // Exception in trap creation : log in display & syslog
39
-        $logging = new Logging();
40
-        $logging->log("Caught exception creating Trap class",2);
39
+        $logging=new Logging();
40
+        $logging->log("Caught exception creating Trap class", 2);
41 41
     }
42 42
     else
43 43
     {
44
-	   $Trap->trapLog("Exception : ". $e->getMessage(),2,0);
44
+	   $Trap->trapLog("Exception : ".$e->getMessage(), 2, 0);
45 45
     }
46 46
 }
47 47
 
Please login to merge, or discard this patch.
library/Trapdirector/Config/MIBLoader.php 3 patches
Braces   +12 added lines, -7 removed lines patch added patch discarded remove patch
@@ -94,7 +94,9 @@  discard block
 block discarded – undo
94 94
 					array('id' => 'id'))
95 95
 				->where("oid = '".$trap."'") ;
96 96
 		$id=$dbconn->fetchRow($query);
97
-		if ( ($id == null) || ! property_exists($id,'id') ) return null;
97
+		if ( ($id == null) || ! property_exists($id,'id') ) {
98
+			return null;
99
+		}
98 100
 		
99 101
 		$query=$dbconn->select()
100 102
 		        ->from(
@@ -107,7 +109,9 @@  discard block
 block discarded – undo
107 109
 		            'o.trap_id='.$id->id )
108 110
 		        ->where("o.object_id = c.id");
109 111
 		$listObjects=$dbconn->fetchAll($query);
110
-		if ( count($listObjects)==0 ) return null;
112
+		if ( count($listObjects)==0 ) {
113
+			return null;
114
+		}
111 115
 		
112 116
 		foreach ($listObjects as $val)
113 117
 		{
@@ -128,7 +132,10 @@  discard block
 block discarded – undo
128 132
 	*/
129 133
 	public function translateOID($oid)
130 134
 	{
131
-	    if (!preg_match('/^\./',$oid)) $oid = '.' . $oid; // Add a leading '.'
135
+	    if (!preg_match('/^\./',$oid)) {
136
+	    	$oid = '.' . $oid;
137
+	    }
138
+	    // Add a leading '.'
132 139
 		$retArray=array('oid' => $oid, 'mib' => null, 'name'=>null,'type'=>null);
133 140
 		$dbconn = $this->db->getConnection();
134 141
 
@@ -166,8 +173,7 @@  discard block
 block discarded – undo
166 173
 		{
167 174
 		    $retArray['type']=$matches[1];
168 175
 		    $retArray['type_enum']=$matches[2];
169
-		}
170
-		else
176
+		} else
171 177
 		{
172 178
 			$retArray['type']=$translate;
173 179
 			$retArray['type_enum']='';			
@@ -233,8 +239,7 @@  discard block
 block discarded – undo
233 239
 	    if ($oid===null)
234 240
 	    {
235 241
 	        $where="c.id = '$id'";
236
-	    }
237
-	    else
242
+	    } else
238 243
 	    {
239 244
 	        $where="c.oid = '$oid'";
240 245
 	    }
Please login to merge, or discard this patch.
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -31,10 +31,10 @@  discard block
 block discarded – undo
31 31
 				
32 32
 	}
33 33
 
34
-    /**
35
-     * Get all mibs in db which have at least one trap
36
-     * @return array
37
-     */	
34
+	/**
35
+	 * Get all mibs in db which have at least one trap
36
+	 * @return array
37
+	 */	
38 38
 	
39 39
 	public function getMIBList()
40 40
 	{
@@ -58,9 +58,9 @@  discard block
 block discarded – undo
58 58
 	
59 59
 	
60 60
 	/** Get trap list from a mib 
61
-	*	@param $mib string mib name
62
-	*	@return array : traps
63
-	*/
61
+	 *	@param $mib string mib name
62
+	 *	@return array : traps
63
+	 */
64 64
 	public function getTrapList($mib)
65 65
 	{
66 66
 		$traps=array();
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 		$query=$dbconn->select()
69 69
 				->from(
70 70
 					$this->config->getMIBCacheTableName(),
71
-				    array('name' => 'name', 'oid' => 'oid', 'description' => 'description'))
71
+					array('name' => 'name', 'oid' => 'oid', 'description' => 'description'))
72 72
 				->where("mib = '".$mib."' AND type='21'") ;
73 73
 		$names=$dbconn->fetchAll($query);
74 74
 		foreach ($names as $val)
@@ -79,9 +79,9 @@  discard block
 block discarded – undo
79 79
 	}
80 80
 	
81 81
 	/** Get objects a trap can have
82
-	*	@param int $trap oid of trap
83
-	*	@return array|null : null if trap not found, or array ( <oid> => name/mib/type )
84
-	*/
82
+	 *	@param int $trap oid of trap
83
+	 *	@return array|null : null if trap not found, or array ( <oid> => name/mib/type )
84
+	 */
85 85
 	public function getObjectList($trap)
86 86
 	{
87 87
 		$objects=array();
@@ -97,15 +97,15 @@  discard block
 block discarded – undo
97 97
 		if ( ($id == null) || ! property_exists($id,'id') ) return null;
98 98
 		
99 99
 		$query=$dbconn->select()
100
-		        ->from(
101
-		            array('c' => $this->config->getMIBCacheTableName()),
102
-		            array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
103
-		                'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
104
-		                'description' => 'c.description'))
105
-		        ->join(
106
-		            array('o' => $this->config->getMIBCacheTableTrapObjName()),
107
-		            'o.trap_id='.$id->id )
108
-		        ->where("o.object_id = c.id");
100
+				->from(
101
+					array('c' => $this->config->getMIBCacheTableName()),
102
+					array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
103
+						'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
104
+						'description' => 'c.description'))
105
+				->join(
106
+					array('o' => $this->config->getMIBCacheTableTrapObjName()),
107
+					'o.trap_id='.$id->id )
108
+				->where("o.object_id = c.id");
109 109
 		$listObjects=$dbconn->fetchAll($query);
110 110
 		if ( count($listObjects)==0 ) return null;
111 111
 		
@@ -123,12 +123,12 @@  discard block
 block discarded – undo
123 123
 	}
124 124
 
125 125
 	/** translate oid in MIB::Name 
126
-	*	@param string $oid
127
-	*	@return array|null :  return array with index (oid -> oid, mib -> mib name, name -> oid name, type -> oid type)
128
-	*/
126
+	 *	@param string $oid
127
+	 *	@return array|null :  return array with index (oid -> oid, mib -> mib name, name -> oid name, type -> oid type)
128
+	 */
129 129
 	public function translateOID($oid)
130 130
 	{
131
-	    if (!preg_match('/^\./',$oid)) $oid = '.' . $oid; // Add a leading '.'
131
+		if (!preg_match('/^\./',$oid)) $oid = '.' . $oid; // Add a leading '.'
132 132
 		$retArray=array('oid' => $oid, 'mib' => null, 'name'=>null,'type'=>null);
133 133
 		$dbconn = $this->db->getConnection();
134 134
 
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
 				->from(
137 137
 					array('o' => $this->config->getMIBCacheTableName()),
138 138
 					array('mib'=>'o.mib','name' => 'o.name','type'=>'o.syntax',
139
-					    'type_enum'=>'o.type_enum', 'description'=>'o.description'))
139
+						'type_enum'=>'o.type_enum', 'description'=>'o.description'))
140 140
 				->where('o.oid=\''.$oid.'\'');
141 141
 		$object=$dbconn->fetchRow($query);
142 142
 		if ($object != null) 
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
 		// Try to get oid name from snmptranslate
153 153
 		$matches=array();
154 154
 		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
155
-		    ' '.$oid);
155
+			' '.$oid);
156 156
 		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
157 157
 		if ($ret_code===0 || $ret_code===false) {
158 158
 			return null;
@@ -164,8 +164,8 @@  discard block
 block discarded – undo
164 164
 			" | grep SYNTAX | sed 's/SYNTAX[[:blank:]]*//'");
165 165
 		if (preg_match('/(.*)\{(.*)\}/',$translate,$matches))
166 166
 		{
167
-		    $retArray['type']=$matches[1];
168
-		    $retArray['type_enum']=$matches[2];
167
+			$retArray['type']=$matches[1];
168
+			$retArray['type_enum']=$matches[2];
169 169
 		}
170 170
 		else
171 171
 		{
@@ -229,25 +229,25 @@  discard block
 block discarded – undo
229 229
 	 */
230 230
 	public function getTrapDetails($oid=null,$id=null)
231 231
 	{	    
232
-	    // Get trap id in DB
233
-	    if ($oid===null)
234
-	    {
235
-	        $where="c.id = '$id'";
236
-	    }
237
-	    else
238
-	    {
239
-	        $where="c.oid = '$oid'";
240
-	    }
241
-	    $query=$this->db->getConnection()->select()
242
-           ->from(
243
-            array('c' => $this->config->getMIBCacheTableName()),
244
-            array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
245
-                'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
246
-                'description' => 'c.description'))
247
-            ->where($where);
248
-        $trap=$this->db->getConnection()->fetchRow($query);
232
+		// Get trap id in DB
233
+		if ($oid===null)
234
+		{
235
+			$where="c.id = '$id'";
236
+		}
237
+		else
238
+		{
239
+			$where="c.oid = '$oid'";
240
+		}
241
+		$query=$this->db->getConnection()->select()
242
+		   ->from(
243
+			array('c' => $this->config->getMIBCacheTableName()),
244
+			array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
245
+				'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
246
+				'description' => 'c.description'))
247
+			->where($where);
248
+		$trap=$this->db->getConnection()->fetchRow($query);
249 249
         
250
-        return $trap;
250
+		return $trap;
251 251
 	}
252 252
 	
253 253
 }
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
 	 * @param string $db current database
22 22
 	 * @param TrapModuleConfig $config TrapModuleConfig class instance
23 23
 	 */
24
-	public function __construct($snmptranslate,$snmptranslate_dirs,$db,$config)
24
+	public function __construct($snmptranslate, $snmptranslate_dirs, $db, $config)
25 25
 	{
26 26
 		$this->snmptranslate=$snmptranslate;
27 27
 		$this->snmptranslate_dirs=$snmptranslate_dirs;
@@ -38,19 +38,19 @@  discard block
 block discarded – undo
38 38
 	
39 39
 	public function getMIBList()
40 40
 	{
41
-		$dbconn = $this->db->getConnection();
41
+		$dbconn=$this->db->getConnection();
42 42
 		$query=$dbconn->select()
43 43
 				->distinct()
44 44
 				->from(
45 45
 					$this->config->getMIBCacheTableName(),
46 46
 					array('mib' => 'mib'))
47 47
 				->where("type = '21'")
48
-				->order('mib ASC');				;
48
+				->order('mib ASC'); ;
49 49
 		$names=$dbconn->fetchAll($query);
50 50
 		$mib=array();
51
-		foreach($names as $val)
51
+		foreach ($names as $val)
52 52
 		{
53
-			array_push($mib,$val->mib);
53
+			array_push($mib, $val->mib);
54 54
 		}
55 55
 		return $mib;
56 56
 		
@@ -64,12 +64,12 @@  discard block
 block discarded – undo
64 64
 	public function getTrapList($mib)
65 65
 	{
66 66
 		$traps=array();
67
-		$dbconn = $this->db->getConnection();
67
+		$dbconn=$this->db->getConnection();
68 68
 		$query=$dbconn->select()
69 69
 				->from(
70 70
 					$this->config->getMIBCacheTableName(),
71 71
 				    array('name' => 'name', 'oid' => 'oid', 'description' => 'description'))
72
-				->where("mib = '".$mib."' AND type='21'") ;
72
+				->where("mib = '".$mib."' AND type='21'");
73 73
 		$names=$dbconn->fetchAll($query);
74 74
 		foreach ($names as $val)
75 75
 		{
@@ -87,19 +87,19 @@  discard block
 block discarded – undo
87 87
 		$objects=array();
88 88
 		
89 89
 		// Get trap id in DB
90
-		$dbconn = $this->db->getConnection();
90
+		$dbconn=$this->db->getConnection();
91 91
 		$query=$dbconn->select()
92 92
 				->from(
93 93
 					$this->config->getMIBCacheTableName(),
94 94
 					array('id' => 'id'))
95
-				->where("oid = '".$trap."'") ;
95
+				->where("oid = '".$trap."'");
96 96
 		$id=$dbconn->fetchRow($query);
97
-		if ( ($id == null) || ! property_exists($id,'id') ) return null;
97
+		if (($id == null) || !property_exists($id, 'id')) return null;
98 98
 		
99 99
 		$query=$dbconn->select()
100 100
 		        ->from(
101 101
 		            array('c' => $this->config->getMIBCacheTableName()),
102
-		            array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
102
+		            array('name' => 'c.name', 'mib' => 'c.mib', 'oid' => 'c.oid', 'type_enum'=>'c.type_enum',
103 103
 		                'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
104 104
 		                'description' => 'c.description'))
105 105
 		        ->join(
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 		            'o.trap_id='.$id->id )
108 108
 		        ->where("o.object_id = c.id");
109 109
 		$listObjects=$dbconn->fetchAll($query);
110
-		if ( count($listObjects)==0 ) return null;
110
+		if (count($listObjects) == 0) return null;
111 111
 		
112 112
 		foreach ($listObjects as $val)
113 113
 		{
@@ -128,14 +128,14 @@  discard block
 block discarded – undo
128 128
 	*/
129 129
 	public function translateOID($oid)
130 130
 	{
131
-	    if (!preg_match('/^\./',$oid)) $oid = '.' . $oid; // Add a leading '.'
132
-		$retArray=array('oid' => $oid, 'mib' => null, 'name'=>null,'type'=>null);
133
-		$dbconn = $this->db->getConnection();
131
+	    if (!preg_match('/^\./', $oid)) $oid='.'.$oid; // Add a leading '.'
132
+		$retArray=array('oid' => $oid, 'mib' => null, 'name'=>null, 'type'=>null);
133
+		$dbconn=$this->db->getConnection();
134 134
 
135 135
 		$query=$dbconn->select()
136 136
 				->from(
137 137
 					array('o' => $this->config->getMIBCacheTableName()),
138
-					array('mib'=>'o.mib','name' => 'o.name','type'=>'o.syntax',
138
+					array('mib'=>'o.mib', 'name' => 'o.name', 'type'=>'o.syntax',
139 139
 					    'type_enum'=>'o.type_enum', 'description'=>'o.description'))
140 140
 				->where('o.oid=\''.$oid.'\'');
141 141
 		$object=$dbconn->fetchRow($query);
@@ -151,18 +151,18 @@  discard block
 block discarded – undo
151 151
 		
152 152
 		// Try to get oid name from snmptranslate
153 153
 		$matches=array();
154
-		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
154
+		$translate=exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
155 155
 		    ' '.$oid);
156
-		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
157
-		if ($ret_code===0 || $ret_code===false) {
156
+		$ret_code=preg_match('/(.*)::(.*)/', $translate, $matches);
157
+		if ($ret_code === 0 || $ret_code === false) {
158 158
 			return null;
159 159
 		} 
160 160
 		$retArray['mib']=$matches[1];
161 161
 		$retArray['name']=$matches[2];
162 162
 		
163
-		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.' -Td -On ' . $matches[0] .
163
+		$translate=exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.' -Td -On '.$matches[0].
164 164
 			" | grep SYNTAX | sed 's/SYNTAX[[:blank:]]*//'");
165
-		if (preg_match('/(.*)\{(.*)\}/',$translate,$matches))
165
+		if (preg_match('/(.*)\{(.*)\}/', $translate, $matches))
166 166
 		{
167 167
 		    $retArray['type']=$matches[1];
168 168
 		    $retArray['type_enum']=$matches[2];
@@ -197,9 +197,9 @@  discard block
 block discarded – undo
197 197
 	 * @param string $type filter by type (21=trap)
198 198
 	 * @return number number of entries in db.
199 199
 	 */
200
-	public function countObjects($mib=null,$type=null)
200
+	public function countObjects($mib=null, $type=null)
201 201
 	{
202
-		$dbconn = $this->db->getConnection();
202
+		$dbconn=$this->db->getConnection();
203 203
 		$query=$dbconn->select()
204 204
 				->from(
205 205
 					$this->config->getMIBCacheTableName(),
@@ -207,11 +207,11 @@  discard block
 block discarded – undo
207 207
 		$where=null;
208 208
 		if ($mib !== null)
209 209
 		{
210
-			$where ="mib = '$mib' ";
210
+			$where="mib = '$mib' ";
211 211
 		}
212 212
 		if ($type !== null)
213 213
 		{
214
-			$where=($where !== null)?' AND ':'';
214
+			$where=($where !== null) ? ' AND ' : '';
215 215
 			$where.="type='$type'";
216 216
 		}
217 217
 		if ($where !== null)
@@ -227,10 +227,10 @@  discard block
 block discarded – undo
227 227
 	 * @param integer $id
228 228
 	 * @return array trap details
229 229
 	 */
230
-	public function getTrapDetails($oid=null,$id=null)
230
+	public function getTrapDetails($oid=null, $id=null)
231 231
 	{	    
232 232
 	    // Get trap id in DB
233
-	    if ($oid===null)
233
+	    if ($oid === null)
234 234
 	    {
235 235
 	        $where="c.id = '$id'";
236 236
 	    }
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
 	    $query=$this->db->getConnection()->select()
242 242
            ->from(
243 243
             array('c' => $this->config->getMIBCacheTableName()),
244
-            array('name' => 'c.name','mib' => 'c.mib','oid' => 'c.oid','type_enum'=>'c.type_enum',
244
+            array('name' => 'c.name', 'mib' => 'c.mib', 'oid' => 'c.oid', 'type_enum'=>'c.type_enum',
245 245
                 'type' => 'c.syntax', 'text_conv' => 'c.textual_convention', 'disp' => 'display_hint',
246 246
                 'description' => 'c.description'))
247 247
             ->where($where);
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Logging.php 3 patches
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -9,113 +9,113 @@
 block discarded – undo
9 9
 class Logging
10 10
 {
11 11
 
12
-    //**** Options from config database
13
-    // Default values
14
-    public $debugLevel=2;  // 0=No output 1=critical 2=warning 3=trace 4=ALL
15
-    public $outputMode='syslog'; // alert type : file, syslog, display
16
-    public $outputFile="/tmp/trapdebug.txt";
17
-    protected $logLevels=array("","Error","Warning","Info","Debug");
18
-    protected $outputList=array('file', 'syslog', 'display');
12
+	//**** Options from config database
13
+	// Default values
14
+	public $debugLevel=2;  // 0=No output 1=critical 2=warning 3=trace 4=ALL
15
+	public $outputMode='syslog'; // alert type : file, syslog, display
16
+	public $outputFile="/tmp/trapdebug.txt";
17
+	protected $logLevels=array("","Error","Warning","Info","Debug");
18
+	protected $outputList=array('file', 'syslog', 'display');
19 19
     
20
-    /** Send log. Throws exception on critical error
21
-     *	@param	string $message Message to log
22
-     *	@param	int $level 1=critical 2=warning 3=trace 4=debug
23
-     *	@param  string $destination file/syslog/display
24
-     *	@return void
25
-     *  @throws Exception
26
-     **/
27
-    public function log( $message, $level, $destination ='')
28
-    {
29
-        if ($this->debugLevel >= $level)
30
-        {
31
-            $message = '['.  date("Y/m/d H:i:s") . '] ' .
32
-                '[TrapDirector] ['.$this->logLevels[$level].']: ' .$message . "\n";
20
+	/** Send log. Throws exception on critical error
21
+	 *	@param	string $message Message to log
22
+	 *	@param	int $level 1=critical 2=warning 3=trace 4=debug
23
+	 *	@param  string $destination file/syslog/display
24
+	 *	@return void
25
+	 *  @throws Exception
26
+	 **/
27
+	public function log( $message, $level, $destination ='')
28
+	{
29
+		if ($this->debugLevel >= $level)
30
+		{
31
+			$message = '['.  date("Y/m/d H:i:s") . '] ' .
32
+				'[TrapDirector] ['.$this->logLevels[$level].']: ' .$message . "\n";
33 33
             
34
-            $output = ( $destination != '' ) ? $destination : $this->outputMode;
35
-            switch ($output)
36
-            {
37
-                case 'file':
38
-                    file_put_contents ($this->outputFile, $message , FILE_APPEND);
39
-                    break;
40
-                case 'syslog':
41
-                    switch($level)
42
-                    {
43
-                        case 1 : $prio = LOG_ERR;break;
44
-                        case 2 : $prio = LOG_WARNING;break;
45
-                        case 3 : $prio = LOG_INFO;break;
46
-                        case 4 : $prio = LOG_DEBUG;break;
47
-                        default: $prio = LOG_ERR;
48
-                    }
49
-                    syslog($prio,$message);
50
-                    break;
51
-                case 'display':
52
-                    echo $message;
53
-                    break;
54
-                default : // nothing we can do at this point
55
-                    throw new Exception($message);
56
-            }
57
-        }
58
-        if ($level == 1)
59
-        {
60
-            throw new Exception($message);
61
-        }
62
-    }
34
+			$output = ( $destination != '' ) ? $destination : $this->outputMode;
35
+			switch ($output)
36
+			{
37
+				case 'file':
38
+					file_put_contents ($this->outputFile, $message , FILE_APPEND);
39
+					break;
40
+				case 'syslog':
41
+					switch($level)
42
+					{
43
+						case 1 : $prio = LOG_ERR;break;
44
+						case 2 : $prio = LOG_WARNING;break;
45
+						case 3 : $prio = LOG_INFO;break;
46
+						case 4 : $prio = LOG_DEBUG;break;
47
+						default: $prio = LOG_ERR;
48
+					}
49
+					syslog($prio,$message);
50
+					break;
51
+				case 'display':
52
+					echo $message;
53
+					break;
54
+				default : // nothing we can do at this point
55
+					throw new Exception($message);
56
+			}
57
+		}
58
+		if ($level == 1)
59
+		{
60
+			throw new Exception($message);
61
+		}
62
+	}
63 63
     
64 64
         
65
-    public function setLogging($debugLvl,$outputType,$outputFile=null)
66
-    {
67
-        $this->setLevel($debugLvl);
68
-        switch ($outputType)
69
-        {
70
-            case 'file':
71
-                if ($outputFile == null) throw new Exception("File logging without file !");
72
-                $this->setFile($outputFile);
73
-                $this->setDestination('file');
74
-                break;
75
-            default:
76
-                $this->setDestination($outputType);
77
-        }
78
-    }
65
+	public function setLogging($debugLvl,$outputType,$outputFile=null)
66
+	{
67
+		$this->setLevel($debugLvl);
68
+		switch ($outputType)
69
+		{
70
+			case 'file':
71
+				if ($outputFile == null) throw new Exception("File logging without file !");
72
+				$this->setFile($outputFile);
73
+				$this->setDestination('file');
74
+				break;
75
+			default:
76
+				$this->setDestination($outputType);
77
+		}
78
+	}
79 79
     
80
-    /**
81
-     * Set logging level
82
-     * @param integer $level
83
-     * @throws Exception
84
-     */
85
-    public function setLevel($level)
86
-    {
87
-        if (!is_integer($level) || $level < 0 || $level > 10)
88
-        {
89
-            throw new Exception('Invalid log level');
90
-        }
91
-        $this->debugLevel=$level;
92
-    }
80
+	/**
81
+	 * Set logging level
82
+	 * @param integer $level
83
+	 * @throws Exception
84
+	 */
85
+	public function setLevel($level)
86
+	{
87
+		if (!is_integer($level) || $level < 0 || $level > 10)
88
+		{
89
+			throw new Exception('Invalid log level');
90
+		}
91
+		$this->debugLevel=$level;
92
+	}
93 93
 
94
-    /**
95
-     * Set logging destination
96
-     * @param string $destination
97
-     * @throws Exception
98
-     */
99
-    public function setDestination($destination)
100
-    {
101
-        if (!is_string($destination) || ! in_array($destination, $this->outputList))
102
-        {
103
-            throw new Exception('Invalid log destination');
104
-        }
105
-        $this->outputMode=$destination;
106
-    }
107
-    /**
108
-     * Set file destination
109
-     * @param string $file
110
-     * @throws Exception
111
-     */
112
-    public function setFile($file)
113
-    {
114
-        if (!is_string($file))
115
-        {
116
-            throw new Exception('Invalid log file');
117
-        }
118
-        $this->outputFile=$file;
119
-    }
94
+	/**
95
+	 * Set logging destination
96
+	 * @param string $destination
97
+	 * @throws Exception
98
+	 */
99
+	public function setDestination($destination)
100
+	{
101
+		if (!is_string($destination) || ! in_array($destination, $this->outputList))
102
+		{
103
+			throw new Exception('Invalid log destination');
104
+		}
105
+		$this->outputMode=$destination;
106
+	}
107
+	/**
108
+	 * Set file destination
109
+	 * @param string $file
110
+	 * @throws Exception
111
+	 */
112
+	public function setFile($file)
113
+	{
114
+		if (!is_string($file))
115
+		{
116
+			throw new Exception('Invalid log file');
117
+		}
118
+		$this->outputFile=$file;
119
+	}
120 120
     
121 121
 }
122 122
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -4,17 +4,17 @@  discard block
 block discarded – undo
4 4
 
5 5
 use Exception;
6 6
 
7
-define("ERROR", 1);define("WARN", 2);define("INFO", 3);define("DEBUG", 4);
7
+define("ERROR", 1); define("WARN", 2); define("INFO", 3); define("DEBUG", 4);
8 8
 
9 9
 class Logging
10 10
 {
11 11
 
12 12
     //**** Options from config database
13 13
     // Default values
14
-    public $debugLevel=2;  // 0=No output 1=critical 2=warning 3=trace 4=ALL
14
+    public $debugLevel=2; // 0=No output 1=critical 2=warning 3=trace 4=ALL
15 15
     public $outputMode='syslog'; // alert type : file, syslog, display
16 16
     public $outputFile="/tmp/trapdebug.txt";
17
-    protected $logLevels=array("","Error","Warning","Info","Debug");
17
+    protected $logLevels=array("", "Error", "Warning", "Info", "Debug");
18 18
     protected $outputList=array('file', 'syslog', 'display');
19 19
     
20 20
     /** Send log. Throws exception on critical error
@@ -24,29 +24,29 @@  discard block
 block discarded – undo
24 24
      *	@return void
25 25
      *  @throws Exception
26 26
      **/
27
-    public function log( $message, $level, $destination ='')
27
+    public function log($message, $level, $destination='')
28 28
     {
29 29
         if ($this->debugLevel >= $level)
30 30
         {
31
-            $message = '['.  date("Y/m/d H:i:s") . '] ' .
32
-                '[TrapDirector] ['.$this->logLevels[$level].']: ' .$message . "\n";
31
+            $message='['.date("Y/m/d H:i:s").'] '.
32
+                '[TrapDirector] ['.$this->logLevels[$level].']: '.$message."\n";
33 33
             
34
-            $output = ( $destination != '' ) ? $destination : $this->outputMode;
34
+            $output=($destination != '') ? $destination : $this->outputMode;
35 35
             switch ($output)
36 36
             {
37 37
                 case 'file':
38
-                    file_put_contents ($this->outputFile, $message , FILE_APPEND);
38
+                    file_put_contents($this->outputFile, $message, FILE_APPEND);
39 39
                     break;
40 40
                 case 'syslog':
41
-                    switch($level)
41
+                    switch ($level)
42 42
                     {
43
-                        case 1 : $prio = LOG_ERR;break;
44
-                        case 2 : $prio = LOG_WARNING;break;
45
-                        case 3 : $prio = LOG_INFO;break;
46
-                        case 4 : $prio = LOG_DEBUG;break;
47
-                        default: $prio = LOG_ERR;
43
+                        case 1 : $prio=LOG_ERR; break;
44
+                        case 2 : $prio=LOG_WARNING; break;
45
+                        case 3 : $prio=LOG_INFO; break;
46
+                        case 4 : $prio=LOG_DEBUG; break;
47
+                        default: $prio=LOG_ERR;
48 48
                     }
49
-                    syslog($prio,$message);
49
+                    syslog($prio, $message);
50 50
                     break;
51 51
                 case 'display':
52 52
                     echo $message;
@@ -62,7 +62,7 @@  discard block
 block discarded – undo
62 62
     }
63 63
     
64 64
         
65
-    public function setLogging($debugLvl,$outputType,$outputFile=null)
65
+    public function setLogging($debugLvl, $outputType, $outputFile=null)
66 66
     {
67 67
         $this->setLevel($debugLvl);
68 68
         switch ($outputType)
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
      */
99 99
     public function setDestination($destination)
100 100
     {
101
-        if (!is_string($destination) || ! in_array($destination, $this->outputList))
101
+        if (!is_string($destination) || !in_array($destination, $this->outputList))
102 102
         {
103 103
             throw new Exception('Invalid log destination');
104 104
         }
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -68,7 +68,9 @@
 block discarded – undo
68 68
         switch ($outputType)
69 69
         {
70 70
             case 'file':
71
-                if ($outputFile == null) throw new Exception("File logging without file !");
71
+                if ($outputFile == null) {
72
+                	throw new Exception("File logging without file !");
73
+                }
72 74
                 $this->setFile($outputFile);
73 75
                 $this->setDestination('file');
74 76
                 break;
Please login to merge, or discard this patch.
library/Trapdirector/TrapsController.php 3 patches
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -32,8 +32,8 @@  discard block
 block discarded – undo
32 32
 	protected $trapClass;		//< Trap class for bin/trap_class.php
33 33
 		
34 34
 	/** Get instance of TrapModuleConfig class
35
-	*	@return TrapModuleConfig
36
-	*/
35
+	 *	@return TrapModuleConfig
36
+	 */
37 37
 	public function getModuleConfig() 
38 38
 	{
39 39
 		if ($this->moduleConfig == Null) 
@@ -58,12 +58,12 @@  discard block
 block discarded – undo
58 58
 	
59 59
 	public function getTrapHostListTable()
60 60
 	{
61
-	    if ($this->trapTableHostList == Null) 
61
+		if ($this->trapTableHostList == Null) 
62 62
 		{
63
-	        $this->trapTableHostList = new TrapTableHostList();
64
-	        $this->trapTableHostList->setConfig($this->getModuleConfig());
65
-	    }
66
-	    return $this->trapTableHostList;
63
+			$this->trapTableHostList = new TrapTableHostList();
64
+			$this->trapTableHostList->setConfig($this->getModuleConfig());
65
+		}
66
+		return $this->trapTableHostList;
67 67
 	}
68 68
 	
69 69
 	public function getHandlerListTable() 
@@ -77,11 +77,11 @@  discard block
 block discarded – undo
77 77
 	}	
78 78
 	
79 79
 	/**	Get Database connexion
80
-	*	@param $DBname string DB name in resource.ini_ge
81
-	*	@param $test bool if set to true, returns error code and not database
82
-	*	@param $test_version bool if set to flase, does not test database version of trapDB
83
-	*	@return array<integer,mixed>|mixed : if test=false, returns DB connexion, else array(error_num,message) or null on error.
84
-	*/
80
+	 *	@param $DBname string DB name in resource.ini_ge
81
+	 *	@param $test bool if set to true, returns error code and not database
82
+	 *	@param $test_version bool if set to flase, does not test database version of trapDB
83
+	 *	@return array<integer,mixed>|mixed : if test=false, returns DB connexion, else array(error_num,message) or null on error.
84
+	 */
85 85
 	public function getDbByName($DBname,$test=false,$test_version=true)
86 86
 	{
87 87
 		try 
@@ -166,20 +166,20 @@  discard block
 block discarded – undo
166 166
 
167 167
 		if ( ! $dbresource )
168 168
 		{
169
-		    if ($test) return array(1,'No database in config.ini');
170
-		    $this->redirectNow('trapdirector/settings?idodberror=1');
171
-		    return null;
169
+			if ($test) return array(1,'No database in config.ini');
170
+			$this->redirectNow('trapdirector/settings?idodberror=1');
171
+			return null;
172 172
 		}
173 173
 		
174 174
 		try
175 175
 		{
176
-		    $dbconn = IcingaDbConnection::fromResourceName($dbresource);
176
+			$dbconn = IcingaDbConnection::fromResourceName($dbresource);
177 177
 		}
178 178
 		catch (Exception $e)
179 179
 		{
180
-		    if ($test) return array(2,"Database $dbresource does not exists in IcingaWeb2");
181
-		    $this->redirectNow('trapdirector/settings?idodberror=2');
182
-		    return null;
180
+			if ($test) return array(2,"Database $dbresource does not exists in IcingaWeb2");
181
+			$this->redirectNow('trapdirector/settings?idodberror=2');
182
+			return null;
183 183
 		}
184 184
 		
185 185
 		if ($test == false) 
@@ -190,13 +190,13 @@  discard block
 block discarded – undo
190 190
 		
191 191
 		try
192 192
 		{
193
-		    $query = $dbconn->select()
194
-		    ->from('icinga_dbversion',array('version'));
195
-		    $version=$dbconn->fetchRow($query);
196
-		    if ( ($version == null) || ! property_exists($version,'version') )
197
-		    {
198
-		        return array(4,"$dbresource does not look like an IDO database");
199
-		    }
193
+			$query = $dbconn->select()
194
+			->from('icinga_dbversion',array('version'));
195
+			$version=$dbconn->fetchRow($query);
196
+			if ( ($version == null) || ! property_exists($version,'version') )
197
+			{
198
+				return array(4,"$dbresource does not look like an IDO database");
199
+			}
200 200
 		}
201 201
 		catch (Exception $e)
202 202
 		{
@@ -206,15 +206,15 @@  discard block
 block discarded – undo
206 206
 		return array(0,'');
207 207
 	}
208 208
 	
209
-    protected function applyPaginationLimits(Paginatable $paginatable, $limit = 25, $offset = null)
210
-    {
211
-        $limit = $this->params->get('limit', $limit);
212
-        $page = $this->params->get('page', $offset);
209
+	protected function applyPaginationLimits(Paginatable $paginatable, $limit = 25, $offset = null)
210
+	{
211
+		$limit = $this->params->get('limit', $limit);
212
+		$page = $this->params->get('page', $offset);
213 213
 
214
-        $paginatable->limit($limit, $page > 0 ? ($page - 1) * $limit : 0);
214
+		$paginatable->limit($limit, $page > 0 ? ($page - 1) * $limit : 0);
215 215
 
216
-        return $paginatable;
217
-    }	
216
+		return $paginatable;
217
+	}	
218 218
 	
219 219
 	public function displayExitError($source,$message)
220 220
 	{	// TODO : check better ways to transmit data (with POST ?)
@@ -223,33 +223,33 @@  discard block
 block discarded – undo
223 223
 	
224 224
 	protected function checkReadPermission()
225 225
 	{
226
-        if (! $this->Auth()->hasPermission('trapdirector/view')) {
227
-            $this->displayExitError('Permissions','No permission fo view content');
228
-        }		
226
+		if (! $this->Auth()->hasPermission('trapdirector/view')) {
227
+			$this->displayExitError('Permissions','No permission fo view content');
228
+		}		
229 229
 	}
230 230
 
231 231
 	protected function checkConfigPermission()
232 232
 	{
233
-        if (! $this->Auth()->hasPermission('trapdirector/config')) {
234
-            $this->displayExitError('Permissions','No permission fo configure');
235
-        }		
233
+		if (! $this->Auth()->hasPermission('trapdirector/config')) {
234
+			$this->displayExitError('Permissions','No permission fo configure');
235
+		}		
236 236
 	}
237 237
 	
238
-    /**
239
-     * Check if user has write permission
240
-     * @param number $check optional : if set to 1, return true (user has permission) or false instead of displaying error page
241
-     * @return boolean : user has permission
242
-     */
238
+	/**
239
+	 * Check if user has write permission
240
+	 * @param number $check optional : if set to 1, return true (user has permission) or false instead of displaying error page
241
+	 * @return boolean : user has permission
242
+	 */
243 243
 	protected function checkModuleConfigPermission($check=0)
244 244
 	{
245
-        if (! $this->Auth()->hasPermission('trapdirector/module_config')) {
246
-            if ($check == 0)
247
-            {
248
-                $this->displayExitError('Permissions','No permission fo configure module');
249
-            }
250
-            return false;
251
-        }
252
-        return true;
245
+		if (! $this->Auth()->hasPermission('trapdirector/module_config')) {
246
+			if ($check == 0)
247
+			{
248
+				$this->displayExitError('Permissions','No permission fo configure module');
249
+			}
250
+			return false;
251
+		}
252
+		return true;
253 253
 	}
254 254
 
255 255
 	/*************************  Trap class get **********************/
@@ -269,8 +269,8 @@  discard block
 block discarded – undo
269 269
 	/************************** MIB related **************************/
270 270
 	
271 271
 	/** Get MIBLoader class
272
-	*	@return MIBLoader class
273
-	*/
272
+	 *	@return MIBLoader class
273
+	 */
274 274
 	protected function getMIB()
275 275
 	{
276 276
 		if ($this->MIBData == null)
@@ -288,9 +288,9 @@  discard block
 block discarded – undo
288 288
 	/**************************  Database queries *******************/
289 289
 	
290 290
 	/** Get host(s) by IP (v4 or v6) or by name in IDO database
291
-	*	does not catch exceptions
292
-	*	@return array of objects ( name, id (object_id), display_name)
293
-	*/
291
+	 *	does not catch exceptions
292
+	 *	@return array of objects ( name, id (object_id), display_name)
293
+	 */
294 294
 	protected function getHostByIP($ip) 
295 295
 	{
296 296
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -309,9 +309,9 @@  discard block
 block discarded – undo
309 309
 	}
310 310
 
311 311
 	/** Get host(s) by name in IDO database
312
-	*	does not catch exceptions
313
-	*	@return array of objects ( name, id (object_id), display_name)
314
-	*/
312
+	 *	does not catch exceptions
313
+	 *	@return array of objects ( name, id (object_id), display_name)
314
+	 */
315 315
 	protected function getHostByName($name) 
316 316
 	{
317 317
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -330,9 +330,9 @@  discard block
 block discarded – undo
330 330
 	}	
331 331
 	
332 332
 	/** Get host groups by  name in IDO database
333
-	*	does not catch exceptions
334
-	*	@return array of objects ( name, id (object_id), display_name)
335
-	*/
333
+	 *	does not catch exceptions
334
+	 *	@return array of objects ( name, id (object_id), display_name)
335
+	 */
336 336
 	protected function getHostGroupByName($ip) 
337 337
 	{
338 338
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -352,9 +352,9 @@  discard block
 block discarded – undo
352 352
 
353 353
 	
354 354
 	/** Get host IP (v4 and v6) by name in IDO database
355
-	*	does not catch exceptions
356
-	*	@return array ( name, display_name, ip4, ip6)
357
-	*/
355
+	 *	does not catch exceptions
356
+	 *	@return array ( name, display_name, ip4, ip6)
357
+	 */
358 358
 	protected function getHostInfoByID($id) 
359 359
 	{
360 360
 		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
@@ -373,9 +373,9 @@  discard block
 block discarded – undo
373 373
 
374 374
 	
375 375
 	/** Get host by objectid  in IDO database
376
-	*	does not catch exceptions
377
-	*	@return array of objects ( id, name, display_name, ip, ip6,  )
378
-	*/
376
+	 *	does not catch exceptions
377
+	 *	@return array of objects ( id, name, display_name, ip, ip6,  )
378
+	 */
379 379
 	protected function getHostByObjectID($id) // TODO : duplicate of getHostInfoByID above
380 380
 	{
381 381
 		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
@@ -393,10 +393,10 @@  discard block
 block discarded – undo
393 393
 	}	
394 394
 	
395 395
 	/** Get services from object ( host_object_id) in IDO database
396
-	*	does not catch exceptions
397
-	*	@param $id	int object_id
398
-	*	@return array display_name (of service), service_object_id
399
-	*/
396
+	 *	does not catch exceptions
397
+	 *	@param $id	int object_id
398
+	 *	@return array display_name (of service), service_object_id
399
+	 */
400 400
 	protected function getServicesByHostid($id) 
401 401
 	{
402 402
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -416,11 +416,11 @@  discard block
 block discarded – undo
416 416
 	}	
417 417
 	
418 418
 	/** Get services from hostgroup object id ( hostgroup_object_id) in IDO database
419
-	* 	gets all hosts in hostgroup and return common services
420
-	*	does not catch exceptions
421
-	*	@param $id	int object_id
422
-	*	@return array display_name (of service), service_object_id
423
-	*/
419
+	 * 	gets all hosts in hostgroup and return common services
420
+	 *	does not catch exceptions
421
+	 *	@param $id	int object_id
422
+	 *	@return array display_name (of service), service_object_id
423
+	 */
424 424
 	protected function getServicesByHostGroupid($id) 
425 425
 	{		
426 426
 		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
 		//print_r($common_services);
460 460
 		foreach (array_keys($common_services) as $key)
461 461
 		{
462
-		    if ($common_services[$key]['num'] == $num_hosts)
462
+			if ($common_services[$key]['num'] == $num_hosts)
463 463
 			{
464 464
 				array_push($result,array($key,$common_services[$key]['name']));
465 465
 			}
@@ -469,11 +469,11 @@  discard block
 block discarded – undo
469 469
 	}	
470 470
 
471 471
 	/** Get services object id by host name / service name in IDO database
472
-	*	does not catch exceptions
473
-	*	@param $hostname string host name
474
-	*	@param $name string service name
475
-	*	@return array  service id
476
-	*/
472
+	 *	does not catch exceptions
473
+	 *	@param $hostname string host name
474
+	 *	@param $name string service name
475
+	 *	@return array  service id
476
+	 */
477 477
 	protected function getServiceIDByName($hostname,$name) 
478 478
 	{
479 479
 		$db = $this->getIdoDb()->getConnection();
@@ -496,10 +496,10 @@  discard block
 block discarded – undo
496 496
 	}
497 497
 	
498 498
 	/** Get object name from object_id  in IDO database
499
-	*	does not catch exceptions
500
-	*	@param int $id object_id (default to null, used first if not null)
501
-	*	@return array name1 (host) name2 (service)
502
-	*/
499
+	 *	does not catch exceptions
500
+	 *	@param int $id object_id (default to null, used first if not null)
501
+	 *	@return array name1 (host) name2 (service)
502
+	 */
503 503
 	protected function getObjectNameByid($id) 
504 504
 	{
505 505
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -515,9 +515,9 @@  discard block
 block discarded – undo
515 515
 	}		
516 516
 
517 517
 	/** Add handler rule in traps DB
518
-	*	@param array $params : array(<db item>=><value>)
519
-	*	@return int inserted id
520
-	*/
518
+	 *	@param array $params : array(<db item>=><value>)
519
+	 *	@return int inserted id
520
+	 */
521 521
 	protected function addHandlerRule($params)
522 522
 	{
523 523
 		// TODO Check for rule consistency
@@ -539,10 +539,10 @@  discard block
 block discarded – undo
539 539
 	}	
540 540
 
541 541
 	/** Update handler rule in traps DB
542
-	*	@param array $params : (<db item>=><value>)
543
-	*   @param integer $ruleID : rule id in db
544
-	*	@return array affected rows
545
-	*/
542
+	 *	@param array $params : (<db item>=><value>)
543
+	 *   @param integer $ruleID : rule id in db
544
+	 *	@return array affected rows
545
+	 */
546 546
 	protected function updateHandlerRule($params,$ruleID)
547 547
 	{
548 548
 		// TODO Check for rule consistency
@@ -560,8 +560,8 @@  discard block
 block discarded – undo
560 560
 	}	
561 561
 	
562 562
 	/** Delete rule by id
563
-	*	@param int $ruleID rule id
564
-	*/
563
+	 *	@param int $ruleID rule id
564
+	 */
565 565
 	protected function deleteRule($ruleID)
566 566
 	{
567 567
 		if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
@@ -575,9 +575,9 @@  discard block
 block discarded – undo
575 575
 	}
576 576
 
577 577
 	/** Delete trap by ip & oid
578
-	*	@param $ip string source IP (v4 or v6)
579
-	*	@param $oid string oid
580
-	*/
578
+	 *	@param $ip string source IP (v4 or v6)
579
+	 *	@param $oid string oid
580
+	 */
581 581
 	protected function deleteTrap($ip,$oid)
582 582
 	{
583 583
 		
@@ -603,9 +603,9 @@  discard block
 block discarded – undo
603 603
    
604 604
 
605 605
 	/** count trap by ip & oid
606
-	*	@param $ip string source IP (v4 or v6)
607
-	*	@param $oid string oid
608
-	*/
606
+	 *	@param $ip string source IP (v4 or v6)
607
+	 *	@param $oid string oid
608
+	 */
609 609
 	protected function countTrap($ip,$oid)
610 610
 	{
611 611
 		
@@ -631,8 +631,8 @@  discard block
 block discarded – undo
631 631
 	}		
632 632
 	
633 633
 	/** get configuration value
634
-	*	@param string $element : configuration name in db
635
-	*/
634
+	 *	@param string $element : configuration name in db
635
+	 */
636 636
 	protected function getDBConfigValue($element)
637 637
 	{
638 638
 	
@@ -663,9 +663,9 @@  discard block
 block discarded – undo
663 663
 	}
664 664
 
665 665
 	/** add configuration value
666
-	*	@param string $element : name of config element
667
-	*   @param string $value : value
668
-	*/
666
+	 *	@param string $element : name of config element
667
+	 *   @param string $value : value
668
+	 */
669 669
 		
670 670
 	protected function addDBConfigValue($element,$value)
671 671
 	{
@@ -683,9 +683,9 @@  discard block
 block discarded – undo
683 683
 	}
684 684
 
685 685
 	/** set configuration value
686
-	*	@param string $element : name of config element
687
-	*   @param string $value : value
688
-	*/
686
+	 *	@param string $element : name of config element
687
+	 *   @param string $value : value
688
+	 */
689 689
 	protected function setDBConfigValue($element,$value)
690 690
 	{
691 691
 	
@@ -699,13 +699,13 @@  discard block
 block discarded – undo
699 699
 	}
700 700
 	
701 701
 	/** Check if director is installed
702
-	*	@return bool true/false
703
-	*/
702
+	 *	@return bool true/false
703
+	 */
704 704
 	protected function isDirectorInstalled()
705 705
 	{
706
-	    $output=array();
707
-	    exec('icingacli module list',$output);
708
-	    foreach ($output as $line)
706
+		$output=array();
707
+		exec('icingacli module list',$output);
708
+		foreach ($output as $line)
709 709
 		{
710 710
 			if (preg_match('/^director .*enabled/',$line))
711 711
 			{
Please login to merge, or discard this patch.
Spacing   +112 added lines, -112 removed lines patch added patch discarded remove patch
@@ -22,14 +22,14 @@  discard block
 block discarded – undo
22 22
 
23 23
 class TrapsController extends Controller
24 24
 {
25
-	protected $moduleConfig;  	//< TrapModuleConfig instance
26
-	protected $trapTableList; 	//< TrapTableList (by date)
27
-	protected $trapTableHostList; 	//< TrapTableList (by hosts)
28
-	protected $handlerTableList; 	//< HandlerTableList instance
29
-	protected $trapDB;			//< Trap database
30
-	protected $icingaDB;		//< Icinga IDO database;
31
-	protected $MIBData; 		//< MIBLoader class
32
-	protected $trapClass;		//< Trap class for bin/trap_class.php
25
+	protected $moduleConfig; //< TrapModuleConfig instance
26
+	protected $trapTableList; //< TrapTableList (by date)
27
+	protected $trapTableHostList; //< TrapTableList (by hosts)
28
+	protected $handlerTableList; //< HandlerTableList instance
29
+	protected $trapDB; //< Trap database
30
+	protected $icingaDB; //< Icinga IDO database;
31
+	protected $MIBData; //< MIBLoader class
32
+	protected $trapClass; //< Trap class for bin/trap_class.php
33 33
 		
34 34
 	/** Get instance of TrapModuleConfig class
35 35
 	*	@return TrapModuleConfig
@@ -43,14 +43,14 @@  discard block
 block discarded – undo
43 43
 			{
44 44
 				$this->redirectNow('trapdirector/settings?message=No database prefix');
45 45
 			}
46
-			$this->moduleConfig = new TrapModuleConfig($db_prefix);
46
+			$this->moduleConfig=new TrapModuleConfig($db_prefix);
47 47
 		}
48 48
 		return $this->moduleConfig;
49 49
 	}
50 50
 	
51 51
 	public function getTrapListTable() {
52 52
 		if ($this->trapTableList == Null) {
53
-			$this->trapTableList = new TrapTableList();
53
+			$this->trapTableList=new TrapTableList();
54 54
 			$this->trapTableList->setConfig($this->getModuleConfig());
55 55
 		}
56 56
 		return $this->trapTableList;
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 	{
61 61
 	    if ($this->trapTableHostList == Null) 
62 62
 		{
63
-	        $this->trapTableHostList = new TrapTableHostList();
63
+	        $this->trapTableHostList=new TrapTableHostList();
64 64
 	        $this->trapTableHostList->setConfig($this->getModuleConfig());
65 65
 	    }
66 66
 	    return $this->trapTableHostList;
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 	{
71 71
 		if ($this->handlerTableList == Null) 
72 72
 		{
73
-			$this->handlerTableList = new HandlerTableList();
73
+			$this->handlerTableList=new HandlerTableList();
74 74
 			$this->handlerTableList->setConfig($this->getModuleConfig());
75 75
 		}
76 76
 		return $this->handlerTableList;
@@ -82,15 +82,15 @@  discard block
 block discarded – undo
82 82
 	*	@param $test_version bool if set to flase, does not test database version of trapDB
83 83
 	*	@return array<integer,mixed>|mixed : if test=false, returns DB connexion, else array(error_num,message) or null on error.
84 84
 	*/
85
-	public function getDbByName($DBname,$test=false,$test_version=true)
85
+	public function getDbByName($DBname, $test=false, $test_version=true)
86 86
 	{
87 87
 		try 
88 88
 		{
89
-			$dbconn = IcingaDbConnection::fromResourceName($DBname);
89
+			$dbconn=IcingaDbConnection::fromResourceName($DBname);
90 90
 		} 
91 91
 		catch (Exception $e)
92 92
 		{
93
-			if ($test) return array(2,$DBname);
93
+			if ($test) return array(2, $DBname);
94 94
 			$this->redirectNow('trapdirector/settings?dberror=2');
95 95
 			return null;
96 96
 		}
@@ -101,37 +101,37 @@  discard block
 block discarded – undo
101 101
 			}
102 102
 			catch (Exception $e) 
103 103
 			{
104
-				if ($test) return array(3,$DBname,$e->getMessage());
104
+				if ($test) return array(3, $DBname, $e->getMessage());
105 105
 				$this->redirectNow('trapdirector/settings?dberror=3');
106 106
 				return null;
107 107
 			}
108 108
 			try
109 109
 			{
110
-				$query = $db->select()
111
-					->from($this->getModuleConfig()->getDbConfigTableName(),'value')
110
+				$query=$db->select()
111
+					->from($this->getModuleConfig()->getDbConfigTableName(), 'value')
112 112
 					->where('name=\'db_version\'');
113 113
 				$version=$db->fetchRow($query);
114
-				if ( ($version == null) || ! property_exists($version,'value') )
114
+				if (($version == null) || !property_exists($version, 'value'))
115 115
 				{
116
-					if ($test) return array(4,$DBname);
116
+					if ($test) return array(4, $DBname);
117 117
 					$this->redirectNow('trapdirector/settings?dberror=4');
118 118
 					return null;
119 119
 				}
120 120
 				if ($version->value < $this->getModuleConfig()->getDbMinVersion()) 
121 121
 				{
122
-					if ($test) return array(5,$version->value,$this->getModuleConfig()->getDbMinVersion());
122
+					if ($test) return array(5, $version->value, $this->getModuleConfig()->getDbMinVersion());
123 123
 					$this->redirectNow('trapdirector/settings?dberror=5');
124 124
 					return null;
125 125
 				}
126 126
 			}
127 127
 			catch (Exception $e) 
128 128
 			{
129
-				if ($test) return array(3,$DBname,$e->getMessage());
129
+				if ($test) return array(3, $DBname, $e->getMessage());
130 130
 				$this->redirectNow('trapdirector/settings?dberror=4');
131 131
 				return null;
132 132
 			}
133 133
 		}
134
-		if ($test) return array(0,'');
134
+		if ($test) return array(0, '');
135 135
 		return $dbconn;
136 136
 	}
137 137
 
@@ -142,17 +142,17 @@  discard block
 block discarded – undo
142 142
 	 */
143 143
 	public function getDb($test=false)
144 144
 	{
145
-		if ($this->trapDB != null && $test = false) return $this->trapDB;
145
+		if ($this->trapDB != null && $test=false) return $this->trapDB;
146 146
 		
147 147
 		$dbresource=$this->Config()->get('config', 'database');
148 148
 		
149
-		if ( ! $dbresource )
149
+		if (!$dbresource)
150 150
 		{	
151
-			if ($test) return array(1,'');
151
+			if ($test) return array(1, '');
152 152
 			$this->redirectNow('trapdirector/settings?dberror=1');
153 153
 			return null;
154 154
 		}
155
-		$retDB=$this->getDbByName($dbresource,$test,true);
155
+		$retDB=$this->getDbByName($dbresource, $test, true);
156 156
 		if ($test == true) return $retDB;
157 157
 		$this->trapDB=$retDB;
158 158
 		return $this->trapDB;
@@ -160,78 +160,78 @@  discard block
 block discarded – undo
160 160
 	
161 161
 	public function getIdoDb($test=false)
162 162
 	{
163
-		if ($this->icingaDB != null && $test = false) return $this->icingaDB;
163
+		if ($this->icingaDB != null && $test=false) return $this->icingaDB;
164 164
 		// TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
165
-		$dbresource=$this->Config()->get('config', 'IDOdatabase');;
165
+		$dbresource=$this->Config()->get('config', 'IDOdatabase'); ;
166 166
 
167
-		if ( ! $dbresource )
167
+		if (!$dbresource)
168 168
 		{
169
-		    if ($test) return array(1,'No database in config.ini');
169
+		    if ($test) return array(1, 'No database in config.ini');
170 170
 		    $this->redirectNow('trapdirector/settings?idodberror=1');
171 171
 		    return null;
172 172
 		}
173 173
 		
174 174
 		try
175 175
 		{
176
-		    $dbconn = IcingaDbConnection::fromResourceName($dbresource);
176
+		    $dbconn=IcingaDbConnection::fromResourceName($dbresource);
177 177
 		}
178 178
 		catch (Exception $e)
179 179
 		{
180
-		    if ($test) return array(2,"Database $dbresource does not exists in IcingaWeb2");
180
+		    if ($test) return array(2, "Database $dbresource does not exists in IcingaWeb2");
181 181
 		    $this->redirectNow('trapdirector/settings?idodberror=2');
182 182
 		    return null;
183 183
 		}
184 184
 		
185 185
 		if ($test == false) 
186 186
 		{ 
187
-			$this->icingaDB = $dbconn; 
187
+			$this->icingaDB=$dbconn; 
188 188
 			return $this->icingaDB;
189 189
 		}
190 190
 		
191 191
 		try
192 192
 		{
193
-		    $query = $dbconn->select()
194
-		    ->from('icinga_dbversion',array('version'));
193
+		    $query=$dbconn->select()
194
+		    ->from('icinga_dbversion', array('version'));
195 195
 		    $version=$dbconn->fetchRow($query);
196
-		    if ( ($version == null) || ! property_exists($version,'version') )
196
+		    if (($version == null) || !property_exists($version, 'version'))
197 197
 		    {
198
-		        return array(4,"$dbresource does not look like an IDO database");
198
+		        return array(4, "$dbresource does not look like an IDO database");
199 199
 		    }
200 200
 		}
201 201
 		catch (Exception $e)
202 202
 		{
203
-			return array(3,"Error connecting to $dbresource : " . $e->getMessage());
203
+			return array(3, "Error connecting to $dbresource : ".$e->getMessage());
204 204
 		}
205 205
 		
206
-		return array(0,'');
206
+		return array(0, '');
207 207
 	}
208 208
 	
209
-    protected function applyPaginationLimits(Paginatable $paginatable, $limit = 25, $offset = null)
209
+    protected function applyPaginationLimits(Paginatable $paginatable, $limit=25, $offset=null)
210 210
     {
211
-        $limit = $this->params->get('limit', $limit);
212
-        $page = $this->params->get('page', $offset);
211
+        $limit=$this->params->get('limit', $limit);
212
+        $page=$this->params->get('page', $offset);
213 213
 
214 214
         $paginatable->limit($limit, $page > 0 ? ($page - 1) * $limit : 0);
215 215
 
216 216
         return $paginatable;
217 217
     }	
218 218
 	
219
-	public function displayExitError($source,$message)
219
+	public function displayExitError($source, $message)
220 220
 	{	// TODO : check better ways to transmit data (with POST ?)
221 221
 		$this->redirectNow('trapdirector/error?source='.$source.'&message='.$message);
222 222
 	}
223 223
 	
224 224
 	protected function checkReadPermission()
225 225
 	{
226
-        if (! $this->Auth()->hasPermission('trapdirector/view')) {
227
-            $this->displayExitError('Permissions','No permission fo view content');
226
+        if (!$this->Auth()->hasPermission('trapdirector/view')) {
227
+            $this->displayExitError('Permissions', 'No permission fo view content');
228 228
         }		
229 229
 	}
230 230
 
231 231
 	protected function checkConfigPermission()
232 232
 	{
233
-        if (! $this->Auth()->hasPermission('trapdirector/config')) {
234
-            $this->displayExitError('Permissions','No permission fo configure');
233
+        if (!$this->Auth()->hasPermission('trapdirector/config')) {
234
+            $this->displayExitError('Permissions', 'No permission fo configure');
235 235
         }		
236 236
 	}
237 237
 	
@@ -242,10 +242,10 @@  discard block
 block discarded – undo
242 242
      */
243 243
 	protected function checkModuleConfigPermission($check=0)
244 244
 	{
245
-        if (! $this->Auth()->hasPermission('trapdirector/module_config')) {
245
+        if (!$this->Auth()->hasPermission('trapdirector/module_config')) {
246 246
             if ($check == 0)
247 247
             {
248
-                $this->displayExitError('Permissions','No permission fo configure module');
248
+                $this->displayExitError('Permissions', 'No permission fo configure module');
249 249
             }
250 250
             return false;
251 251
         }
@@ -257,10 +257,10 @@  discard block
 block discarded – undo
257 257
 	{ // TODO : try/catch here ? or within caller
258 258
 		if ($this->trapClass == null)
259 259
 		{
260
-			require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
260
+			require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
261 261
 			$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
262 262
 			//$debug_level=4;
263
-			$this->trapClass = new Trap($icingaweb2_etc);
263
+			$this->trapClass=new Trap($icingaweb2_etc);
264 264
 			//$Trap->setLogging($debug_level,'syslog');
265 265
 		}
266 266
 		return $this->trapClass;
@@ -294,12 +294,12 @@  discard block
 block discarded – undo
294 294
 	protected function getHostByIP($ip) 
295 295
 	{
296 296
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
297
-		$db = $this->getIdoDb()->getConnection();
297
+		$db=$this->getIdoDb()->getConnection();
298 298
 		// TODO : check for SQL injections
299 299
 		$query=$db->select()
300 300
 				->from(
301 301
 					array('a' => 'icinga_objects'),
302
-					array('name' => 'a.name1','id' => 'object_id'))
302
+					array('name' => 'a.name1', 'id' => 'object_id'))
303 303
 				->join(
304 304
 					array('b' => 'icinga_hosts'),
305 305
 					'b.host_object_id=a.object_id',
@@ -315,12 +315,12 @@  discard block
 block discarded – undo
315 315
 	protected function getHostByName($name) 
316 316
 	{
317 317
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
318
-		$db = $this->getIdoDb()->getConnection();
318
+		$db=$this->getIdoDb()->getConnection();
319 319
 		// TODO : check for SQL injections
320 320
 		$query=$db->select()
321 321
 				->from(
322 322
 					array('a' => 'icinga_objects'),
323
-					array('name' => 'a.name1','id' => 'object_id'))
323
+					array('name' => 'a.name1', 'id' => 'object_id'))
324 324
 				->join(
325 325
 					array('b' => 'icinga_hosts'),
326 326
 					'b.host_object_id=a.object_id',
@@ -336,12 +336,12 @@  discard block
 block discarded – undo
336 336
 	protected function getHostGroupByName($ip) 
337 337
 	{
338 338
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
339
-		$db = $this->getIdoDb()->getConnection();
339
+		$db=$this->getIdoDb()->getConnection();
340 340
 		// TODO : check for SQL injections
341 341
 		$query=$db->select()
342 342
 				->from(
343 343
 					array('a' => 'icinga_objects'),
344
-					array('name' => 'a.name1','id' => 'object_id'))
344
+					array('name' => 'a.name1', 'id' => 'object_id'))
345 345
 				->join(
346 346
 					array('b' => 'icinga_hostgroups'),
347 347
 					'b.hostgroup_object_id=a.object_id',
@@ -357,8 +357,8 @@  discard block
 block discarded – undo
357 357
 	*/
358 358
 	protected function getHostInfoByID($id) 
359 359
 	{
360
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
361
-		$db = $this->getIdoDb()->getConnection();
360
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
361
+		$db=$this->getIdoDb()->getConnection();
362 362
 		$query=$db->select()
363 363
 				->from(
364 364
 					array('a' => 'icinga_objects'),
@@ -378,17 +378,17 @@  discard block
 block discarded – undo
378 378
 	*/
379 379
 	protected function getHostByObjectID($id) // TODO : duplicate of getHostInfoByID above
380 380
 	{
381
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
382
-		$db = $this->getIdoDb()->getConnection();
381
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
382
+		$db=$this->getIdoDb()->getConnection();
383 383
 		$query=$db->select()
384 384
 				->from(
385 385
 					array('a' => 'icinga_objects'),
386
-					array('name' => 'a.name1','id' => 'a.object_id'))
386
+					array('name' => 'a.name1', 'id' => 'a.object_id'))
387 387
 				->join(
388 388
 					array('b' => 'icinga_hosts'),
389 389
 					'b.host_object_id=a.object_id',
390
-					array('display_name' => 'b.display_name' , 'ip' => 'b.address', 'ip6' => 'b.address6'))
391
-				->where('a.object_id = ?',$id);
390
+					array('display_name' => 'b.display_name', 'ip' => 'b.address', 'ip6' => 'b.address6'))
391
+				->where('a.object_id = ?', $id);
392 392
 		return $db->fetchRow($query);
393 393
 	}	
394 394
 	
@@ -400,16 +400,16 @@  discard block
 block discarded – undo
400 400
 	protected function getServicesByHostid($id) 
401 401
 	{
402 402
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
403
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
404
-		$db = $this->getIdoDb()->getConnection();
403
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
404
+		$db=$this->getIdoDb()->getConnection();
405 405
 		$query=$db->select()
406 406
 				->from(
407 407
 					array('s' => 'icinga_services'),
408
-					array('name' => 's.display_name','id' => 's.service_object_id'))
408
+					array('name' => 's.display_name', 'id' => 's.service_object_id'))
409 409
 				->join(
410 410
 					array('a' => 'icinga_objects'),
411 411
 					's.service_object_id=a.object_id',
412
-					array('is_active'=>'a.is_active','name2'=>'a.name2'))
412
+					array('is_active'=>'a.is_active', 'name2'=>'a.name2'))
413 413
 				->where('s.host_object_id='.$id.' AND a.is_active = 1');
414 414
 
415 415
 		return $db->fetchAll($query);
@@ -423,8 +423,8 @@  discard block
 block discarded – undo
423 423
 	*/
424 424
 	protected function getServicesByHostGroupid($id) 
425 425
 	{		
426
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
427
-		$db = $this->getIdoDb()->getConnection();
426
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
427
+		$db=$this->getIdoDb()->getConnection();
428 428
 		$query=$db->select()
429 429
 				->from(
430 430
 					array('s' => 'icinga_hostgroup_members'),
@@ -441,11 +441,11 @@  discard block
 block discarded – undo
441 441
 		foreach ($hosts as $key => $host)
442 442
 		{ // For each host, get all services and add in common_services if not found or add counter
443 443
 			$host_services=$this->getServicesByHostid($host->host_object_id);
444
-			foreach($host_services as $service)
444
+			foreach ($host_services as $service)
445 445
 			{
446 446
 				if (isset($common_services[$service->name2]['num']))
447 447
 				{
448
-					$common_services[$service->name2]['num'] +=1;
448
+					$common_services[$service->name2]['num']+=1;
449 449
 				}
450 450
 				else
451 451
 				{
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
 		{
462 462
 		    if ($common_services[$key]['num'] == $num_hosts)
463 463
 			{
464
-				array_push($result,array($key,$common_services[$key]['name']));
464
+				array_push($result, array($key, $common_services[$key]['name']));
465 465
 			}
466 466
 		}
467 467
 		
@@ -474,9 +474,9 @@  discard block
 block discarded – undo
474 474
 	*	@param $name string service name
475 475
 	*	@return array  service id
476 476
 	*/
477
-	protected function getServiceIDByName($hostname,$name) 
477
+	protected function getServiceIDByName($hostname, $name) 
478 478
 	{
479
-		$db = $this->getIdoDb()->getConnection();
479
+		$db=$this->getIdoDb()->getConnection();
480 480
 		if ($name == null)
481 481
 		{
482 482
 			return array();
@@ -485,7 +485,7 @@  discard block
 block discarded – undo
485 485
 		$query=$db->select()
486 486
 				->from(
487 487
 					array('s' => 'icinga_services'),
488
-					array('name' => 's.display_name','id' => 's.service_object_id'))
488
+					array('name' => 's.display_name', 'id' => 's.service_object_id'))
489 489
 				->join(
490 490
 					array('a' => 'icinga_objects'),
491 491
 					's.service_object_id=a.object_id',
@@ -503,12 +503,12 @@  discard block
 block discarded – undo
503 503
 	protected function getObjectNameByid($id) 
504 504
 	{
505 505
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
506
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
507
-		$db = $this->getIdoDb()->getConnection();
506
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
507
+		$db=$this->getIdoDb()->getConnection();
508 508
 		$query=$db->select()
509 509
 				->from(
510 510
 					array('a' => 'icinga_objects'),
511
-					array('name1' => 'a.name1','name2' => 'a.name2'))
511
+					array('name1' => 'a.name1', 'name2' => 'a.name2'))
512 512
 				->where('a.object_id='.$id.' AND a.is_active = 1');
513 513
 
514 514
 		return $db->fetchRow($query);
@@ -521,17 +521,17 @@  discard block
 block discarded – undo
521 521
 	protected function addHandlerRule($params)
522 522
 	{
523 523
 		// TODO Check for rule consistency
524
-		$db = $this->getDb()->getConnection();
524
+		$db=$this->getDb()->getConnection();
525 525
 		// Add last modified date = creation date and username
526
-		$params['created'] = new Zend_Db_Expr('NOW()');
527
-		$params['modified'] = new 	Zend_Db_Expr('NOW()');
528
-		$params['modifier'] = $this->Auth()->getUser()->getUsername();
526
+		$params['created']=new Zend_Db_Expr('NOW()');
527
+		$params['modified']=new 	Zend_Db_Expr('NOW()');
528
+		$params['modifier']=$this->Auth()->getUser()->getUsername();
529 529
 		
530 530
 		$query=$db->insert(
531 531
 			$this->getModuleConfig()->getTrapRuleName(),
532 532
 			$params
533 533
 		);
534
-		if($query==false)
534
+		if ($query == false)
535 535
 		{
536 536
 		  return null;
537 537
 		}
@@ -543,13 +543,13 @@  discard block
 block discarded – undo
543 543
 	*   @param integer $ruleID : rule id in db
544 544
 	*	@return array affected rows
545 545
 	*/
546
-	protected function updateHandlerRule($params,$ruleID)
546
+	protected function updateHandlerRule($params, $ruleID)
547 547
 	{
548 548
 		// TODO Check for rule consistency
549
-		$db = $this->getDb()->getConnection();
549
+		$db=$this->getDb()->getConnection();
550 550
 		// Add last modified date = creation date and username
551
-		$params['modified'] = new 	Zend_Db_Expr('NOW()');
552
-		$params['modifier'] = $this->Auth()->getUser()->getUsername();
551
+		$params['modified']=new 	Zend_Db_Expr('NOW()');
552
+		$params['modifier']=$this->Auth()->getUser()->getUsername();
553 553
 		
554 554
 		$numRows=$db->update(
555 555
 			$this->getModuleConfig()->getTrapRuleName(),
@@ -564,8 +564,8 @@  discard block
 block discarded – undo
564 564
 	*/
565 565
 	protected function deleteRule($ruleID)
566 566
 	{
567
-		if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
568
-		$db = $this->getDb()->getConnection();
567
+		if (!preg_match('/^[0-9]+$/', $ruleID)) { throw new Exception('Invalid id'); }
568
+		$db=$this->getDb()->getConnection();
569 569
 		
570 570
 		$query=$db->delete(
571 571
 			$this->getModuleConfig()->getTrapRuleName(),
@@ -578,10 +578,10 @@  discard block
 block discarded – undo
578 578
 	*	@param $ip string source IP (v4 or v6)
579 579
 	*	@param $oid string oid
580 580
 	*/
581
-	protected function deleteTrap($ip,$oid)
581
+	protected function deleteTrap($ip, $oid)
582 582
 	{
583 583
 		
584
-		$db = $this->getDb()->getConnection();
584
+		$db=$this->getDb()->getConnection();
585 585
 		$condition=null;
586 586
 		if ($ip != null)
587 587
 		{
@@ -589,10 +589,10 @@  discard block
 block discarded – undo
589 589
 		}
590 590
 		if ($oid != null)
591 591
 		{
592
-			$condition=($condition===null)?'':$condition.' AND ';
592
+			$condition=($condition === null) ? '' : $condition.' AND ';
593 593
 			$condition.="trap_oid='$oid'";
594 594
 		}
595
-		if($condition === null) return null;
595
+		if ($condition === null) return null;
596 596
 		$query=$db->delete(
597 597
 			$this->getModuleConfig()->getTrapTableName(),
598 598
 			$condition
@@ -606,10 +606,10 @@  discard block
 block discarded – undo
606 606
 	*	@param $ip string source IP (v4 or v6)
607 607
 	*	@param $oid string oid
608 608
 	*/
609
-	protected function countTrap($ip,$oid)
609
+	protected function countTrap($ip, $oid)
610 610
 	{
611 611
 		
612
-		$db = $this->getDb()->getConnection();
612
+		$db=$this->getDb()->getConnection();
613 613
 		$condition=null;
614 614
 		if ($ip != null)
615 615
 		{
@@ -617,10 +617,10 @@  discard block
 block discarded – undo
617 617
 		}
618 618
 		if ($oid != null)
619 619
 		{
620
-			$condition=($condition===null)?'':$condition.' AND ';
620
+			$condition=($condition === null) ? '' : $condition.' AND ';
621 621
 			$condition.="trap_oid='$oid'";
622 622
 		}
623
-		if($condition === null) return 0;
623
+		if ($condition === null) return 0;
624 624
 		$query=$db->select()
625 625
 			->from(
626 626
 				$this->getModuleConfig()->getTrapTableName(),
@@ -636,27 +636,27 @@  discard block
 block discarded – undo
636 636
 	protected function getDBConfigValue($element)
637 637
 	{
638 638
 	
639
-		$db = $this->getDb()->getConnection();
639
+		$db=$this->getDb()->getConnection();
640 640
 		
641 641
 		$query=$db->select()
642 642
 			->from(
643 643
 				$this->getModuleConfig()->getDbConfigTableName(),
644 644
 				array('value'=>'value'))
645
-			->where('name=?',$element);
645
+			->where('name=?', $element);
646 646
 		$return_row=$db->fetchRow($query);
647
-		if ($return_row==null)  // value does not exists
647
+		if ($return_row == null)  // value does not exists
648 648
 		{
649 649
 			$default=$this->getModuleConfig()->getDBConfigDefaults();
650
-			if ( ! isset($default[$element])) return null; // no default and not value
650
+			if (!isset($default[$element])) return null; // no default and not value
651 651
 			
652
-			$this->addDBConfigValue($element,$default[$element]);
652
+			$this->addDBConfigValue($element, $default[$element]);
653 653
 			return $default[$element];
654 654
 		}
655 655
 		if ($return_row->value == null) // value id empty
656 656
 		{
657 657
 			$default=$this->getModuleConfig()->getDBConfigDefaults();
658
-			if ( ! isset($default[$element])) return null; // no default and not value
659
-			$this->setDBConfigValue($element,$default[$element]);
658
+			if (!isset($default[$element])) return null; // no default and not value
659
+			$this->setDBConfigValue($element, $default[$element]);
660 660
 			return $default[$element];			
661 661
 		}
662 662
 		return $return_row->value;		
@@ -667,10 +667,10 @@  discard block
 block discarded – undo
667 667
 	*   @param string $value : value
668 668
 	*/
669 669
 		
670
-	protected function addDBConfigValue($element,$value)
670
+	protected function addDBConfigValue($element, $value)
671 671
 	{
672 672
 	
673
-		$db = $this->getDb()->getConnection();
673
+		$db=$this->getDb()->getConnection();
674 674
 		
675 675
 		$query=$db->insert(
676 676
 				$this->getModuleConfig()->getDbConfigTableName(),
@@ -686,10 +686,10 @@  discard block
 block discarded – undo
686 686
 	*	@param string $element : name of config element
687 687
 	*   @param string $value : value
688 688
 	*/
689
-	protected function setDBConfigValue($element,$value)
689
+	protected function setDBConfigValue($element, $value)
690 690
 	{
691 691
 	
692
-		$db = $this->getDb()->getConnection();
692
+		$db=$this->getDb()->getConnection();
693 693
 		$query=$db->update(
694 694
 				$this->getModuleConfig()->getDbConfigTableName(),
695 695
 				array('value'=>$value),
@@ -704,10 +704,10 @@  discard block
 block discarded – undo
704 704
 	protected function isDirectorInstalled()
705 705
 	{
706 706
 	    $output=array();
707
-	    exec('icingacli module list',$output);
707
+	    exec('icingacli module list', $output);
708 708
 	    foreach ($output as $line)
709 709
 		{
710
-			if (preg_match('/^director .*enabled/',$line))
710
+			if (preg_match('/^director .*enabled/', $line))
711 711
 			{
712 712
 				return true;
713 713
 			}
Please login to merge, or discard this patch.
Braces   +62 added lines, -30 removed lines patch added patch discarded remove patch
@@ -87,10 +87,11 @@  discard block
 block discarded – undo
87 87
 		try 
88 88
 		{
89 89
 			$dbconn = IcingaDbConnection::fromResourceName($DBname);
90
-		} 
91
-		catch (Exception $e)
90
+		} catch (Exception $e)
92 91
 		{
93
-			if ($test) return array(2,$DBname);
92
+			if ($test) {
93
+				return array(2,$DBname);
94
+			}
94 95
 			$this->redirectNow('trapdirector/settings?dberror=2');
95 96
 			return null;
96 97
 		}
@@ -98,10 +99,11 @@  discard block
 block discarded – undo
98 99
 			try 
99 100
 			{
100 101
 				$db=$dbconn->getConnection();
101
-			}
102
-			catch (Exception $e) 
102
+			} catch (Exception $e) 
103 103
 			{
104
-				if ($test) return array(3,$DBname,$e->getMessage());
104
+				if ($test) {
105
+					return array(3,$DBname,$e->getMessage());
106
+				}
105 107
 				$this->redirectNow('trapdirector/settings?dberror=3');
106 108
 				return null;
107 109
 			}
@@ -113,25 +115,32 @@  discard block
 block discarded – undo
113 115
 				$version=$db->fetchRow($query);
114 116
 				if ( ($version == null) || ! property_exists($version,'value') )
115 117
 				{
116
-					if ($test) return array(4,$DBname);
118
+					if ($test) {
119
+						return array(4,$DBname);
120
+					}
117 121
 					$this->redirectNow('trapdirector/settings?dberror=4');
118 122
 					return null;
119 123
 				}
120 124
 				if ($version->value < $this->getModuleConfig()->getDbMinVersion()) 
121 125
 				{
122
-					if ($test) return array(5,$version->value,$this->getModuleConfig()->getDbMinVersion());
126
+					if ($test) {
127
+						return array(5,$version->value,$this->getModuleConfig()->getDbMinVersion());
128
+					}
123 129
 					$this->redirectNow('trapdirector/settings?dberror=5');
124 130
 					return null;
125 131
 				}
126
-			}
127
-			catch (Exception $e) 
132
+			} catch (Exception $e) 
128 133
 			{
129
-				if ($test) return array(3,$DBname,$e->getMessage());
134
+				if ($test) {
135
+					return array(3,$DBname,$e->getMessage());
136
+				}
130 137
 				$this->redirectNow('trapdirector/settings?dberror=4');
131 138
 				return null;
132 139
 			}
133 140
 		}
134
-		if ($test) return array(0,'');
141
+		if ($test) {
142
+			return array(0,'');
143
+		}
135 144
 		return $dbconn;
136 145
 	}
137 146
 
@@ -142,31 +151,41 @@  discard block
 block discarded – undo
142 151
 	 */
143 152
 	public function getDb($test=false)
144 153
 	{
145
-		if ($this->trapDB != null && $test = false) return $this->trapDB;
154
+		if ($this->trapDB != null && $test = false) {
155
+			return $this->trapDB;
156
+		}
146 157
 		
147 158
 		$dbresource=$this->Config()->get('config', 'database');
148 159
 		
149 160
 		if ( ! $dbresource )
150 161
 		{	
151
-			if ($test) return array(1,'');
162
+			if ($test) {
163
+				return array(1,'');
164
+			}
152 165
 			$this->redirectNow('trapdirector/settings?dberror=1');
153 166
 			return null;
154 167
 		}
155 168
 		$retDB=$this->getDbByName($dbresource,$test,true);
156
-		if ($test == true) return $retDB;
169
+		if ($test == true) {
170
+			return $retDB;
171
+		}
157 172
 		$this->trapDB=$retDB;
158 173
 		return $this->trapDB;
159 174
 	}
160 175
 	
161 176
 	public function getIdoDb($test=false)
162 177
 	{
163
-		if ($this->icingaDB != null && $test = false) return $this->icingaDB;
178
+		if ($this->icingaDB != null && $test = false) {
179
+			return $this->icingaDB;
180
+		}
164 181
 		// TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
165 182
 		$dbresource=$this->Config()->get('config', 'IDOdatabase');;
166 183
 
167 184
 		if ( ! $dbresource )
168 185
 		{
169
-		    if ($test) return array(1,'No database in config.ini');
186
+		    if ($test) {
187
+		    	return array(1,'No database in config.ini');
188
+		    }
170 189
 		    $this->redirectNow('trapdirector/settings?idodberror=1');
171 190
 		    return null;
172 191
 		}
@@ -174,10 +193,11 @@  discard block
 block discarded – undo
174 193
 		try
175 194
 		{
176 195
 		    $dbconn = IcingaDbConnection::fromResourceName($dbresource);
177
-		}
178
-		catch (Exception $e)
196
+		} catch (Exception $e)
179 197
 		{
180
-		    if ($test) return array(2,"Database $dbresource does not exists in IcingaWeb2");
198
+		    if ($test) {
199
+		    	return array(2,"Database $dbresource does not exists in IcingaWeb2");
200
+		    }
181 201
 		    $this->redirectNow('trapdirector/settings?idodberror=2');
182 202
 		    return null;
183 203
 		}
@@ -197,8 +217,7 @@  discard block
 block discarded – undo
197 217
 		    {
198 218
 		        return array(4,"$dbresource does not look like an IDO database");
199 219
 		    }
200
-		}
201
-		catch (Exception $e)
220
+		} catch (Exception $e)
202 221
 		{
203 222
 			return array(3,"Error connecting to $dbresource : " . $e->getMessage());
204 223
 		}
@@ -446,8 +465,7 @@  discard block
 block discarded – undo
446 465
 				if (isset($common_services[$service->name2]['num']))
447 466
 				{
448 467
 					$common_services[$service->name2]['num'] +=1;
449
-				}
450
-				else
468
+				} else
451 469
 				{
452 470
 					$common_services[$service->name2]['num']=1;
453 471
 					$common_services[$service->name2]['name']=$service->name;
@@ -592,7 +610,9 @@  discard block
 block discarded – undo
592 610
 			$condition=($condition===null)?'':$condition.' AND ';
593 611
 			$condition.="trap_oid='$oid'";
594 612
 		}
595
-		if($condition === null) return null;
613
+		if($condition === null) {
614
+			return null;
615
+		}
596 616
 		$query=$db->delete(
597 617
 			$this->getModuleConfig()->getTrapTableName(),
598 618
 			$condition
@@ -620,7 +640,9 @@  discard block
 block discarded – undo
620 640
 			$condition=($condition===null)?'':$condition.' AND ';
621 641
 			$condition.="trap_oid='$oid'";
622 642
 		}
623
-		if($condition === null) return 0;
643
+		if($condition === null) {
644
+			return 0;
645
+		}
624 646
 		$query=$db->select()
625 647
 			->from(
626 648
 				$this->getModuleConfig()->getTrapTableName(),
@@ -644,18 +666,28 @@  discard block
 block discarded – undo
644 666
 				array('value'=>'value'))
645 667
 			->where('name=?',$element);
646 668
 		$return_row=$db->fetchRow($query);
647
-		if ($return_row==null)  // value does not exists
669
+		if ($return_row==null) {
670
+			// value does not exists
648 671
 		{
649 672
 			$default=$this->getModuleConfig()->getDBConfigDefaults();
650
-			if ( ! isset($default[$element])) return null; // no default and not value
673
+		}
674
+			if ( ! isset($default[$element])) {
675
+				return null;
676
+			}
677
+			// no default and not value
651 678
 			
652 679
 			$this->addDBConfigValue($element,$default[$element]);
653 680
 			return $default[$element];
654 681
 		}
655
-		if ($return_row->value == null) // value id empty
682
+		if ($return_row->value == null) {
683
+			// value id empty
656 684
 		{
657 685
 			$default=$this->getModuleConfig()->getDBConfigDefaults();
658
-			if ( ! isset($default[$element])) return null; // no default and not value
686
+		}
687
+			if ( ! isset($default[$element])) {
688
+				return null;
689
+			}
690
+			// no default and not value
659 691
 			$this->setDBConfigValue($element,$default[$element]);
660 692
 			return $default[$element];			
661 693
 		}
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Database.php 3 patches
Braces   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -171,8 +171,7 @@  discard block
 block discarded – undo
171 171
                 if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
172 172
                 {
173 173
                     $cur_table='table '.$cur_table_array[1];
174
-                }
175
-                else
174
+                } else
176 175
                 {
177 176
                     $cur_table='secret SQL stuff :-)';
178 177
                 }
@@ -217,8 +216,7 @@  discard block
 block discarded – undo
217 216
         if ($this->trapDBType == 'pgsql')
218 217
         {
219 218
             $prefix .= 'update_pgsql/schema_';
220
-        }
221
-        else
219
+        } else
222 220
         {
223 221
             $prefix .= 'update_sql/schema_';
224 222
         }
@@ -264,7 +262,10 @@  discard block
 block discarded – undo
264 262
             $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
265 263
             while (($line=fgets($input_stream)) !== false)
266 264
             {
267
-                if (preg_match('/^#/', $line)) continue; // ignore comment lines
265
+                if (preg_match('/^#/', $line)) {
266
+                	continue;
267
+                }
268
+                // ignore comment lines
268 269
                 $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
269 270
                 if (preg_match('/; *$/', $newline))
270 271
                 {
@@ -276,8 +277,7 @@  discard block
 block discarded – undo
276 277
                     if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
277 278
                     {
278 279
                         $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
279
-                    }
280
-                    else
280
+                    } else
281 281
                     {
282 282
                         $cur_table='secret SQL stuff :-)';
283 283
                         //$cur_table=$newline;
Please login to merge, or discard this patch.
Indentation   +296 added lines, -296 removed lines patch added patch discarded remove patch
@@ -11,330 +11,330 @@
 block discarded – undo
11 11
 class Database
12 12
 {
13 13
 
14
-    // Databases
15
-    protected $trapDB=null; //< trap database
16
-    protected $idoDB=null; //< ido database
17
-    public $trapDBType; //< Type of database for traps (mysql, pgsql)
18
-    public $idoDBType; //< Type of database for ido (mysql, pgsql)
14
+	// Databases
15
+	protected $trapDB=null; //< trap database
16
+	protected $idoDB=null; //< ido database
17
+	public $trapDBType; //< Type of database for traps (mysql, pgsql)
18
+	public $idoDBType; //< Type of database for ido (mysql, pgsql)
19 19
     
20
-    protected $trapDSN; //< trap database connection params
21
-    protected $trapUsername; //< trap database connection params
22
-    protected $trapPass; //< trap database connection params
23
-    public $dbPrefix; //< database tables prefix
20
+	protected $trapDSN; //< trap database connection params
21
+	protected $trapUsername; //< trap database connection params
22
+	protected $trapPass; //< trap database connection params
23
+	public $dbPrefix; //< database tables prefix
24 24
     
25
-    protected $idoSet; //< bool true is ido database set
26
-    protected $idoDSN; //< trap database connection params
27
-    protected $idoUsername; //< trap database connection params
28
-    protected $idoPass; //< trap database connection params
25
+	protected $idoSet; //< bool true is ido database set
26
+	protected $idoDSN; //< trap database connection params
27
+	protected $idoUsername; //< trap database connection params
28
+	protected $idoPass; //< trap database connection params
29 29
     
30
-    // Logging function
30
+	// Logging function
31 31
     
32
-    protected $logging; //< logging class
32
+	protected $logging; //< logging class
33 33
     
34
-    /**
35
-     * @param Logging $logClass : where to log
36
-     * @param array $dbParam : array of named params  type,host,dbname,username,[port],[password]
37
-     */
38
-    function __construct($logClass,$dbParam,$dbPrefix)
39
-    {
40
-        $this->logging=$logClass;
41
-        $this->dbPrefix=$dbPrefix;
34
+	/**
35
+	 * @param Logging $logClass : where to log
36
+	 * @param array $dbParam : array of named params  type,host,dbname,username,[port],[password]
37
+	 */
38
+	function __construct($logClass,$dbParam,$dbPrefix)
39
+	{
40
+		$this->logging=$logClass;
41
+		$this->dbPrefix=$dbPrefix;
42 42
         
43
-        $this->trapDSN=$this->setupDSN($dbParam);
44
-        $this->trapUsername = $dbParam['username'];
45
-        $this->trapPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
46
-        $this->trapDBType=$dbParam['db'];
47
-        $this->logging->log('DSN : '.$this->trapDSN. ';user '.$this->trapUsername.' / prefix : '. $this->dbPrefix,INFO);
48
-        $this->db_connect_trap();
43
+		$this->trapDSN=$this->setupDSN($dbParam);
44
+		$this->trapUsername = $dbParam['username'];
45
+		$this->trapPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
46
+		$this->trapDBType=$dbParam['db'];
47
+		$this->logging->log('DSN : '.$this->trapDSN. ';user '.$this->trapUsername.' / prefix : '. $this->dbPrefix,INFO);
48
+		$this->db_connect_trap();
49 49
         
50
-    }
50
+	}
51 51
     
52
-    /**
53
-     * Setup and connect to IDO database
54
-     * @param array $dbParam : array of named params
55
-     */
56
-    public function setupIDO($dbParam)
57
-    {
58
-        $this->idoDSN=$this->setupDSN($dbParam);
59
-        $this->idoUsername = $dbParam['username'];
60
-        $this->idoPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
61
-        $this->logging->log('DSN : '.$this->idoDSN. ';user '.$this->idoUsername,INFO);
62
-        $this->idoDBType=$dbParam['db'];
63
-        $this->db_connect_ido();
64
-    }
52
+	/**
53
+	 * Setup and connect to IDO database
54
+	 * @param array $dbParam : array of named params
55
+	 */
56
+	public function setupIDO($dbParam)
57
+	{
58
+		$this->idoDSN=$this->setupDSN($dbParam);
59
+		$this->idoUsername = $dbParam['username'];
60
+		$this->idoPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
61
+		$this->logging->log('DSN : '.$this->idoDSN. ';user '.$this->idoUsername,INFO);
62
+		$this->idoDBType=$dbParam['db'];
63
+		$this->db_connect_ido();
64
+	}
65 65
     
66
-    /**
67
-     * Connect to IDO database
68
-     * @return \PDO
69
-     */
70
-    public function db_connect_ido()
71
-    {
72
-        if ($this->idoDB != null) {
73
-            // Check if connection is still alive
74
-            try {
75
-                $this->idoDB->query('select 1')->fetchColumn();
76
-                return $this->idoDB;
77
-            } catch (Exception $e) {
78
-                // select 1 failed, try to reconnect.
79
-                $this->logging->log('Database IDO connection lost, reconnecting',WARN);
80
-            }
81
-        }
82
-        try {
83
-            $this->idoDB = new PDO($this->idoDSN,$this->idoUsername,$this->idoPass);
84
-        } catch (PDOException $e) {
85
-            $this->logging->log('Connection failed to IDO : ' . $e->getMessage(),ERROR,'');
86
-        }
87
-        return $this->idoDB;
88
-    }
66
+	/**
67
+	 * Connect to IDO database
68
+	 * @return \PDO
69
+	 */
70
+	public function db_connect_ido()
71
+	{
72
+		if ($this->idoDB != null) {
73
+			// Check if connection is still alive
74
+			try {
75
+				$this->idoDB->query('select 1')->fetchColumn();
76
+				return $this->idoDB;
77
+			} catch (Exception $e) {
78
+				// select 1 failed, try to reconnect.
79
+				$this->logging->log('Database IDO connection lost, reconnecting',WARN);
80
+			}
81
+		}
82
+		try {
83
+			$this->idoDB = new PDO($this->idoDSN,$this->idoUsername,$this->idoPass);
84
+		} catch (PDOException $e) {
85
+			$this->logging->log('Connection failed to IDO : ' . $e->getMessage(),ERROR,'');
86
+		}
87
+		return $this->idoDB;
88
+	}
89 89
     
90
-    /**
91
-     * Connect to Trap database
92
-     * @return \PDO
93
-     */
94
-    public function db_connect_trap()
95
-    {
90
+	/**
91
+	 * Connect to Trap database
92
+	 * @return \PDO
93
+	 */
94
+	public function db_connect_trap()
95
+	{
96 96
         
97
-        if ($this->trapDB != null) {
98
-            // Check if connection is still alive
99
-            try {
100
-                $this->trapDB->query('select 1')->fetchColumn();
101
-                return $this->trapDB;
102
-            } catch (Exception $e) {
103
-                // select 1 failed, try to reconnect.
104
-                $this->logging->log('Database connection lost, reconnecting',WARN);
105
-            }           
106
-        }       
107
-        try {
108
-            $this->trapDB = new PDO($this->trapDSN,$this->trapUsername,$this->trapPass);
109
-        } catch (PDOException $e) {
110
-            $this->logging->log('Connection failed : ' . $e->getMessage(),ERROR,'');
111
-        }
112
-        return $this->trapDB;
113
-    }
97
+		if ($this->trapDB != null) {
98
+			// Check if connection is still alive
99
+			try {
100
+				$this->trapDB->query('select 1')->fetchColumn();
101
+				return $this->trapDB;
102
+			} catch (Exception $e) {
103
+				// select 1 failed, try to reconnect.
104
+				$this->logging->log('Database connection lost, reconnecting',WARN);
105
+			}           
106
+		}       
107
+		try {
108
+			$this->trapDB = new PDO($this->trapDSN,$this->trapUsername,$this->trapPass);
109
+		} catch (PDOException $e) {
110
+			$this->logging->log('Connection failed : ' . $e->getMessage(),ERROR,'');
111
+		}
112
+		return $this->trapDB;
113
+	}
114 114
     
115
-    /**
116
-     * Setup dsn and check parameters
117
-     * @param array $configElmt
118
-     * @return string
119
-     */
120
-    protected function setupDSN($configElmt)  
121
-    {
122
-        if (!array_key_exists('db',$configElmt) ||
123
-            !array_key_exists('host',$configElmt) ||
124
-            !array_key_exists('dbname',$configElmt) ||
125
-            !array_key_exists('username',$configElmt))
126
-        {
127
-            $this->logging->log('Missing DB params',ERROR);
128
-            return ''; 
129
-        }
115
+	/**
116
+	 * Setup dsn and check parameters
117
+	 * @param array $configElmt
118
+	 * @return string
119
+	 */
120
+	protected function setupDSN($configElmt)  
121
+	{
122
+		if (!array_key_exists('db',$configElmt) ||
123
+			!array_key_exists('host',$configElmt) ||
124
+			!array_key_exists('dbname',$configElmt) ||
125
+			!array_key_exists('username',$configElmt))
126
+		{
127
+			$this->logging->log('Missing DB params',ERROR);
128
+			return ''; 
129
+		}
130 130
         
131
-        //	$dsn = 'mysql:dbname=traps;host=127.0.0.1';
132
-        $dsn= $configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
131
+		//	$dsn = 'mysql:dbname=traps;host=127.0.0.1';
132
+		$dsn= $configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
133 133
         
134
-        if (array_key_exists('port', $configElmt))
135
-        {
136
-            $dsn .= ';port='.$configElmt['port'];
137
-        }
138
-        return $dsn;
139
-    }
134
+		if (array_key_exists('port', $configElmt))
135
+		{
136
+			$dsn .= ';port='.$configElmt['port'];
137
+		}
138
+		return $dsn;
139
+	}
140 140
 
141 141
     
142
-    /** Create database schema
143
-     *	@param $schema_file	string File to read schema from
144
-     *	@param $table_prefix string to replace #PREFIX# in schema file by this
145
-     */
146
-    public function create_schema($schema_file,$table_prefix)
147
-    {
148
-        //Read data from snmptrapd from stdin
149
-        $input_stream=fopen($schema_file, 'r');
142
+	/** Create database schema
143
+	 *	@param $schema_file	string File to read schema from
144
+	 *	@param $table_prefix string to replace #PREFIX# in schema file by this
145
+	 */
146
+	public function create_schema($schema_file,$table_prefix)
147
+	{
148
+		//Read data from snmptrapd from stdin
149
+		$input_stream=fopen($schema_file, 'r');
150 150
         
151
-        if ($input_stream=== false)
152
-        {
153
-            $this->logging->log("Error reading schema !",ERROR,'');
154
-            return;
155
-        }
156
-        $newline='';
157
-        $cur_table='';
158
-        $cur_table_array=array();
159
-        $db_conn=$this->db_connect_trap();
151
+		if ($input_stream=== false)
152
+		{
153
+			$this->logging->log("Error reading schema !",ERROR,'');
154
+			return;
155
+		}
156
+		$newline='';
157
+		$cur_table='';
158
+		$cur_table_array=array();
159
+		$db_conn=$this->db_connect_trap();
160 160
         
161
-        while (($line=fgets($input_stream)) !== false)
162
-        {
163
-            $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
164
-            if (preg_match('/; *$/', $newline))
165
-            {
166
-                $sql= $newline;
167
-                if ($db_conn->query($sql) === false) {
168
-                    $this->logging->log('Error create schema : '.$sql,ERROR,'');
169
-                    return;
170
-                }
171
-                if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
172
-                {
173
-                    $cur_table='table '.$cur_table_array[1];
174
-                }
175
-                else
176
-                {
177
-                    $cur_table='secret SQL stuff :-)';
178
-                }
179
-                $this->logging->log('Creating : ' . $cur_table,INFO );
180
-                $newline='';
181
-            }
182
-        }
161
+		while (($line=fgets($input_stream)) !== false)
162
+		{
163
+			$newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
164
+			if (preg_match('/; *$/', $newline))
165
+			{
166
+				$sql= $newline;
167
+				if ($db_conn->query($sql) === false) {
168
+					$this->logging->log('Error create schema : '.$sql,ERROR,'');
169
+					return;
170
+				}
171
+				if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
172
+				{
173
+					$cur_table='table '.$cur_table_array[1];
174
+				}
175
+				else
176
+				{
177
+					$cur_table='secret SQL stuff :-)';
178
+				}
179
+				$this->logging->log('Creating : ' . $cur_table,INFO );
180
+				$newline='';
181
+			}
182
+		}
183 183
         
184
-        $sql= $newline;
185
-        if ($sql != '' )
186
-        {
187
-            if ($db_conn->query($sql) === false) {
188
-                $this->logging->log('Error create schema : '.$sql,ERROR,'');
189
-                return;
190
-            }
191
-        }
192
-        $this->logging->log('Schema created',INFO);
193
-    }
184
+		$sql= $newline;
185
+		if ($sql != '' )
186
+		{
187
+			if ($db_conn->query($sql) === false) {
188
+				$this->logging->log('Error create schema : '.$sql,ERROR,'');
189
+				return;
190
+			}
191
+		}
192
+		$this->logging->log('Schema created',INFO);
193
+	}
194 194
     
195
-    /**
196
-     * Update database schema from current (as set in db) to $target_version
197
-     *     @param $prefix string file prefix of sql update File
198
-     *     @param $target_version int target db version number
199
-     *     @param $table_prefix string to replace #PREFIX# in schema file by this
200
-     *     @param bool $getmsg : only get messages from version upgrades
201
-     *     @return string : if $getmsg=true, return messages or 'ERROR' on error.
202
-     */
203
-    public function update_schema($prefix,$target_version,$table_prefix,$getmsg=false)
204
-    {
205
-        // Get current db number
206
-        $db_conn=$this->db_connect_trap();
207
-        $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE name=\'db_version\' ';
208
-        $this->logging->log('SQL query : '.$sql,DEBUG );
209
-        if (($ret_code=$db_conn->query($sql)) === false) {
210
-            $this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
211
-            return 'ERROR';
212
-        }
213
-        $version=$ret_code->fetchAll();
214
-        $cur_version=$version[0]['value'];
195
+	/**
196
+	 * Update database schema from current (as set in db) to $target_version
197
+	 *     @param $prefix string file prefix of sql update File
198
+	 *     @param $target_version int target db version number
199
+	 *     @param $table_prefix string to replace #PREFIX# in schema file by this
200
+	 *     @param bool $getmsg : only get messages from version upgrades
201
+	 *     @return string : if $getmsg=true, return messages or 'ERROR' on error.
202
+	 */
203
+	public function update_schema($prefix,$target_version,$table_prefix,$getmsg=false)
204
+	{
205
+		// Get current db number
206
+		$db_conn=$this->db_connect_trap();
207
+		$sql='SELECT value from '.$this->dbPrefix.'db_config WHERE name=\'db_version\' ';
208
+		$this->logging->log('SQL query : '.$sql,DEBUG );
209
+		if (($ret_code=$db_conn->query($sql)) === false) {
210
+			$this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
211
+			return 'ERROR';
212
+		}
213
+		$version=$ret_code->fetchAll();
214
+		$cur_version=$version[0]['value'];
215 215
         
216
-        if ($this->trapDBType == 'pgsql')
217
-        {
218
-            $prefix .= 'update_pgsql/schema_';
219
-        }
220
-        else
221
-        {
222
-            $prefix .= 'update_sql/schema_';
223
-        }
224
-        //echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
225
-        if ($getmsg === true)
226
-        {
227
-            return $this->update_schema_message($prefix, $cur_version, $target_version);
228
-        }
216
+		if ($this->trapDBType == 'pgsql')
217
+		{
218
+			$prefix .= 'update_pgsql/schema_';
219
+		}
220
+		else
221
+		{
222
+			$prefix .= 'update_sql/schema_';
223
+		}
224
+		//echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
225
+		if ($getmsg === true)
226
+		{
227
+			return $this->update_schema_message($prefix, $cur_version, $target_version);
228
+		}
229 229
         
230
-        if ($this->update_schema_do($prefix, $cur_version, $target_version, $table_prefix) === true)
231
-        {
232
-            return 'ERROR';
233
-        }
234
-        return '';
230
+		if ($this->update_schema_do($prefix, $cur_version, $target_version, $table_prefix) === true)
231
+		{
232
+			return 'ERROR';
233
+		}
234
+		return '';
235 235
 
236
-    }
236
+	}
237 237
 
238
-    /**
239
-     * Update database schema from current (as set in db) to $target_version
240
-     *     @param string $prefix  file prefix of sql update File
241
-     *     @param int $cur_version  current db version number
242
-     *     @param int $target_version  target db version number
243
-     *     @param string $table_prefix   to replace #PREFIX# in schema file by this
244
-     *     @return bool : true on error
245
-     */
246
-    public function update_schema_do($prefix,$cur_version,$target_version,$table_prefix)
247
-    {
248
-        while($cur_version<$target_version)
249
-        { // TODO : execute pre & post scripts
250
-            $cur_version++;
251
-            $this->logging->log('Updating to version : ' .$cur_version ,INFO );
252
-            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
253
-            $input_stream=fopen($updateFile, 'r');
254
-            if ($input_stream=== false)
255
-            {
256
-                $this->logging->log("Error reading update file ". $updateFile,ERROR);
257
-                return true;
258
-            }
259
-            $newline='';
260
-            $db_conn=$this->db_connect_trap();
261
-            $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
262
-            while (($line=fgets($input_stream)) !== false)
263
-            {
264
-                if (preg_match('/^#/', $line)) continue; // ignore comment lines
265
-                $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
266
-                if (preg_match('/; *$/', $newline))
267
-                {
268
-                    $sql_req=$db_conn->prepare($newline);
269
-                    if ($sql_req->execute() === false) {
270
-                        $this->logging->log('Error create schema : '.$newline,ERROR);
271
-                        return true;
272
-                    }
273
-                    $cur_table_array=array();
274
-                    if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
275
-                    {
276
-                        $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
277
-                    }
278
-                    else
279
-                    {
280
-                        $cur_table='secret SQL stuff :-)';
281
-                        //$cur_table=$newline;
282
-                    }
283
-                    $this->logging->log('Doing : ' . $cur_table,INFO );
238
+	/**
239
+	 * Update database schema from current (as set in db) to $target_version
240
+	 *     @param string $prefix  file prefix of sql update File
241
+	 *     @param int $cur_version  current db version number
242
+	 *     @param int $target_version  target db version number
243
+	 *     @param string $table_prefix   to replace #PREFIX# in schema file by this
244
+	 *     @return bool : true on error
245
+	 */
246
+	public function update_schema_do($prefix,$cur_version,$target_version,$table_prefix)
247
+	{
248
+		while($cur_version<$target_version)
249
+		{ // TODO : execute pre & post scripts
250
+			$cur_version++;
251
+			$this->logging->log('Updating to version : ' .$cur_version ,INFO );
252
+			$updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
253
+			$input_stream=fopen($updateFile, 'r');
254
+			if ($input_stream=== false)
255
+			{
256
+				$this->logging->log("Error reading update file ". $updateFile,ERROR);
257
+				return true;
258
+			}
259
+			$newline='';
260
+			$db_conn=$this->db_connect_trap();
261
+			$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
262
+			while (($line=fgets($input_stream)) !== false)
263
+			{
264
+				if (preg_match('/^#/', $line)) continue; // ignore comment lines
265
+				$newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
266
+				if (preg_match('/; *$/', $newline))
267
+				{
268
+					$sql_req=$db_conn->prepare($newline);
269
+					if ($sql_req->execute() === false) {
270
+						$this->logging->log('Error create schema : '.$newline,ERROR);
271
+						return true;
272
+					}
273
+					$cur_table_array=array();
274
+					if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
275
+					{
276
+						$cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
277
+					}
278
+					else
279
+					{
280
+						$cur_table='secret SQL stuff :-)';
281
+						//$cur_table=$newline;
282
+					}
283
+					$this->logging->log('Doing : ' . $cur_table,INFO );
284 284
                     
285
-                    $newline='';
286
-                }
287
-            }
288
-            fclose($input_stream);
285
+					$newline='';
286
+				}
287
+			}
288
+			fclose($input_stream);
289 289
             
290
-            $sql='UPDATE '.$this->dbPrefix.'db_config SET value='.$cur_version.' WHERE ( name=\'db_version\' )';
291
-            $this->logging->log('SQL query : '.$sql,DEBUG );
292
-            if ($db_conn->query($sql) === false) {
293
-                $this->logging->log('Cannot update db version. Query : ' . $sql,WARN);
294
-                return true;
295
-            }
290
+			$sql='UPDATE '.$this->dbPrefix.'db_config SET value='.$cur_version.' WHERE ( name=\'db_version\' )';
291
+			$this->logging->log('SQL query : '.$sql,DEBUG );
292
+			if ($db_conn->query($sql) === false) {
293
+				$this->logging->log('Cannot update db version. Query : ' . $sql,WARN);
294
+				return true;
295
+			}
296 296
             
297
-            $this->logging->log('Schema updated to version : '.$cur_version ,INFO);
298
-        }
299
-        return false;
300
-    }
297
+			$this->logging->log('Schema updated to version : '.$cur_version ,INFO);
298
+		}
299
+		return false;
300
+	}
301 301
     
302
-    /**
303
-     * Get database message for update to $target_version
304
-     *     @param string $prefix  file prefix of sql update File
305
-     *     @param int $cur_version  current db version number
306
-     *     @param int $target_version  target db version number
307
-     *     @return string : return messages or 'ERROR'.
308
-     */
309
-    private function update_schema_message($prefix,$cur_version,$target_version)
310
-    {
302
+	/**
303
+	 * Get database message for update to $target_version
304
+	 *     @param string $prefix  file prefix of sql update File
305
+	 *     @param int $cur_version  current db version number
306
+	 *     @param int $target_version  target db version number
307
+	 *     @return string : return messages or 'ERROR'.
308
+	 */
309
+	private function update_schema_message($prefix,$cur_version,$target_version)
310
+	{
311 311
  
312
-        $message='';
313
-        $this->logging->log('getting message for upgrade',DEBUG );
314
-        while($cur_version<$target_version)
315
-        {
316
-            $cur_version++;
317
-            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
318
-            $input_stream=fopen($updateFile, 'r');
319
-            if ($input_stream=== false)
320
-            {
321
-                $this->logging->log("Error reading update file ". $updateFile,2,'');
322
-                return 'ERROR';
323
-            }
324
-            do 
325
-            { 
326
-                $line=fgets($input_stream); 
327
-            }
328
-            while ($line !== false && !preg_match('/#MESSAGE/',$line));
329
-            fclose($input_stream);
330
-            if ($line === false)
331
-            {
332
-                $this->logging->log("No message in file ". $updateFile,2,'');
333
-                return '';
334
-            }
335
-            $message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
336
-        }
337
-        return $message;
338
-    }
312
+		$message='';
313
+		$this->logging->log('getting message for upgrade',DEBUG );
314
+		while($cur_version<$target_version)
315
+		{
316
+			$cur_version++;
317
+			$updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
318
+			$input_stream=fopen($updateFile, 'r');
319
+			if ($input_stream=== false)
320
+			{
321
+				$this->logging->log("Error reading update file ". $updateFile,2,'');
322
+				return 'ERROR';
323
+			}
324
+			do 
325
+			{ 
326
+				$line=fgets($input_stream); 
327
+			}
328
+			while ($line !== false && !preg_match('/#MESSAGE/',$line));
329
+			fclose($input_stream);
330
+			if ($line === false)
331
+			{
332
+				$this->logging->log("No message in file ". $updateFile,2,'');
333
+				return '';
334
+			}
335
+			$message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
336
+		}
337
+		return $message;
338
+	}
339 339
     
340 340
 }
341 341
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -35,16 +35,16 @@  discard block
 block discarded – undo
35 35
      * @param Logging $logClass : where to log
36 36
      * @param array $dbParam : array of named params  type,host,dbname,username,[port],[password]
37 37
      */
38
-    function __construct($logClass,$dbParam,$dbPrefix)
38
+    function __construct($logClass, $dbParam, $dbPrefix)
39 39
     {
40 40
         $this->logging=$logClass;
41 41
         $this->dbPrefix=$dbPrefix;
42 42
         
43 43
         $this->trapDSN=$this->setupDSN($dbParam);
44
-        $this->trapUsername = $dbParam['username'];
45
-        $this->trapPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
44
+        $this->trapUsername=$dbParam['username'];
45
+        $this->trapPass=(array_key_exists('password', $dbParam)) ? $dbParam['password'] : '';
46 46
         $this->trapDBType=$dbParam['db'];
47
-        $this->logging->log('DSN : '.$this->trapDSN. ';user '.$this->trapUsername.' / prefix : '. $this->dbPrefix,INFO);
47
+        $this->logging->log('DSN : '.$this->trapDSN.';user '.$this->trapUsername.' / prefix : '.$this->dbPrefix, INFO);
48 48
         $this->db_connect_trap();
49 49
         
50 50
     }
@@ -56,9 +56,9 @@  discard block
 block discarded – undo
56 56
     public function setupIDO($dbParam)
57 57
     {
58 58
         $this->idoDSN=$this->setupDSN($dbParam);
59
-        $this->idoUsername = $dbParam['username'];
60
-        $this->idoPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
61
-        $this->logging->log('DSN : '.$this->idoDSN. ';user '.$this->idoUsername,INFO);
59
+        $this->idoUsername=$dbParam['username'];
60
+        $this->idoPass=(array_key_exists('password', $dbParam)) ? $dbParam['password'] : '';
61
+        $this->logging->log('DSN : '.$this->idoDSN.';user '.$this->idoUsername, INFO);
62 62
         $this->idoDBType=$dbParam['db'];
63 63
         $this->db_connect_ido();
64 64
     }
@@ -76,13 +76,13 @@  discard block
 block discarded – undo
76 76
                 return $this->idoDB;
77 77
             } catch (Exception $e) {
78 78
                 // select 1 failed, try to reconnect.
79
-                $this->logging->log('Database IDO connection lost, reconnecting',WARN);
79
+                $this->logging->log('Database IDO connection lost, reconnecting', WARN);
80 80
             }
81 81
         }
82 82
         try {
83
-            $this->idoDB = new PDO($this->idoDSN,$this->idoUsername,$this->idoPass);
83
+            $this->idoDB=new PDO($this->idoDSN, $this->idoUsername, $this->idoPass);
84 84
         } catch (PDOException $e) {
85
-            $this->logging->log('Connection failed to IDO : ' . $e->getMessage(),ERROR,'');
85
+            $this->logging->log('Connection failed to IDO : '.$e->getMessage(), ERROR, '');
86 86
         }
87 87
         return $this->idoDB;
88 88
     }
@@ -101,13 +101,13 @@  discard block
 block discarded – undo
101 101
                 return $this->trapDB;
102 102
             } catch (Exception $e) {
103 103
                 // select 1 failed, try to reconnect.
104
-                $this->logging->log('Database connection lost, reconnecting',WARN);
104
+                $this->logging->log('Database connection lost, reconnecting', WARN);
105 105
             }           
106 106
         }       
107 107
         try {
108
-            $this->trapDB = new PDO($this->trapDSN,$this->trapUsername,$this->trapPass);
108
+            $this->trapDB=new PDO($this->trapDSN, $this->trapUsername, $this->trapPass);
109 109
         } catch (PDOException $e) {
110
-            $this->logging->log('Connection failed : ' . $e->getMessage(),ERROR,'');
110
+            $this->logging->log('Connection failed : '.$e->getMessage(), ERROR, '');
111 111
         }
112 112
         return $this->trapDB;
113 113
     }
@@ -119,21 +119,21 @@  discard block
 block discarded – undo
119 119
      */
120 120
     protected function setupDSN($configElmt)  
121 121
     {
122
-        if (!array_key_exists('db',$configElmt) ||
123
-            !array_key_exists('host',$configElmt) ||
124
-            !array_key_exists('dbname',$configElmt) ||
125
-            !array_key_exists('username',$configElmt))
122
+        if (!array_key_exists('db', $configElmt) ||
123
+            !array_key_exists('host', $configElmt) ||
124
+            !array_key_exists('dbname', $configElmt) ||
125
+            !array_key_exists('username', $configElmt))
126 126
         {
127
-            $this->logging->log('Missing DB params',ERROR);
127
+            $this->logging->log('Missing DB params', ERROR);
128 128
             return ''; 
129 129
         }
130 130
         
131 131
         //	$dsn = 'mysql:dbname=traps;host=127.0.0.1';
132
-        $dsn= $configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
132
+        $dsn=$configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
133 133
         
134 134
         if (array_key_exists('port', $configElmt))
135 135
         {
136
-            $dsn .= ';port='.$configElmt['port'];
136
+            $dsn.=';port='.$configElmt['port'];
137 137
         }
138 138
         return $dsn;
139 139
     }
@@ -143,14 +143,14 @@  discard block
 block discarded – undo
143 143
      *	@param $schema_file	string File to read schema from
144 144
      *	@param $table_prefix string to replace #PREFIX# in schema file by this
145 145
      */
146
-    public function create_schema($schema_file,$table_prefix)
146
+    public function create_schema($schema_file, $table_prefix)
147 147
     {
148 148
         //Read data from snmptrapd from stdin
149 149
         $input_stream=fopen($schema_file, 'r');
150 150
         
151
-        if ($input_stream=== false)
151
+        if ($input_stream === false)
152 152
         {
153
-            $this->logging->log("Error reading schema !",ERROR,'');
153
+            $this->logging->log("Error reading schema !", ERROR, '');
154 154
             return;
155 155
         }
156 156
         $newline='';
@@ -160,15 +160,15 @@  discard block
 block discarded – undo
160 160
         
161 161
         while (($line=fgets($input_stream)) !== false)
162 162
         {
163
-            $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
163
+            $newline.=chop(preg_replace('/#PREFIX#/', $table_prefix, $line));
164 164
             if (preg_match('/; *$/', $newline))
165 165
             {
166
-                $sql= $newline;
166
+                $sql=$newline;
167 167
                 if ($db_conn->query($sql) === false) {
168
-                    $this->logging->log('Error create schema : '.$sql,ERROR,'');
168
+                    $this->logging->log('Error create schema : '.$sql, ERROR, '');
169 169
                     return;
170 170
                 }
171
-                if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
171
+                if (preg_match('/^ *CREATE TABLE ([^ ]+)/', $newline, $cur_table_array))
172 172
                 {
173 173
                     $cur_table='table '.$cur_table_array[1];
174 174
                 }
@@ -176,20 +176,20 @@  discard block
 block discarded – undo
176 176
                 {
177 177
                     $cur_table='secret SQL stuff :-)';
178 178
                 }
179
-                $this->logging->log('Creating : ' . $cur_table,INFO );
179
+                $this->logging->log('Creating : '.$cur_table, INFO);
180 180
                 $newline='';
181 181
             }
182 182
         }
183 183
         
184
-        $sql= $newline;
185
-        if ($sql != '' )
184
+        $sql=$newline;
185
+        if ($sql != '')
186 186
         {
187 187
             if ($db_conn->query($sql) === false) {
188
-                $this->logging->log('Error create schema : '.$sql,ERROR,'');
188
+                $this->logging->log('Error create schema : '.$sql, ERROR, '');
189 189
                 return;
190 190
             }
191 191
         }
192
-        $this->logging->log('Schema created',INFO);
192
+        $this->logging->log('Schema created', INFO);
193 193
     }
194 194
     
195 195
     /**
@@ -200,14 +200,14 @@  discard block
 block discarded – undo
200 200
      *     @param bool $getmsg : only get messages from version upgrades
201 201
      *     @return string : if $getmsg=true, return messages or 'ERROR' on error.
202 202
      */
203
-    public function update_schema($prefix,$target_version,$table_prefix,$getmsg=false)
203
+    public function update_schema($prefix, $target_version, $table_prefix, $getmsg=false)
204 204
     {
205 205
         // Get current db number
206 206
         $db_conn=$this->db_connect_trap();
207 207
         $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE name=\'db_version\' ';
208
-        $this->logging->log('SQL query : '.$sql,DEBUG );
208
+        $this->logging->log('SQL query : '.$sql, DEBUG);
209 209
         if (($ret_code=$db_conn->query($sql)) === false) {
210
-            $this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
210
+            $this->logging->log('Cannot get db version. Query : '.$sql, 2, '');
211 211
             return 'ERROR';
212 212
         }
213 213
         $version=$ret_code->fetchAll();
@@ -215,11 +215,11 @@  discard block
 block discarded – undo
215 215
         
216 216
         if ($this->trapDBType == 'pgsql')
217 217
         {
218
-            $prefix .= 'update_pgsql/schema_';
218
+            $prefix.='update_pgsql/schema_';
219 219
         }
220 220
         else
221 221
         {
222
-            $prefix .= 'update_sql/schema_';
222
+            $prefix.='update_sql/schema_';
223 223
         }
224 224
         //echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
225 225
         if ($getmsg === true)
@@ -243,17 +243,17 @@  discard block
 block discarded – undo
243 243
      *     @param string $table_prefix   to replace #PREFIX# in schema file by this
244 244
      *     @return bool : true on error
245 245
      */
246
-    public function update_schema_do($prefix,$cur_version,$target_version,$table_prefix)
246
+    public function update_schema_do($prefix, $cur_version, $target_version, $table_prefix)
247 247
     {
248
-        while($cur_version<$target_version)
248
+        while ($cur_version < $target_version)
249 249
         { // TODO : execute pre & post scripts
250 250
             $cur_version++;
251
-            $this->logging->log('Updating to version : ' .$cur_version ,INFO );
252
-            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
251
+            $this->logging->log('Updating to version : '.$cur_version, INFO);
252
+            $updateFile=$prefix.'v'.($cur_version - 1).'_v'.$cur_version.'.sql';
253 253
             $input_stream=fopen($updateFile, 'r');
254
-            if ($input_stream=== false)
254
+            if ($input_stream === false)
255 255
             {
256
-                $this->logging->log("Error reading update file ". $updateFile,ERROR);
256
+                $this->logging->log("Error reading update file ".$updateFile, ERROR);
257 257
                 return true;
258 258
             }
259 259
             $newline='';
@@ -262,25 +262,25 @@  discard block
 block discarded – undo
262 262
             while (($line=fgets($input_stream)) !== false)
263 263
             {
264 264
                 if (preg_match('/^#/', $line)) continue; // ignore comment lines
265
-                $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
265
+                $newline.=chop(preg_replace('/#PREFIX#/', $table_prefix, $line));
266 266
                 if (preg_match('/; *$/', $newline))
267 267
                 {
268 268
                     $sql_req=$db_conn->prepare($newline);
269 269
                     if ($sql_req->execute() === false) {
270
-                        $this->logging->log('Error create schema : '.$newline,ERROR);
270
+                        $this->logging->log('Error create schema : '.$newline, ERROR);
271 271
                         return true;
272 272
                     }
273 273
                     $cur_table_array=array();
274
-                    if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
274
+                    if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/', $newline, $cur_table_array))
275 275
                     {
276
-                        $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
276
+                        $cur_table=$cur_table_array[1].' SQL table '.$cur_table_array[2];
277 277
                     }
278 278
                     else
279 279
                     {
280 280
                         $cur_table='secret SQL stuff :-)';
281 281
                         //$cur_table=$newline;
282 282
                     }
283
-                    $this->logging->log('Doing : ' . $cur_table,INFO );
283
+                    $this->logging->log('Doing : '.$cur_table, INFO);
284 284
                     
285 285
                     $newline='';
286 286
                 }
@@ -288,13 +288,13 @@  discard block
 block discarded – undo
288 288
             fclose($input_stream);
289 289
             
290 290
             $sql='UPDATE '.$this->dbPrefix.'db_config SET value='.$cur_version.' WHERE ( name=\'db_version\' )';
291
-            $this->logging->log('SQL query : '.$sql,DEBUG );
291
+            $this->logging->log('SQL query : '.$sql, DEBUG);
292 292
             if ($db_conn->query($sql) === false) {
293
-                $this->logging->log('Cannot update db version. Query : ' . $sql,WARN);
293
+                $this->logging->log('Cannot update db version. Query : '.$sql, WARN);
294 294
                 return true;
295 295
             }
296 296
             
297
-            $this->logging->log('Schema updated to version : '.$cur_version ,INFO);
297
+            $this->logging->log('Schema updated to version : '.$cur_version, INFO);
298 298
         }
299 299
         return false;
300 300
     }
@@ -306,33 +306,33 @@  discard block
 block discarded – undo
306 306
      *     @param int $target_version  target db version number
307 307
      *     @return string : return messages or 'ERROR'.
308 308
      */
309
-    private function update_schema_message($prefix,$cur_version,$target_version)
309
+    private function update_schema_message($prefix, $cur_version, $target_version)
310 310
     {
311 311
  
312 312
         $message='';
313
-        $this->logging->log('getting message for upgrade',DEBUG );
314
-        while($cur_version<$target_version)
313
+        $this->logging->log('getting message for upgrade', DEBUG);
314
+        while ($cur_version < $target_version)
315 315
         {
316 316
             $cur_version++;
317
-            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
317
+            $updateFile=$prefix.'v'.($cur_version - 1).'_v'.$cur_version.'.sql';
318 318
             $input_stream=fopen($updateFile, 'r');
319
-            if ($input_stream=== false)
319
+            if ($input_stream === false)
320 320
             {
321
-                $this->logging->log("Error reading update file ". $updateFile,2,'');
321
+                $this->logging->log("Error reading update file ".$updateFile, 2, '');
322 322
                 return 'ERROR';
323 323
             }
324 324
             do 
325 325
             { 
326 326
                 $line=fgets($input_stream); 
327 327
             }
328
-            while ($line !== false && !preg_match('/#MESSAGE/',$line));
328
+            while ($line !== false && !preg_match('/#MESSAGE/', $line));
329 329
             fclose($input_stream);
330 330
             if ($line === false)
331 331
             {
332
-                $this->logging->log("No message in file ". $updateFile,2,'');
332
+                $this->logging->log("No message in file ".$updateFile, 2, '');
333 333
                 return '';
334 334
             }
335
-            $message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
335
+            $message.=($cur_version - 1).'->'.$cur_version.' : '.preg_replace('/#MESSAGE : /', '', $line)."\n";
336 336
         }
337 337
         return $message;
338 338
     }
Please login to merge, or discard this patch.
tests/db_test.php 2 patches
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -14,40 +14,40 @@
 block discarded – undo
14 14
 
15 15
 if (!array_key_exists('v',$options) || !array_key_exists('c',$options) || !array_key_exists('b',$options)|| !array_key_exists('a',$options))
16 16
 {
17
-    printf("Need version -v, path -a, database -b (mysql,pgsql) command -c (create/update)\n");
18
-    exit(1);
17
+	printf("Need version -v, path -a, database -b (mysql,pgsql) command -c (create/update)\n");
18
+	exit(1);
19 19
 }
20 20
 $command=$options['c'];
21 21
 $path=$options['a'];
22 22
 try {
23
-    switch($command)
24
-    {
25
-        case 'create':
26
-            $schema=($options['b']=='mysql')?'schema_v'.$options['v'].'.sql':'schema_v'.$options['v'].'.pgsql';
27
-            $schema=$path.'/SQL/'.$schema;
28
-            $trap->trapsDB->create_schema($schema, 'traps_');
29
-            break;
30
-        case 'update':
31
-            $message=$trap->trapsDB->update_schema($path."/SQL/",$options['v'], 'traps_',true);
32
-            printf("Update message : %s\n",$message);
33
-            if ($message == 'ERROR')
34
-            {
35
-                exit(1);
36
-            }
37
-            printf("Messages DONE, updating : \n");
38
-            $message=$trap->trapsDB->update_schema($path."/SQL/",$options['v'], 'traps_');
39
-            if ($message == 'ERROR')
40
-            {
41
-                exit(1);
42
-            }
43
-            break;
44
-        default:
45
-            printf("Unknown command\n");
46
-            exit(1);
47
-    }
23
+	switch($command)
24
+	{
25
+		case 'create':
26
+			$schema=($options['b']=='mysql')?'schema_v'.$options['v'].'.sql':'schema_v'.$options['v'].'.pgsql';
27
+			$schema=$path.'/SQL/'.$schema;
28
+			$trap->trapsDB->create_schema($schema, 'traps_');
29
+			break;
30
+		case 'update':
31
+			$message=$trap->trapsDB->update_schema($path."/SQL/",$options['v'], 'traps_',true);
32
+			printf("Update message : %s\n",$message);
33
+			if ($message == 'ERROR')
34
+			{
35
+				exit(1);
36
+			}
37
+			printf("Messages DONE, updating : \n");
38
+			$message=$trap->trapsDB->update_schema($path."/SQL/",$options['v'], 'traps_');
39
+			if ($message == 'ERROR')
40
+			{
41
+				exit(1);
42
+			}
43
+			break;
44
+		default:
45
+			printf("Unknown command\n");
46
+			exit(1);
47
+	}
48 48
 } catch (Exception $e) {
49
-    printf("Caught Exception %s\n",$e->getMessage());
50
-    exit (1);
49
+	printf("Caught Exception %s\n",$e->getMessage());
50
+	exit (1);
51 51
 }
52 52
 
53 53
 exit(0);
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -3,16 +3,16 @@  discard block
 block discarded – undo
3 3
 
4 4
 require_once 'bin/trap_class.php';
5 5
 
6
-$options = getopt("c:v:d:b:a:");
6
+$options=getopt("c:v:d:b:a:");
7 7
 
8
-$icingaweb2Etc=(array_key_exists('d',$options))?$options['d']:"/etc/icingaweb2";
8
+$icingaweb2Etc=(array_key_exists('d', $options)) ? $options['d'] : "/etc/icingaweb2";
9 9
 
10
-$debugLevel=4;// 0=No output 1=critical 2=warning 3=trace 4=ALL
10
+$debugLevel=4; // 0=No output 1=critical 2=warning 3=trace 4=ALL
11 11
 
12
-$trap = new trap($icingaweb2Etc,$debugLevel,'display');
13
-$trap->setLogging($debugLevel,'display');
12
+$trap=new trap($icingaweb2Etc, $debugLevel, 'display');
13
+$trap->setLogging($debugLevel, 'display');
14 14
 
15
-if (!array_key_exists('v',$options) || !array_key_exists('c',$options) || !array_key_exists('b',$options)|| !array_key_exists('a',$options))
15
+if (!array_key_exists('v', $options) || !array_key_exists('c', $options) || !array_key_exists('b', $options) || !array_key_exists('a', $options))
16 16
 {
17 17
     printf("Need version -v, path -a, database -b (mysql,pgsql) command -c (create/update)\n");
18 18
     exit(1);
@@ -20,22 +20,22 @@  discard block
 block discarded – undo
20 20
 $command=$options['c'];
21 21
 $path=$options['a'];
22 22
 try {
23
-    switch($command)
23
+    switch ($command)
24 24
     {
25 25
         case 'create':
26
-            $schema=($options['b']=='mysql')?'schema_v'.$options['v'].'.sql':'schema_v'.$options['v'].'.pgsql';
26
+            $schema=($options['b'] == 'mysql') ? 'schema_v'.$options['v'].'.sql' : 'schema_v'.$options['v'].'.pgsql';
27 27
             $schema=$path.'/SQL/'.$schema;
28 28
             $trap->trapsDB->create_schema($schema, 'traps_');
29 29
             break;
30 30
         case 'update':
31
-            $message=$trap->trapsDB->update_schema($path."/SQL/",$options['v'], 'traps_',true);
32
-            printf("Update message : %s\n",$message);
31
+            $message=$trap->trapsDB->update_schema($path."/SQL/", $options['v'], 'traps_', true);
32
+            printf("Update message : %s\n", $message);
33 33
             if ($message == 'ERROR')
34 34
             {
35 35
                 exit(1);
36 36
             }
37 37
             printf("Messages DONE, updating : \n");
38
-            $message=$trap->trapsDB->update_schema($path."/SQL/",$options['v'], 'traps_');
38
+            $message=$trap->trapsDB->update_schema($path."/SQL/", $options['v'], 'traps_');
39 39
             if ($message == 'ERROR')
40 40
             {
41 41
                 exit(1);
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
             exit(1);
47 47
     }
48 48
 } catch (Exception $e) {
49
-    printf("Caught Exception %s\n",$e->getMessage());
49
+    printf("Caught Exception %s\n", $e->getMessage());
50 50
     exit (1);
51 51
 }
52 52
 
Please login to merge, or discard this patch.
application/clicommands/MibCommand.php 3 patches
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -22,77 +22,77 @@  discard block
 block discarded – undo
22 22
 class MibCommand extends Command
23 23
 {
24 24
 	/**
25
-	*	Update mib database
26
-	*
27
-	*	USAGE 
28
-	*
29
-	*	icingli trapdirector mib update
30
-	*	
31
-	*	OPTIONS
32
-	*	
33
-	*	--pid <file> : run in background with pid in <file>
34
-	*
35
-	*	--verb    : Set output log to verbose
36
-	*
37
-	*   --force-check : force check of all traps & objects for change. (NOT IMPLEMENTED)
38
-	*/
25
+	 *	Update mib database
26
+	 *
27
+	 *	USAGE 
28
+	 *
29
+	 *	icingli trapdirector mib update
30
+	 *	
31
+	 *	OPTIONS
32
+	 *	
33
+	 *	--pid <file> : run in background with pid in <file>
34
+	 *
35
+	 *	--verb    : Set output log to verbose
36
+	 *
37
+	 *   --force-check : force check of all traps & objects for change. (NOT IMPLEMENTED)
38
+	 */
39 39
 	public function updateAction()
40 40
 	{
41
-	    $background = $this->params->get('pid', null);
42
-	    $logLevel= $this->params->has('verb') ? 4 : 2;
43
-	    if ($this->params->has('force-check')) { echo "Not implemented"; return;}
44
-	    $forceCheck=$this->params->has('force-check')?True:False;
45
-	    $pid=1;
46
-	    if ($background != null)
47
-	    {
48
-	        $file=@fopen($background,'w');
49
-	        if ($file == false)
50
-	        {
51
-	            echo 'Error : cannot open pid file '.$background;
52
-	            return 1;
53
-	        }
54
-	        $pid = pcntl_fork();
55
-	        if ($pid == -1) {
56
-	            echo 'Error : Cannot fork process';
57
-	            return 1;
58
-	        }
59
-	    }
60
-	    $module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
41
+		$background = $this->params->get('pid', null);
42
+		$logLevel= $this->params->has('verb') ? 4 : 2;
43
+		if ($this->params->has('force-check')) { echo "Not implemented"; return;}
44
+		$forceCheck=$this->params->has('force-check')?True:False;
45
+		$pid=1;
46
+		if ($background != null)
47
+		{
48
+			$file=@fopen($background,'w');
49
+			if ($file == false)
50
+			{
51
+				echo 'Error : cannot open pid file '.$background;
52
+				return 1;
53
+			}
54
+			$pid = pcntl_fork();
55
+			if ($pid == -1) {
56
+				echo 'Error : Cannot fork process';
57
+				return 1;
58
+			}
59
+		}
60
+		$module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
61 61
 		require_once($module->getBaseDir() .'/bin/trap_class.php');
62 62
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
63 63
 		$trap = new Trap($icingaweb2_etc);
64 64
 		if ($pid == 1)
65 65
 		{
66
-		    $trap->setLogging($logLevel,'display');
66
+			$trap->setLogging($logLevel,'display');
67 67
 		}
68 68
 		else
69 69
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
70
-		    if ($pid != 0)
71
-		    {
72
-		        // father process
73
-		        fwrite($file,$pid);
74
-		        fclose($file);
75
-		        echo "OK : process $pid in bckground";
76
-		        return 0;
77
-		    }
78
-		    else
79
-		    {  // son process : close all file descriptors and go to a new session
80
-		        fclose($file);		        
70
+			if ($pid != 0)
71
+			{
72
+				// father process
73
+				fwrite($file,$pid);
74
+				fclose($file);
75
+				echo "OK : process $pid in bckground";
76
+				return 0;
77
+			}
78
+			else
79
+			{  // son process : close all file descriptors and go to a new session
80
+				fclose($file);		        
81 81
 // 		        $sid = posix_setsid();
82
-                fclose(STDIN);
83
-                fclose(STDOUT);
84
-                fclose(STDERR);
85
-                try
86
-                {
87
-                    $trap->mibClass->update_mib_database(false,$forceCheck);
88
-                }
89
-                catch (Exception $e)
90
-                {
91
-                    $trap->trapLog('Error in updating : ' . $e->getMessage(),2);
92
-                }
93
-                unlink($background);
94
-                return 0;
95
-		    }
82
+				fclose(STDIN);
83
+				fclose(STDOUT);
84
+				fclose(STDERR);
85
+				try
86
+				{
87
+					$trap->mibClass->update_mib_database(false,$forceCheck);
88
+				}
89
+				catch (Exception $e)
90
+				{
91
+					$trap->trapLog('Error in updating : ' . $e->getMessage(),2);
92
+				}
93
+				unlink($background);
94
+				return 0;
95
+			}
96 96
 		    
97 97
 		}
98 98
 		
@@ -110,28 +110,28 @@  discard block
 block discarded – undo
110 110
 		}
111 111
 		if ($pid != 1)
112 112
 		{
113
-		    unlink($background);
113
+			unlink($background);
114 114
 		}
115 115
 	}
116 116
 	/**
117
-	*	purge all mib database NOT IMPLEMENTED
118
-	*
119
-	*	USAGE 
120
-	*
121
-	*	icingli trapdirector mib purge --confirm
122
-	*	
123
-	*	OPTIONS
124
-	*	
125
-	*	--confirm : needed to execute purge
126
-	*/
117
+	 *	purge all mib database NOT IMPLEMENTED
118
+	 *
119
+	 *	USAGE 
120
+	 *
121
+	 *	icingli trapdirector mib purge --confirm
122
+	 *	
123
+	 *	OPTIONS
124
+	 *	
125
+	 *	--confirm : needed to execute purge
126
+	 */
127 127
 	public function purgeAction()
128 128
 	{
129 129
 		$db_prefix=$this->Config()->get('config', 'database_prefix');
130 130
 		
131 131
 		if (!$this->params->has('confirm'))
132 132
 		{
133
-		    echo "This needs confirmation with '--confirm'\n";
134
-		    return;
133
+			echo "This needs confirmation with '--confirm'\n";
134
+			return;
135 135
 		}
136 136
 		
137 137
 		$Config = new TrapModuleConfig($db_prefix);
@@ -144,9 +144,9 @@  discard block
 block discarded – undo
144 144
 			$db = IcingaDbConnection::fromResourceName($dbresource)->getConnection();
145 145
 			
146 146
 			$query = $db->delete(
147
-			    $Config->getMIBCacheTableName(),
148
-			    'id>0');
149
-            echo 'Deleted '. $query . " traps and objects\n";
147
+				$Config->getMIBCacheTableName(),
148
+				'id>0');
149
+			echo 'Deleted '. $query . " traps and objects\n";
150 150
 		}
151 151
 		catch (Exception $e)
152 152
 		{
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -38,39 +38,39 @@  discard block
 block discarded – undo
38 38
 	*/
39 39
 	public function updateAction()
40 40
 	{
41
-	    $background = $this->params->get('pid', null);
42
-	    $logLevel= $this->params->has('verb') ? 4 : 2;
43
-	    if ($this->params->has('force-check')) { echo "Not implemented"; return;}
44
-	    $forceCheck=$this->params->has('force-check')?True:False;
41
+	    $background=$this->params->get('pid', null);
42
+	    $logLevel=$this->params->has('verb') ? 4 : 2;
43
+	    if ($this->params->has('force-check')) { echo "Not implemented"; return; }
44
+	    $forceCheck=$this->params->has('force-check') ?True:False;
45 45
 	    $pid=1;
46 46
 	    if ($background != null)
47 47
 	    {
48
-	        $file=@fopen($background,'w');
48
+	        $file=@fopen($background, 'w');
49 49
 	        if ($file == false)
50 50
 	        {
51 51
 	            echo 'Error : cannot open pid file '.$background;
52 52
 	            return 1;
53 53
 	        }
54
-	        $pid = pcntl_fork();
54
+	        $pid=pcntl_fork();
55 55
 	        if ($pid == -1) {
56 56
 	            echo 'Error : Cannot fork process';
57 57
 	            return 1;
58 58
 	        }
59 59
 	    }
60 60
 	    $module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
61
-		require_once($module->getBaseDir() .'/bin/trap_class.php');
61
+		require_once($module->getBaseDir().'/bin/trap_class.php');
62 62
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
63
-		$trap = new Trap($icingaweb2_etc);
63
+		$trap=new Trap($icingaweb2_etc);
64 64
 		if ($pid == 1)
65 65
 		{
66
-		    $trap->setLogging($logLevel,'display');
66
+		    $trap->setLogging($logLevel, 'display');
67 67
 		}
68 68
 		else
69 69
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
70 70
 		    if ($pid != 0)
71 71
 		    {
72 72
 		        // father process
73
-		        fwrite($file,$pid);
73
+		        fwrite($file, $pid);
74 74
 		        fclose($file);
75 75
 		        echo "OK : process $pid in bckground";
76 76
 		        return 0;
@@ -84,11 +84,11 @@  discard block
 block discarded – undo
84 84
                 fclose(STDERR);
85 85
                 try
86 86
                 {
87
-                    $trap->mibClass->update_mib_database(false,$forceCheck);
87
+                    $trap->mibClass->update_mib_database(false, $forceCheck);
88 88
                 }
89 89
                 catch (Exception $e)
90 90
                 {
91
-                    $trap->trapLog('Error in updating : ' . $e->getMessage(),2);
91
+                    $trap->trapLog('Error in updating : '.$e->getMessage(), 2);
92 92
                 }
93 93
                 unlink($background);
94 94
                 return 0;
@@ -100,13 +100,13 @@  discard block
 block discarded – undo
100 100
 		{
101 101
 			echo "Update main mib database : \n";
102 102
 			echo "# (trap found) C (trap already processed) . (every 2 seconds) : \n";
103
-			$trap->mibClass->update_mib_database(true,$forceCheck);
103
+			$trap->mibClass->update_mib_database(true, $forceCheck);
104 104
 			echo "Done\n";
105 105
 			
106 106
 		}
107 107
 		catch (Exception $e)
108 108
 		{
109
-			echo 'Error in updating : ' . $e->getMessage();
109
+			echo 'Error in updating : '.$e->getMessage();
110 110
 		}
111 111
 		if ($pid != 1)
112 112
 		{
@@ -134,23 +134,23 @@  discard block
 block discarded – undo
134 134
 		    return;
135 135
 		}
136 136
 		
137
-		$Config = new TrapModuleConfig($db_prefix);
137
+		$Config=new TrapModuleConfig($db_prefix);
138 138
 		
139 139
 		try
140 140
 		{
141 141
 			
142 142
 			$dbresource=$this->Config()->get('config', 'database');
143 143
 			echo "DB name : $dbresource\n";
144
-			$db = IcingaDbConnection::fromResourceName($dbresource)->getConnection();
144
+			$db=IcingaDbConnection::fromResourceName($dbresource)->getConnection();
145 145
 			
146
-			$query = $db->delete(
146
+			$query=$db->delete(
147 147
 			    $Config->getMIBCacheTableName(),
148 148
 			    'id>0');
149
-            echo 'Deleted '. $query . " traps and objects\n";
149
+            echo 'Deleted '.$query." traps and objects\n";
150 150
 		}
151 151
 		catch (Exception $e)
152 152
 		{
153
-			echo 'Error in DB : ' . $e->getMessage();
153
+			echo 'Error in DB : '.$e->getMessage();
154 154
 		}	   
155 155
 	}  	 	
156 156
 
Please login to merge, or discard this patch.
Braces   +5 added lines, -10 removed lines patch added patch discarded remove patch
@@ -64,8 +64,7 @@  discard block
 block discarded – undo
64 64
 		if ($pid == 1)
65 65
 		{
66 66
 		    $trap->setLogging($logLevel,'display');
67
-		}
68
-		else
67
+		} else
69 68
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
70 69
 		    if ($pid != 0)
71 70
 		    {
@@ -74,8 +73,7 @@  discard block
 block discarded – undo
74 73
 		        fclose($file);
75 74
 		        echo "OK : process $pid in bckground";
76 75
 		        return 0;
77
-		    }
78
-		    else
76
+		    } else
79 77
 		    {  // son process : close all file descriptors and go to a new session
80 78
 		        fclose($file);		        
81 79
 // 		        $sid = posix_setsid();
@@ -85,8 +83,7 @@  discard block
 block discarded – undo
85 83
                 try
86 84
                 {
87 85
                     $trap->mibClass->update_mib_database(false,$forceCheck);
88
-                }
89
-                catch (Exception $e)
86
+                } catch (Exception $e)
90 87
                 {
91 88
                     $trap->trapLog('Error in updating : ' . $e->getMessage(),2);
92 89
                 }
@@ -103,8 +100,7 @@  discard block
 block discarded – undo
103 100
 			$trap->mibClass->update_mib_database(true,$forceCheck);
104 101
 			echo "Done\n";
105 102
 			
106
-		}
107
-		catch (Exception $e)
103
+		} catch (Exception $e)
108 104
 		{
109 105
 			echo 'Error in updating : ' . $e->getMessage();
110 106
 		}
@@ -147,8 +143,7 @@  discard block
 block discarded – undo
147 143
 			    $Config->getMIBCacheTableName(),
148 144
 			    'id>0');
149 145
             echo 'Deleted '. $query . " traps and objects\n";
150
-		}
151
-		catch (Exception $e)
146
+		} catch (Exception $e)
152 147
 		{
153 148
 			echo 'Error in DB : ' . $e->getMessage();
154 149
 		}	   
Please login to merge, or discard this patch.