Passed
Push — master ( 2ea6c2...c1d2b2 )
by Patrick
02:01
created
library/Trapdirector/Tables/HandlerTable.php 1 patch
Indentation   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -7,136 +7,136 @@
 block discarded – undo
7 7
 class HandlerTable extends TrapDirectorTable
8 8
 {
9 9
 
10
-    protected $status_display=array(
11
-        -2	=>'ignore',
12
-        -1 => '-',
13
-        0	=> 'OK',
14
-        1	=> 'warning',
15
-        2	=> 'critical',
16
-        3	=> 'unknown',);
10
+	protected $status_display=array(
11
+		-2	=>'ignore',
12
+		-1 => '-',
13
+		0	=> 'OK',
14
+		1	=> 'warning',
15
+		2	=> 'critical',
16
+		3	=> 'unknown',);
17 17
     
18
-    // translate
19
-    protected $doTranslate=false;
20
-    protected $MIB;
18
+	// translate
19
+	protected $doTranslate=false;
20
+	protected $MIB;
21 21
     
22
-    // categories
23
-    protected $categories = NULL;
22
+	// categories
23
+	protected $categories = NULL;
24 24
     
25
-    public function setCategoriesArray(array $categories)
26
-    {
27
-        $this->categories = $categories;
28
-    }
25
+	public function setCategoriesArray(array $categories)
26
+	{
27
+		$this->categories = $categories;
28
+	}
29 29
     
30
-    public function groupingPrintData( string $value)
31
-    {
32
-        if ($this->groupingColumn == 'rule_type')
33
-        {
34
-            if ($this->categories == NULL || (! isset($this->categories[$value])))
35
-                return 'Unknown category ('.$value.')';
36
-            return 'Category : '. $this->categories[$value];
37
-        }
38
-        $html = "$value";
39
-        return $html;
40
-    }
30
+	public function groupingPrintData( string $value)
31
+	{
32
+		if ($this->groupingColumn == 'rule_type')
33
+		{
34
+			if ($this->categories == NULL || (! isset($this->categories[$value])))
35
+				return 'Unknown category ('.$value.')';
36
+			return 'Category : '. $this->categories[$value];
37
+		}
38
+		$html = "$value";
39
+		return $html;
40
+	}
41 41
     
42
-    public function setMibloader($mibloader)
43
-    {
44
-        $this->MIB=$mibloader;
45
-        $this->doTranslate=true;
46
-    }
42
+	public function setMibloader($mibloader)
43
+	{
44
+		$this->MIB=$mibloader;
45
+		$this->doTranslate=true;
46
+	}
47 47
 
48
-    public function titleOrder($name)
49
-    {
50
-        switch ($name)
51
-        {
52
-            case 'host_name' : return $this->content[$name]; break;
53
-            case 'source_ip' : return 'ip4'; break;
54
-            default: return $this->content[$name];	
55
-        }
56
-    }
48
+	public function titleOrder($name)
49
+	{
50
+		switch ($name)
51
+		{
52
+			case 'host_name' : return $this->content[$name]; break;
53
+			case 'source_ip' : return 'ip4'; break;
54
+			default: return $this->content[$name];	
55
+		}
56
+	}
57 57
     
58
-    public function getCurrentURL()
59
-    {
60
-        return Url::fromPath($this->urlPath . '/handler');
61
-    }
58
+	public function getCurrentURL()
59
+	{
60
+		return Url::fromPath($this->urlPath . '/handler');
61
+	}
62 62
     
63
-    public function renderLine($row)
64
-      {
65
-          $html = '';
66
-          $firstCol = true;
63
+	public function renderLine($row)
64
+	  {
65
+		  $html = '';
66
+		  $firstCol = true;
67 67
                
68
-          $titleNames = array_keys($this->titles);
69
-          foreach ($titleNames as $rowkey )
70
-          {        
71
-              // Check missing value
72
-              if (property_exists($row, $rowkey))
73
-              {
74
-                  switch ($rowkey)
75
-                  {
76
-                      case 'action_match': // display text levels
77
-                      case 'action_nomatch':
78
-                          $val=$this->status_display[$row->$rowkey];
79
-                          break;
80
-                      case 'trap_oid': // try to traslate oids.
68
+		  $titleNames = array_keys($this->titles);
69
+		  foreach ($titleNames as $rowkey )
70
+		  {        
71
+			  // Check missing value
72
+			  if (property_exists($row, $rowkey))
73
+			  {
74
+				  switch ($rowkey)
75
+				  {
76
+					  case 'action_match': // display text levels
77
+					  case 'action_nomatch':
78
+						  $val=$this->status_display[$row->$rowkey];
79
+						  break;
80
+					  case 'trap_oid': // try to traslate oids.
81 81
                           
82
-                          if ($this->doTranslate === true)
83
-                          {
84
-                              $oidName = $this->MIB->translateOID($row->$rowkey);
85
-                              if (isset($oidName['name']))
86
-                              {
87
-                                  $val=$oidName['name'];
88
-                              }
89
-                              else
90
-                              {
91
-                                  $val = $row->$rowkey;
92
-                              }
93
-                          }
94
-                          else
95
-                          {
96
-                              $val = $row->$rowkey;
97
-                          }
98
-                          break;
99
-                      case 'host_name': // switch to hostgroup if name is null
100
-                          if ($row->$rowkey == null)
101
-                          {
102
-                              $val = $row->host_group_name;
103
-                          }
104
-                          else
105
-                          {
106
-                              $val = $row->$rowkey;
107
-                          }
108
-                          break;
109
-                      default:
110
-                          $val = $row->$rowkey;
111
-                  }
112
-                  if ($rowkey == 'trap_oid' && $this->doTranslate===true)
113
-                  {
82
+						  if ($this->doTranslate === true)
83
+						  {
84
+							  $oidName = $this->MIB->translateOID($row->$rowkey);
85
+							  if (isset($oidName['name']))
86
+							  {
87
+								  $val=$oidName['name'];
88
+							  }
89
+							  else
90
+							  {
91
+								  $val = $row->$rowkey;
92
+							  }
93
+						  }
94
+						  else
95
+						  {
96
+							  $val = $row->$rowkey;
97
+						  }
98
+						  break;
99
+					  case 'host_name': // switch to hostgroup if name is null
100
+						  if ($row->$rowkey == null)
101
+						  {
102
+							  $val = $row->host_group_name;
103
+						  }
104
+						  else
105
+						  {
106
+							  $val = $row->$rowkey;
107
+						  }
108
+						  break;
109
+					  default:
110
+						  $val = $row->$rowkey;
111
+				  }
112
+				  if ($rowkey == 'trap_oid' && $this->doTranslate===true)
113
+				  {
114 114
                       
115
-                  }
116
-              } else {
117
-                  $val = '-';
118
-              }
119
-              if ($firstCol === true) { // Put link in first column for trap detail.
120
-                  $html .= '<td class="traphover">'
121
-                      . $this->view->qlink(
122
-                          $this->view->escape($val),
123
-                          Url::fromPath(
124
-                              $this->urlPath . '/handler/add',
125
-                              array('ruleid' => $row->id)
126
-                              )
127
-                          );
128
-                  if ($row->comment != '')
129
-                  {
130
-                      $html.= '<span class="tohover">'. $row->comment .'</span></td>';
131
-                  }
132
-                  $html.= '</td>';
133
-              } else {
134
-                  $html .= '<td>' . $this->view->escape($val) . '</td>';
135
-              }
136
-              $firstCol=false;
115
+				  }
116
+			  } else {
117
+				  $val = '-';
118
+			  }
119
+			  if ($firstCol === true) { // Put link in first column for trap detail.
120
+				  $html .= '<td class="traphover">'
121
+					  . $this->view->qlink(
122
+						  $this->view->escape($val),
123
+						  Url::fromPath(
124
+							  $this->urlPath . '/handler/add',
125
+							  array('ruleid' => $row->id)
126
+							  )
127
+						  );
128
+				  if ($row->comment != '')
129
+				  {
130
+					  $html.= '<span class="tohover">'. $row->comment .'</span></td>';
131
+				  }
132
+				  $html.= '</td>';
133
+			  } else {
134
+				  $html .= '<td>' . $this->view->escape($val) . '</td>';
135
+			  }
136
+			  $firstCol=false;
137 137
               
138
-          }
139
-          return $html;
140
-      }
138
+		  }
139
+		  return $html;
140
+	  }
141 141
 
142 142
 }
143 143
\ No newline at end of file
Please login to merge, or discard this patch.
library/Trapdirector/Icinga2Api.php 3 patches
Indentation   +336 added lines, -336 removed lines patch added patch discarded remove patch
@@ -8,367 +8,367 @@
 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 ($permissions === NULL || count($permissions) == 0) // If no permission check return OK after connexion
86
-        {
87
-            return array(false,'OK');
88
-        }
89
-        if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
90
-        {
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 ($permissions === NULL || count($permissions) == 0) // If no permission check return OK after connexion
86
+		{
87
+			return array(false,'OK');
88
+		}
89
+		if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
90
+		{
91 91
             
92
-            foreach ( $permissions as $mustPermission)
93
-            {
94
-                $curPermOK=0;
95
-                foreach ( $result->results[0]->permissions as $curPermission)
96
-                {
97
-                    $curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
98
-                    if (preg_match('#'.$curPermission.'#',$mustPermission))
99
-                    {
100
-                        $curPermOK=1;
101
-                        break;
102
-                    }
103
-                }
104
-                if ($curPermOK == 0)
105
-                {
106
-                    $permOk=0;
107
-                    $permMissing=$mustPermission;
108
-                    break;
109
-                }
110
-            }
111
-            if ($permOk == 0)
112
-            {
113
-                return array(true,'API connection OK, but missing permission : '.$permMissing);
114
-            }
115
-            return array(false,'API connection OK');
92
+			foreach ( $permissions as $mustPermission)
93
+			{
94
+				$curPermOK=0;
95
+				foreach ( $result->results[0]->permissions as $curPermission)
96
+				{
97
+					$curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
98
+					if (preg_match('#'.$curPermission.'#',$mustPermission))
99
+					{
100
+						$curPermOK=1;
101
+						break;
102
+					}
103
+				}
104
+				if ($curPermOK == 0)
105
+				{
106
+					$permOk=0;
107
+					$permMissing=$mustPermission;
108
+					break;
109
+				}
110
+			}
111
+			if ($permOk == 0)
112
+			{
113
+				return array(true,'API connection OK, but missing permission : '.$permMissing);
114
+			}
115
+			return array(false,'API connection OK');
116 116
             
117
-        }
118
-        return array(true,'API connection OK, but cannot get permissions');
119
-    }
117
+		}
118
+		return array(true,'API connection OK, but cannot get permissions');
119
+	}
120 120
     
121 121
     
122
-    protected function url($url) {
123
-        return sprintf('https://%s:%d/%s/%s', $this->host, $this->port, $this->version, $url);
124
-    }
122
+	protected function url($url) {
123
+		return sprintf('https://%s:%d/%s/%s', $this->host, $this->port, $this->version, $url);
124
+	}
125 125
     
126
-    /**
127
-     * Create or return curl ressource
128
-     * @throws Exception
129
-     * @return resource
130
-     */
131
-    protected function curl() {
132
-        if ($this->curl === null) {
133
-            $this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
134
-            if ($this->curl === false) {
135
-                throw new Exception('CURL INIT ERROR');
136
-            }
137
-        }
138
-        return $this->curl;
139
-    }
126
+	/**
127
+	 * Create or return curl ressource
128
+	 * @throws Exception
129
+	 * @return resource
130
+	 */
131
+	protected function curl() {
132
+		if ($this->curl === null) {
133
+			$this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
134
+			if ($this->curl === false) {
135
+				throw new Exception('CURL INIT ERROR');
136
+			}
137
+		}
138
+		return $this->curl;
139
+	}
140 140
 
141
-    /**
142
-     * Send a passive service check
143
-     * @param string $host : host name 
144
-     * @param string $service : service name
145
-     * @param int $state : state of service
146
-     * @param string $display : service passive check output
147
-     * @param string $perfdata : performance data as string
148
-     * @return array (status = true (oK) or false (nok), string message)
149
-     */
150
-    public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
151
-    {
152
-        //Send a POST request to the URL endpoint /v1/actions/process-check-result
153
-        //actions/process-check-result?service=example.localdomain!passive-ping6
154
-        $url='actions/process-check-result';
155
-        $body=array(
156
-            "filter"        => 'service.name=="'.$service.'" && service.host_name=="'.$host.'"',
157
-            'type'          => 'Service',
158
-            "exit_status"   => $state,
159
-            "plugin_output" => $display,
160
-            "performance_data" => $perfdata
161
-        );
162
-        try 
163
-        {
164
-            $result=$this->request('POST', $url, null, $body);
165
-        } catch (Exception $e) 
166
-        {
167
-            return array(false, $e->getMessage());
168
-        }
169
-        if (property_exists($result,'error') )
170
-        {
171
-            if (property_exists($result,'status'))
172
-            {
173
-                $message=$result->status;
174
-            }
175
-            else 
176
-            {
177
-                $message="Unkown status";
178
-            }
179
-            return array(false , 'Ret code ' .$result->error.' : '.$message);
180
-        }
181
-        if (property_exists($result, 'results'))
182
-        {
183
-            if (isset($result->results[0]))
184
-            {
185
-                return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
186
-            }
187
-            else
188
-            {
189
-                return array(false,'Service not found');
190
-            }
141
+	/**
142
+	 * Send a passive service check
143
+	 * @param string $host : host name 
144
+	 * @param string $service : service name
145
+	 * @param int $state : state of service
146
+	 * @param string $display : service passive check output
147
+	 * @param string $perfdata : performance data as string
148
+	 * @return array (status = true (oK) or false (nok), string message)
149
+	 */
150
+	public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
151
+	{
152
+		//Send a POST request to the URL endpoint /v1/actions/process-check-result
153
+		//actions/process-check-result?service=example.localdomain!passive-ping6
154
+		$url='actions/process-check-result';
155
+		$body=array(
156
+			"filter"        => 'service.name=="'.$service.'" && service.host_name=="'.$host.'"',
157
+			'type'          => 'Service',
158
+			"exit_status"   => $state,
159
+			"plugin_output" => $display,
160
+			"performance_data" => $perfdata
161
+		);
162
+		try 
163
+		{
164
+			$result=$this->request('POST', $url, null, $body);
165
+		} catch (Exception $e) 
166
+		{
167
+			return array(false, $e->getMessage());
168
+		}
169
+		if (property_exists($result,'error') )
170
+		{
171
+			if (property_exists($result,'status'))
172
+			{
173
+				$message=$result->status;
174
+			}
175
+			else 
176
+			{
177
+				$message="Unkown status";
178
+			}
179
+			return array(false , 'Ret code ' .$result->error.' : '.$message);
180
+		}
181
+		if (property_exists($result, 'results'))
182
+		{
183
+			if (isset($result->results[0]))
184
+			{
185
+				return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
186
+			}
187
+			else
188
+			{
189
+				return array(false,'Service not found');
190
+			}
191 191
             
192
-        }
193
-        return array(false,'Unkown result, open issue with this : '.print_r($result,true));
194
-    }
192
+		}
193
+		return array(false,'Unkown result, open issue with this : '.print_r($result,true));
194
+	}
195 195
  
196
-    /**
197
-     * return array of host by IP (4 or 6)
198
-     * @param string $ip
199
-     * @throws Exception
200
-     * @return array objects : array('__name','name','display_name')
201
-     */
202
-    public function getHostByIP($ip) 
203
-    {
204
-        /*
196
+	/**
197
+	 * return array of host by IP (4 or 6)
198
+	 * @param string $ip
199
+	 * @throws Exception
200
+	 * @return array objects : array('__name','name','display_name')
201
+	 */
202
+	public function getHostByIP($ip) 
203
+	{
204
+		/*
205 205
          *  curl -k -s -u  trapdirector:trapdirector -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts' 
206 206
          *  -d '{"filter":"host.group==\"test_trap\"","attrs": ["address" ,"address6"]}'
207 207
             
208 208
             {"results":[{"attrs":{"__name":"Icinga host","address":"127.0.0.1","display_name":"Icinga host","name":"Icinga host"},"joins":{},"meta":{},"name":"Icinga host","type":"Host"}]}
209 209
          */
210 210
         
211
-        $url='objects/hosts';
212
-        $body=array(
213
-            "filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
214
-            "attrs"         => array('__name','name','display_name','groups')
215
-        );
216
-        try
217
-        {
218
-            $result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
219
-        } catch (Exception $e)
220
-        {
221
-            throw new Exception($e->getMessage());
222
-        }
211
+		$url='objects/hosts';
212
+		$body=array(
213
+			"filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
214
+			"attrs"         => array('__name','name','display_name','groups')
215
+		);
216
+		try
217
+		{
218
+			$result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
219
+		} catch (Exception $e)
220
+		{
221
+			throw new Exception($e->getMessage());
222
+		}
223 223
         
224
-        if (property_exists($result,'error') )
225
-        {
226
-            if (property_exists($result,'status'))
227
-            {
228
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
229
-            }
230
-            else
231
-            {
232
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
233
-            }
234
-        }
235
-        if (property_exists($result, 'results'))
236
-        {
237
-            $numHost=0;
238
-            $hostArray=array();
239
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
240
-            {
241
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
242
-                $numHost++;
243
-            }
244
-            return $hostArray;            
245
-        }
246
-        throw new Exception('Unkown result');
247
-    }
224
+		if (property_exists($result,'error') )
225
+		{
226
+			if (property_exists($result,'status'))
227
+			{
228
+				throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
229
+			}
230
+			else
231
+			{
232
+				throw new Exception('Ret code ' .$result->error.' : Unkown status');
233
+			}
234
+		}
235
+		if (property_exists($result, 'results'))
236
+		{
237
+			$numHost=0;
238
+			$hostArray=array();
239
+			while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
240
+			{
241
+				$hostArray[$numHost] = $result->results[$numHost]->attrs;
242
+				$numHost++;
243
+			}
244
+			return $hostArray;            
245
+		}
246
+		throw new Exception('Unkown result');
247
+	}
248 248
 
249
-    /**
250
-     * Get all host and IP from hostgroup
251
-     * @param string $hostGroup
252
-     * @throws Exception
253
-     * @return array : attributes : address, address6, name
254
-     */
255
-    public function getHostsIPByHostGroup($hostGroup)
256
-    {        
257
-        $url='objects/hosts';
258
-        $body=array(
259
-            "filter"        => '\"'.$hostGroup.'\" in groups',
260
-            "attrs"         => array('address','address','name')
261
-        );
262
-        try
263
-        {
264
-            $result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
265
-        } catch (Exception $e)
266
-        {
267
-            throw new Exception($e->getMessage());
268
-        }
249
+	/**
250
+	 * Get all host and IP from hostgroup
251
+	 * @param string $hostGroup
252
+	 * @throws Exception
253
+	 * @return array : attributes : address, address6, name
254
+	 */
255
+	public function getHostsIPByHostGroup($hostGroup)
256
+	{        
257
+		$url='objects/hosts';
258
+		$body=array(
259
+			"filter"        => '\"'.$hostGroup.'\" in groups',
260
+			"attrs"         => array('address','address','name')
261
+		);
262
+		try
263
+		{
264
+			$result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
265
+		} catch (Exception $e)
266
+		{
267
+			throw new Exception($e->getMessage());
268
+		}
269 269
         
270
-        if (property_exists($result,'error') )
271
-        {
272
-            if (property_exists($result,'status'))
273
-            {
274
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
275
-            }
276
-            else
277
-            {
278
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
279
-            }
280
-        }
281
-        if (property_exists($result, 'results'))
282
-        {
283
-            $numHost=0;
284
-            $hostArray=array();
285
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
286
-            {
287
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
288
-                $hostArray[$numHost]->name = $result->results[$numHost]->name;
289
-                $numHost++;
290
-            }
291
-            return $hostArray;
292
-        }
293
-        throw new Exception('Unkown result');
294
-    }
270
+		if (property_exists($result,'error') )
271
+		{
272
+			if (property_exists($result,'status'))
273
+			{
274
+				throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
275
+			}
276
+			else
277
+			{
278
+				throw new Exception('Ret code ' .$result->error.' : Unkown status');
279
+			}
280
+		}
281
+		if (property_exists($result, 'results'))
282
+		{
283
+			$numHost=0;
284
+			$hostArray=array();
285
+			while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
286
+			{
287
+				$hostArray[$numHost] = $result->results[$numHost]->attrs;
288
+				$hostArray[$numHost]->name = $result->results[$numHost]->name;
289
+				$numHost++;
290
+			}
291
+			return $hostArray;
292
+		}
293
+		throw new Exception('Unkown result');
294
+	}
295 295
     
296
-    /**
297
-     * Send request to API
298
-     * @param string $method get/post/...
299
-     * @param string $url (after /v1/ )
300
-     * @param array $headers
301
-     * @param array $body 
302
-     * @throws Exception
303
-     * @return array
304
-     */
305
-    public function request($method, $url, $headers, $body) {
306
-        $auth = sprintf('%s:%s', $this->user, $this->pass);
307
-        $curlHeaders = array("Accept: application/json");
308
-        if ($body !== null) {
309
-            $body = json_encode($body);
310
-            array_push($curlHeaders, 'Content-Type: application/json');
311
-            //array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
312
-        }
313
-        //var_dump($body);
314
-        //var_dump($this->url($url));
315
-        if ($headers !== null) {
316
-            $curlFinalHeaders = array_merge($curlHeaders, $headers);
317
-        } else 
318
-        {
319
-            $curlFinalHeaders=$curlHeaders;
320
-        }
321
-        $curl = $this->curl();
322
-        $opts = array(
323
-            CURLOPT_URL		=> $this->url($url),
324
-            CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
325
-            CURLOPT_USERPWD		=> $auth,
326
-            CURLOPT_CUSTOMREQUEST	=> strtoupper($method),
327
-            CURLOPT_RETURNTRANSFER 	=> true,
328
-            CURLOPT_CONNECTTIMEOUT 	=> 10,
329
-            CURLOPT_SSL_VERIFYHOST 	=> false,
330
-            CURLOPT_SSL_VERIFYPEER 	=> false,
331
-        );
332
-        if ($body !== null) {
333
-            $opts[CURLOPT_POSTFIELDS] = $body;
334
-        }
335
-        curl_setopt_array($curl, $opts);
336
-        $res = curl_exec($curl);
337
-        if ($res === false) {
338
-            throw new Exception('CURL ERROR: ' . curl_error($curl));
339
-        }
340
-        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
341
-        if ($statusCode === 401) {
342
-            throw new Exception('Unable to authenticate, please check your API credentials');
343
-        }
344
-        return $this->fromJsonResult($res);
345
-    }
296
+	/**
297
+	 * Send request to API
298
+	 * @param string $method get/post/...
299
+	 * @param string $url (after /v1/ )
300
+	 * @param array $headers
301
+	 * @param array $body 
302
+	 * @throws Exception
303
+	 * @return array
304
+	 */
305
+	public function request($method, $url, $headers, $body) {
306
+		$auth = sprintf('%s:%s', $this->user, $this->pass);
307
+		$curlHeaders = array("Accept: application/json");
308
+		if ($body !== null) {
309
+			$body = json_encode($body);
310
+			array_push($curlHeaders, 'Content-Type: application/json');
311
+			//array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
312
+		}
313
+		//var_dump($body);
314
+		//var_dump($this->url($url));
315
+		if ($headers !== null) {
316
+			$curlFinalHeaders = array_merge($curlHeaders, $headers);
317
+		} else 
318
+		{
319
+			$curlFinalHeaders=$curlHeaders;
320
+		}
321
+		$curl = $this->curl();
322
+		$opts = array(
323
+			CURLOPT_URL		=> $this->url($url),
324
+			CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
325
+			CURLOPT_USERPWD		=> $auth,
326
+			CURLOPT_CUSTOMREQUEST	=> strtoupper($method),
327
+			CURLOPT_RETURNTRANSFER 	=> true,
328
+			CURLOPT_CONNECTTIMEOUT 	=> 10,
329
+			CURLOPT_SSL_VERIFYHOST 	=> false,
330
+			CURLOPT_SSL_VERIFYPEER 	=> false,
331
+		);
332
+		if ($body !== null) {
333
+			$opts[CURLOPT_POSTFIELDS] = $body;
334
+		}
335
+		curl_setopt_array($curl, $opts);
336
+		$res = curl_exec($curl);
337
+		if ($res === false) {
338
+			throw new Exception('CURL ERROR: ' . curl_error($curl));
339
+		}
340
+		$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
341
+		if ($statusCode === 401) {
342
+			throw new Exception('Unable to authenticate, please check your API credentials');
343
+		}
344
+		return $this->fromJsonResult($res);
345
+	}
346 346
     
347
-    /**
348
-     * 
349
-     * @param string $json json encoded 
350
-     * @throws Exception
351
-     * @return array json decoded
352
-     */
353
-    protected function fromJsonResult($json) {
354
-        $result = @json_decode($json);
355
-        //var_dump($json);
356
-        if ($result === null) {
357
-            throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
358
-        }
359
-        return $result;
360
-    }
347
+	/**
348
+	 * 
349
+	 * @param string $json json encoded 
350
+	 * @throws Exception
351
+	 * @return array json decoded
352
+	 */
353
+	protected function fromJsonResult($json) {
354
+		$result = @json_decode($json);
355
+		//var_dump($json);
356
+		if ($result === null) {
357
+			throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
358
+		}
359
+		return $result;
360
+	}
361 361
     
362
-    /**
363
-     * Return text error no json error
364
-     * @param string $errorCode
365
-     * @return string
366
-     */
367
-    protected function getLastJsonErrorMessage($errorCode) {
368
-        if (!array_key_exists($errorCode, $this->errorReference)) {
369
-            return self::JSON_UNKNOWN_ERROR;
370
-        }
371
-        return $this->errorReference[$errorCode];
372
-    }
362
+	/**
363
+	 * Return text error no json error
364
+	 * @param string $errorCode
365
+	 * @return string
366
+	 */
367
+	protected function getLastJsonErrorMessage($errorCode) {
368
+		if (!array_key_exists($errorCode, $this->errorReference)) {
369
+			return self::JSON_UNKNOWN_ERROR;
370
+		}
371
+		return $this->errorReference[$errorCode];
372
+	}
373 373
 }
374 374
 
Please login to merge, or discard this patch.
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,18 +84,18 @@  discard block
 block discarded – undo
84 84
         $permMissing='';
85 85
         if ($permissions === NULL || count($permissions) == 0) // If no permission check return OK after connexion
86 86
         {
87
-            return array(false,'OK');
87
+            return array(false, 'OK');
88 88
         }
89 89
         if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
90 90
         {
91 91
             
92
-            foreach ( $permissions as $mustPermission)
92
+            foreach ($permissions as $mustPermission)
93 93
             {
94 94
                 $curPermOK=0;
95
-                foreach ( $result->results[0]->permissions as $curPermission)
95
+                foreach ($result->results[0]->permissions as $curPermission)
96 96
                 {
97
-                    $curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
98
-                    if (preg_match('#'.$curPermission.'#',$mustPermission))
97
+                    $curPermission=preg_replace('/\*/', '.*', $curPermission); // put * as .* to created a regexp
98
+                    if (preg_match('#'.$curPermission.'#', $mustPermission))
99 99
                     {
100 100
                         $curPermOK=1;
101 101
                         break;
@@ -110,12 +110,12 @@  discard block
 block discarded – undo
110 110
             }
111 111
             if ($permOk == 0)
112 112
             {
113
-                return array(true,'API connection OK, but missing permission : '.$permMissing);
113
+                return array(true, 'API connection OK, but missing permission : '.$permMissing);
114 114
             }
115
-            return array(false,'API connection OK');
115
+            return array(false, 'API connection OK');
116 116
             
117 117
         }
118
-        return array(true,'API connection OK, but cannot get permissions');
118
+        return array(true, 'API connection OK, but cannot get permissions');
119 119
     }
120 120
     
121 121
     
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
      */
131 131
     protected function curl() {
132 132
         if ($this->curl === null) {
133
-            $this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
133
+            $this->curl=curl_init(sprintf('https://%s:%d', $this->host, $this->port));
134 134
             if ($this->curl === false) {
135 135
                 throw new Exception('CURL INIT ERROR');
136 136
             }
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
      * @param string $perfdata : performance data as string
148 148
      * @return array (status = true (oK) or false (nok), string message)
149 149
      */
150
-    public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
150
+    public function serviceCheckResult($host, $service, $state, $display, $perfdata='')
151 151
     {
152 152
         //Send a POST request to the URL endpoint /v1/actions/process-check-result
153 153
         //actions/process-check-result?service=example.localdomain!passive-ping6
@@ -166,9 +166,9 @@  discard block
 block discarded – undo
166 166
         {
167 167
             return array(false, $e->getMessage());
168 168
         }
169
-        if (property_exists($result,'error') )
169
+        if (property_exists($result, 'error'))
170 170
         {
171
-            if (property_exists($result,'status'))
171
+            if (property_exists($result, 'status'))
172 172
             {
173 173
                 $message=$result->status;
174 174
             }
@@ -176,21 +176,21 @@  discard block
 block discarded – undo
176 176
             {
177 177
                 $message="Unkown status";
178 178
             }
179
-            return array(false , 'Ret code ' .$result->error.' : '.$message);
179
+            return array(false, 'Ret code '.$result->error.' : '.$message);
180 180
         }
181 181
         if (property_exists($result, 'results'))
182 182
         {
183 183
             if (isset($result->results[0]))
184 184
             {
185
-                return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
185
+                return array(true, 'code '.$result->results[0]->code.' : '.$result->results[0]->status);
186 186
             }
187 187
             else
188 188
             {
189
-                return array(false,'Service not found');
189
+                return array(false, 'Service not found');
190 190
             }
191 191
             
192 192
         }
193
-        return array(false,'Unkown result, open issue with this : '.print_r($result,true));
193
+        return array(false, 'Unkown result, open issue with this : '.print_r($result, true));
194 194
     }
195 195
  
196 196
     /**
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
         $url='objects/hosts';
212 212
         $body=array(
213 213
             "filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
214
-            "attrs"         => array('__name','name','display_name','groups')
214
+            "attrs"         => array('__name', 'name', 'display_name', 'groups')
215 215
         );
216 216
         try
217 217
         {
@@ -221,24 +221,24 @@  discard block
 block discarded – undo
221 221
             throw new Exception($e->getMessage());
222 222
         }
223 223
         
224
-        if (property_exists($result,'error') )
224
+        if (property_exists($result, 'error'))
225 225
         {
226
-            if (property_exists($result,'status'))
226
+            if (property_exists($result, 'status'))
227 227
             {
228
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
228
+                throw new Exception('Ret code '.$result->error.' : '.$result->status);
229 229
             }
230 230
             else
231 231
             {
232
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
232
+                throw new Exception('Ret code '.$result->error.' : Unkown status');
233 233
             }
234 234
         }
235 235
         if (property_exists($result, 'results'))
236 236
         {
237 237
             $numHost=0;
238 238
             $hostArray=array();
239
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
239
+            while (isset($result->results[$numHost]) && property_exists($result->results[$numHost], 'attrs'))
240 240
             {
241
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
241
+                $hostArray[$numHost]=$result->results[$numHost]->attrs;
242 242
                 $numHost++;
243 243
             }
244 244
             return $hostArray;            
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
         $url='objects/hosts';
258 258
         $body=array(
259 259
             "filter"        => '\"'.$hostGroup.'\" in groups',
260
-            "attrs"         => array('address','address','name')
260
+            "attrs"         => array('address', 'address', 'name')
261 261
         );
262 262
         try
263 263
         {
@@ -267,25 +267,25 @@  discard block
 block discarded – undo
267 267
             throw new Exception($e->getMessage());
268 268
         }
269 269
         
270
-        if (property_exists($result,'error') )
270
+        if (property_exists($result, 'error'))
271 271
         {
272
-            if (property_exists($result,'status'))
272
+            if (property_exists($result, 'status'))
273 273
             {
274
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
274
+                throw new Exception('Ret code '.$result->error.' : '.$result->status);
275 275
             }
276 276
             else
277 277
             {
278
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
278
+                throw new Exception('Ret code '.$result->error.' : Unkown status');
279 279
             }
280 280
         }
281 281
         if (property_exists($result, 'results'))
282 282
         {
283 283
             $numHost=0;
284 284
             $hostArray=array();
285
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
285
+            while (isset($result->results[$numHost]) && property_exists($result->results[$numHost], 'attrs'))
286 286
             {
287
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
288
-                $hostArray[$numHost]->name = $result->results[$numHost]->name;
287
+                $hostArray[$numHost]=$result->results[$numHost]->attrs;
288
+                $hostArray[$numHost]->name=$result->results[$numHost]->name;
289 289
                 $numHost++;
290 290
             }
291 291
             return $hostArray;
@@ -303,23 +303,23 @@  discard block
 block discarded – undo
303 303
      * @return array
304 304
      */
305 305
     public function request($method, $url, $headers, $body) {
306
-        $auth = sprintf('%s:%s', $this->user, $this->pass);
307
-        $curlHeaders = array("Accept: application/json");
306
+        $auth=sprintf('%s:%s', $this->user, $this->pass);
307
+        $curlHeaders=array("Accept: application/json");
308 308
         if ($body !== null) {
309
-            $body = json_encode($body);
309
+            $body=json_encode($body);
310 310
             array_push($curlHeaders, 'Content-Type: application/json');
311 311
             //array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
312 312
         }
313 313
         //var_dump($body);
314 314
         //var_dump($this->url($url));
315 315
         if ($headers !== null) {
316
-            $curlFinalHeaders = array_merge($curlHeaders, $headers);
316
+            $curlFinalHeaders=array_merge($curlHeaders, $headers);
317 317
         } else 
318 318
         {
319 319
             $curlFinalHeaders=$curlHeaders;
320 320
         }
321
-        $curl = $this->curl();
322
-        $opts = array(
321
+        $curl=$this->curl();
322
+        $opts=array(
323 323
             CURLOPT_URL		=> $this->url($url),
324 324
             CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
325 325
             CURLOPT_USERPWD		=> $auth,
@@ -330,14 +330,14 @@  discard block
 block discarded – undo
330 330
             CURLOPT_SSL_VERIFYPEER 	=> false,
331 331
         );
332 332
         if ($body !== null) {
333
-            $opts[CURLOPT_POSTFIELDS] = $body;
333
+            $opts[CURLOPT_POSTFIELDS]=$body;
334 334
         }
335 335
         curl_setopt_array($curl, $opts);
336
-        $res = curl_exec($curl);
336
+        $res=curl_exec($curl);
337 337
         if ($res === false) {
338
-            throw new Exception('CURL ERROR: ' . curl_error($curl));
338
+            throw new Exception('CURL ERROR: '.curl_error($curl));
339 339
         }
340
-        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
340
+        $statusCode=curl_getinfo($curl, CURLINFO_HTTP_CODE);
341 341
         if ($statusCode === 401) {
342 342
             throw new Exception('Unable to authenticate, please check your API credentials');
343 343
         }
@@ -351,7 +351,7 @@  discard block
 block discarded – undo
351 351
      * @return array json decoded
352 352
      */
353 353
     protected function fromJsonResult($json) {
354
-        $result = @json_decode($json);
354
+        $result=@json_decode($json);
355 355
         //var_dump($json);
356 356
         if ($result === null) {
357 357
             throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
Please login to merge, or discard this patch.
Braces   +8 added lines, -11 removed lines patch added patch discarded remove patch
@@ -74,18 +74,19 @@  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
         }
82 81
         //var_dump($result);
83 82
         $permOk=1;
84 83
         $permMissing='';
85
-        if ($permissions === NULL || count($permissions) == 0) // If no permission check return OK after connexion
84
+        if ($permissions === NULL || count($permissions) == 0) {
85
+        	// If no permission check return OK after connexion
86 86
         {
87 87
             return array(false,'OK');
88 88
         }
89
+        }
89 90
         if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
90 91
         {
91 92
             
@@ -171,8 +172,7 @@  discard block
 block discarded – undo
171 172
             if (property_exists($result,'status'))
172 173
             {
173 174
                 $message=$result->status;
174
-            }
175
-            else 
175
+            } else 
176 176
             {
177 177
                 $message="Unkown status";
178 178
             }
@@ -183,8 +183,7 @@  discard block
 block discarded – undo
183 183
             if (isset($result->results[0]))
184 184
             {
185 185
                 return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
186
-            }
187
-            else
186
+            } else
188 187
             {
189 188
                 return array(false,'Service not found');
190 189
             }
@@ -226,8 +225,7 @@  discard block
 block discarded – undo
226 225
             if (property_exists($result,'status'))
227 226
             {
228 227
                 throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
229
-            }
230
-            else
228
+            } else
231 229
             {
232 230
                 throw new Exception('Ret code ' .$result->error.' : Unkown status');
233 231
             }
@@ -272,8 +270,7 @@  discard block
 block discarded – undo
272 270
             if (property_exists($result,'status'))
273 271
             {
274 272
                 throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
275
-            }
276
-            else
273
+            } else
277 274
             {
278 275
                 throw new Exception('Ret code ' .$result->error.' : Unkown status');
279 276
             }
Please login to merge, or discard this patch.
library/Trapdirector/TrapsController.php 2 patches
Indentation   +103 added lines, -103 removed lines patch added patch discarded remove patch
@@ -46,8 +46,8 @@  discard block
 block discarded – undo
46 46
 	
47 47
 	
48 48
 	/** Get instance of TrapModuleConfig class
49
-	*	@return TrapModuleConfig
50
-	*/
49
+	 *	@return TrapModuleConfig
50
+	 */
51 51
 	public function getModuleConfig() 
52 52
 	{
53 53
 		if ($this->moduleConfig == Null) 
@@ -79,12 +79,12 @@  discard block
 block discarded – undo
79 79
 	 */
80 80
 	public function getTrapHostListTable()
81 81
 	{
82
-	    if ($this->trapTableHostList == Null) 
82
+		if ($this->trapTableHostList == Null) 
83 83
 		{
84
-	        $this->trapTableHostList = new TrapTableHostList();
85
-	        $this->trapTableHostList->setConfig($this->getModuleConfig());
86
-	    }
87
-	    return $this->trapTableHostList;
84
+			$this->trapTableHostList = new TrapTableHostList();
85
+			$this->trapTableHostList->setConfig($this->getModuleConfig());
86
+		}
87
+		return $this->trapTableHostList;
88 88
 	}
89 89
 	
90 90
 	/**
@@ -105,12 +105,12 @@  discard block
 block discarded – undo
105 105
 	 */
106 106
 	public function getUIDatabase()
107 107
 	{
108
-	    if ($this->UIDatabase == Null)
109
-	    {
110
-	        $this->UIDatabase = new UIDatabase($this);
108
+		if ($this->UIDatabase == Null)
109
+		{
110
+			$this->UIDatabase = new UIDatabase($this);
111 111
 	       
112
-	    }
113
-	    return $this->UIDatabase;
112
+		}
113
+		return $this->UIDatabase;
114 114
 	}
115 115
 
116 116
 	/**
@@ -119,34 +119,34 @@  discard block
 block discarded – undo
119 119
 	 */
120 120
 	public function getIdoConn()
121 121
 	{
122
-	    if ($this->icingaAPI === NULL)
123
-	    {
124
-    	    $host = $this->Config()->get('config', 'icingaAPI_host');
125
-    	    $port = $this->Config()->get('config', 'icingaAPI_port');
126
-    	    $user = $this->Config()->get('config', 'icingaAPI_user');
127
-    	    $pass = $this->Config()->get('config', 'icingaAPI_password');
128
-    	    $this->icingaAPI = new Icinga2Api($host,$port);
129
-    	    $this->icingaAPI->setCredentials($user, $pass);
130
-    	    list($ret,$message) = $this->icingaAPI->test(array());
131
-    	    if ($ret === TRUE)
132
-    	    {
133
-    	        return $this->getUIDatabase();
134
-    	    }
122
+		if ($this->icingaAPI === NULL)
123
+		{
124
+			$host = $this->Config()->get('config', 'icingaAPI_host');
125
+			$port = $this->Config()->get('config', 'icingaAPI_port');
126
+			$user = $this->Config()->get('config', 'icingaAPI_user');
127
+			$pass = $this->Config()->get('config', 'icingaAPI_password');
128
+			$this->icingaAPI = new Icinga2Api($host,$port);
129
+			$this->icingaAPI->setCredentials($user, $pass);
130
+			list($ret,$message) = $this->icingaAPI->test(array());
131
+			if ($ret === TRUE)
132
+			{
133
+				return $this->getUIDatabase();
134
+			}
135 135
     	    
136
-	    }
137
-	    return $this->icingaAPI;
136
+		}
137
+		return $this->icingaAPI;
138 138
 	    
139 139
 	}
140 140
 	
141
-    protected function applyPaginationLimits(Paginatable $paginatable, $limit = 25, $offset = null)
142
-    {
143
-        $limit = $this->params->get('limit', $limit);
144
-        $page = $this->params->get('page', $offset);
141
+	protected function applyPaginationLimits(Paginatable $paginatable, $limit = 25, $offset = null)
142
+	{
143
+		$limit = $this->params->get('limit', $limit);
144
+		$page = $this->params->get('page', $offset);
145 145
 
146
-        $paginatable->limit($limit, $page > 0 ? ($page - 1) * $limit : 0);
146
+		$paginatable->limit($limit, $page > 0 ? ($page - 1) * $limit : 0);
147 147
 
148
-        return $paginatable;
149
-    }	
148
+		return $paginatable;
149
+	}	
150 150
 	
151 151
 	public function displayExitError($source,$message)
152 152
 	{	// TODO : check better ways to transmit data (with POST ?)
@@ -155,33 +155,33 @@  discard block
 block discarded – undo
155 155
 	
156 156
 	protected function checkReadPermission()
157 157
 	{
158
-        if (! $this->Auth()->hasPermission('trapdirector/view')) {
159
-            $this->displayExitError('Permissions','No permission fo view content');
160
-        }		
158
+		if (! $this->Auth()->hasPermission('trapdirector/view')) {
159
+			$this->displayExitError('Permissions','No permission fo view content');
160
+		}		
161 161
 	}
162 162
 
163 163
 	protected function checkConfigPermission()
164 164
 	{
165
-        if (! $this->Auth()->hasPermission('trapdirector/config')) {
166
-            $this->displayExitError('Permissions','No permission fo configure');
167
-        }		
165
+		if (! $this->Auth()->hasPermission('trapdirector/config')) {
166
+			$this->displayExitError('Permissions','No permission fo configure');
167
+		}		
168 168
 	}
169 169
 	
170
-    /**
171
-     * Check if user has write permission
172
-     * @param number $check optional : if set to 1, return true (user has permission) or false instead of displaying error page
173
-     * @return boolean : user has permission
174
-     */
170
+	/**
171
+	 * Check if user has write permission
172
+	 * @param number $check optional : if set to 1, return true (user has permission) or false instead of displaying error page
173
+	 * @return boolean : user has permission
174
+	 */
175 175
 	protected function checkModuleConfigPermission($check=0)
176 176
 	{
177
-        if (! $this->Auth()->hasPermission('trapdirector/module_config')) {
178
-            if ($check == 0)
179
-            {
180
-                $this->displayExitError('Permissions','No permission fo configure module');
181
-            }
182
-            return false;
183
-        }
184
-        return true;
177
+		if (! $this->Auth()->hasPermission('trapdirector/module_config')) {
178
+			if ($check == 0)
179
+			{
180
+				$this->displayExitError('Permissions','No permission fo configure module');
181
+			}
182
+			return false;
183
+		}
184
+		return true;
185 185
 	}
186 186
 
187 187
 	/*************************  Trap class get **********************/
@@ -201,18 +201,18 @@  discard block
 block discarded – undo
201 201
 	/************************** MIB related **************************/
202 202
 	
203 203
 	/** Get MIBLoader class
204
-	*	@return MIBLoader class
205
-	*/
204
+	 *	@return MIBLoader class
205
+	 */
206 206
 	protected function getMIB()
207 207
 	{
208 208
 		if ($this->MIBData == null)
209 209
 		{
210
-		    $dbConn = $this->getUIDatabase()->getDbConn();
211
-		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
210
+			$dbConn = $this->getUIDatabase()->getDbConn();
211
+			if ($dbConn === null) throw new \ErrorException('uncatched db error');
212 212
 			$this->MIBData=new MIBLoader(
213 213
 				$this->Config()->get('config', 'snmptranslate'),
214 214
 				$this->Config()->get('config', 'snmptranslate_dirs'),
215
-			    $dbConn,
215
+				$dbConn,
216 216
 				$this->getModuleConfig()
217 217
 			);
218 218
 		}
@@ -222,13 +222,13 @@  discard block
 block discarded – undo
222 222
 	/**************************  Database queries *******************/		
223 223
 	
224 224
 	/** Check if director is installed
225
-	*	@return bool true/false
226
-	*/
225
+	 *	@return bool true/false
226
+	 */
227 227
 	protected function isDirectorInstalled()
228 228
 	{
229
-	    $output=array();
230
-	    exec('icingacli module list',$output);
231
-	    foreach ($output as $line)
229
+		$output=array();
230
+		exec('icingacli module list',$output);
231
+		foreach ($output as $line)
232 232
 		{
233 233
 			if (preg_match('/^director .*enabled/',$line))
234 234
 			{
@@ -241,72 +241,72 @@  discard block
 block discarded – undo
241 241
 
242 242
 	/************************ UI elements **************************/
243 243
 	
244
-    /**
245
-     * get max rows to display before paging.
246
-     * @return number
247
-     */
244
+	/**
245
+	 * get max rows to display before paging.
246
+	 * @return number
247
+	 */
248 248
 	public function itemListDisplay()
249 249
 	{
250
-	    return $this->getUIDatabase()->getDBConfigValue('max_rows_in_list');
250
+		return $this->getUIDatabase()->getDBConfigValue('max_rows_in_list');
251 251
 	}
252 252
 
253 253
 	public function setitemListDisplay(int $maxRows)
254 254
 	{
255
-	    return $this->getUIDatabase()->setDBConfigValue('max_rows_in_list',$maxRows);
255
+		return $this->getUIDatabase()->setDBConfigValue('max_rows_in_list',$maxRows);
256 256
 	}
257 257
 	
258
-    /**
259
-     * get Handlers categories list (index => textvalue).
260
-     * @return array
261
-     */	
258
+	/**
259
+	 * get Handlers categories list (index => textvalue).
260
+	 * @return array
261
+	 */	
262 262
 	public function getHandlersCategory()
263 263
 	{
264
-	    //<index>:<name>!<index>:<name>
265
-	    $catList = $this->getUIDatabase()->getDBConfigValue('handler_categories');
266
-	    $catListArray=explode('!',$catList);
267
-	    $retArray=array();
268
-	    foreach ($catListArray as $category)
269
-	    {
270
-	        $catArray=explode(':',$category);
271
-	        $retArray[$catArray[0]] = $catArray[1];
272
-	    }
273
-	    return $retArray; 
264
+		//<index>:<name>!<index>:<name>
265
+		$catList = $this->getUIDatabase()->getDBConfigValue('handler_categories');
266
+		$catListArray=explode('!',$catList);
267
+		$retArray=array();
268
+		foreach ($catListArray as $category)
269
+		{
270
+			$catArray=explode(':',$category);
271
+			$retArray[$catArray[0]] = $catArray[1];
272
+		}
273
+		return $retArray; 
274 274
 	}
275 275
 
276 276
 	public function setHandlerCategory(array $catArray)
277 277
 	{
278
-	    $catString='';
279
-	    foreach ($catArray as $index => $value)
280
-	    {
281
-	        if ($catString != '' ) $catString .= '!';
282
-	        $catString .= $index . ':' . $value;
283
-	    }
284
-	    $this->getUIDatabase()->setDBConfigValue('handler_categories', $catString);
278
+		$catString='';
279
+		foreach ($catArray as $index => $value)
280
+		{
281
+			if ($catString != '' ) $catString .= '!';
282
+			$catString .= $index . ':' . $value;
283
+		}
284
+		$this->getUIDatabase()->setDBConfigValue('handler_categories', $catString);
285 285
 	}
286 286
 	
287 287
 	public function addHandlersCategory(string $catName)
288 288
 	{
289
-	    $catArray = $this->getHandlersCategory();
290
-	    $i=1;
291
-	    while (isset($catArray[$i]) && $i < 100) $i++;
292
-	    if ($i == 100) throw new ProgrammingError('Category array error');
293
-	    $catArray[$i] = $catName;
294
-	    $this->setHandlerCategory($catArray);
289
+		$catArray = $this->getHandlersCategory();
290
+		$i=1;
291
+		while (isset($catArray[$i]) && $i < 100) $i++;
292
+		if ($i == 100) throw new ProgrammingError('Category array error');
293
+		$catArray[$i] = $catName;
294
+		$this->setHandlerCategory($catArray);
295 295
 	}
296 296
 	
297 297
 	public function delHandlersCategory(int $catIndex)
298 298
 	{
299
-	    $catArray = $this->getHandlersCategory();
300
-	    unset($catArray[$catIndex]);
301
-	    $this->setHandlerCategory($catArray);
302
-	    $this->getUIDatabase()->updateHandlersOnCategoryDelete($catIndex);
299
+		$catArray = $this->getHandlersCategory();
300
+		unset($catArray[$catIndex]);
301
+		$this->setHandlerCategory($catArray);
302
+		$this->getUIDatabase()->updateHandlersOnCategoryDelete($catIndex);
303 303
 	}
304 304
 	
305 305
 	public function renameHandlersCategory(int $catIndex, string $catName)
306 306
 	{
307
-	    $catArray = $this->getHandlersCategory();
308
-	    $catArray[$catIndex] = $catName;
309
-	    $this->setHandlerCategory($catArray);
307
+		$catArray = $this->getHandlersCategory();
308
+		$catArray[$catIndex] = $catName;
309
+		$this->setHandlerCategory($catArray);
310 310
 	}
311 311
 	
312 312
 }
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
 	/** @var UIDatabase $UIDatabase */
42 42
 	protected $UIDatabase;
43 43
 	/** @var Icinga2Api $IcingaAPI */
44
-	protected $icingaAPI = NULL;
44
+	protected $icingaAPI=NULL;
45 45
 	
46 46
 	
47 47
 	
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 			{
58 58
 				$this->redirectNow('trapdirector/settings?message=No database prefix');
59 59
 			}
60
-			$this->moduleConfig = new TrapModuleConfig($db_prefix);
60
+			$this->moduleConfig=new TrapModuleConfig($db_prefix);
61 61
 		}
62 62
 		return $this->moduleConfig;
63 63
 	}
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 	 */
69 69
 	public function getTrapListTable() {
70 70
 		if ($this->trapTableList == Null) {
71
-			$this->trapTableList = new TrapTableList();
71
+			$this->trapTableList=new TrapTableList();
72 72
 			$this->trapTableList->setConfig($this->getModuleConfig());
73 73
 		}
74 74
 		return $this->trapTableList;
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
 	{
82 82
 	    if ($this->trapTableHostList == Null) 
83 83
 		{
84
-	        $this->trapTableHostList = new TrapTableHostList();
84
+	        $this->trapTableHostList=new TrapTableHostList();
85 85
 	        $this->trapTableHostList->setConfig($this->getModuleConfig());
86 86
 	    }
87 87
 	    return $this->trapTableHostList;
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	{
95 95
 		if ($this->handlerTableList == Null) 
96 96
 		{
97
-			$this->handlerTableList = new HandlerTableList();
97
+			$this->handlerTableList=new HandlerTableList();
98 98
 			$this->handlerTableList->setConfig($this->getModuleConfig());
99 99
 		}
100 100
 		return $this->handlerTableList;
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 	{
108 108
 	    if ($this->UIDatabase == Null)
109 109
 	    {
110
-	        $this->UIDatabase = new UIDatabase($this);
110
+	        $this->UIDatabase=new UIDatabase($this);
111 111
 	       
112 112
 	    }
113 113
 	    return $this->UIDatabase;
@@ -121,13 +121,13 @@  discard block
 block discarded – undo
121 121
 	{
122 122
 	    if ($this->icingaAPI === NULL)
123 123
 	    {
124
-    	    $host = $this->Config()->get('config', 'icingaAPI_host');
125
-    	    $port = $this->Config()->get('config', 'icingaAPI_port');
126
-    	    $user = $this->Config()->get('config', 'icingaAPI_user');
127
-    	    $pass = $this->Config()->get('config', 'icingaAPI_password');
128
-    	    $this->icingaAPI = new Icinga2Api($host,$port);
124
+    	    $host=$this->Config()->get('config', 'icingaAPI_host');
125
+    	    $port=$this->Config()->get('config', 'icingaAPI_port');
126
+    	    $user=$this->Config()->get('config', 'icingaAPI_user');
127
+    	    $pass=$this->Config()->get('config', 'icingaAPI_password');
128
+    	    $this->icingaAPI=new Icinga2Api($host, $port);
129 129
     	    $this->icingaAPI->setCredentials($user, $pass);
130
-    	    list($ret,$message) = $this->icingaAPI->test(array());
130
+    	    list($ret, $message)=$this->icingaAPI->test(array());
131 131
     	    if ($ret === TRUE)
132 132
     	    {
133 133
     	        return $this->getUIDatabase();
@@ -138,32 +138,32 @@  discard block
 block discarded – undo
138 138
 	    
139 139
 	}
140 140
 	
141
-    protected function applyPaginationLimits(Paginatable $paginatable, $limit = 25, $offset = null)
141
+    protected function applyPaginationLimits(Paginatable $paginatable, $limit=25, $offset=null)
142 142
     {
143
-        $limit = $this->params->get('limit', $limit);
144
-        $page = $this->params->get('page', $offset);
143
+        $limit=$this->params->get('limit', $limit);
144
+        $page=$this->params->get('page', $offset);
145 145
 
146 146
         $paginatable->limit($limit, $page > 0 ? ($page - 1) * $limit : 0);
147 147
 
148 148
         return $paginatable;
149 149
     }	
150 150
 	
151
-	public function displayExitError($source,$message)
151
+	public function displayExitError($source, $message)
152 152
 	{	// TODO : check better ways to transmit data (with POST ?)
153 153
 		$this->redirectNow('trapdirector/error?source='.$source.'&message='.$message);
154 154
 	}
155 155
 	
156 156
 	protected function checkReadPermission()
157 157
 	{
158
-        if (! $this->Auth()->hasPermission('trapdirector/view')) {
159
-            $this->displayExitError('Permissions','No permission fo view content');
158
+        if (!$this->Auth()->hasPermission('trapdirector/view')) {
159
+            $this->displayExitError('Permissions', 'No permission fo view content');
160 160
         }		
161 161
 	}
162 162
 
163 163
 	protected function checkConfigPermission()
164 164
 	{
165
-        if (! $this->Auth()->hasPermission('trapdirector/config')) {
166
-            $this->displayExitError('Permissions','No permission fo configure');
165
+        if (!$this->Auth()->hasPermission('trapdirector/config')) {
166
+            $this->displayExitError('Permissions', 'No permission fo configure');
167 167
         }		
168 168
 	}
169 169
 	
@@ -174,10 +174,10 @@  discard block
 block discarded – undo
174 174
      */
175 175
 	protected function checkModuleConfigPermission($check=0)
176 176
 	{
177
-        if (! $this->Auth()->hasPermission('trapdirector/module_config')) {
177
+        if (!$this->Auth()->hasPermission('trapdirector/module_config')) {
178 178
             if ($check == 0)
179 179
             {
180
-                $this->displayExitError('Permissions','No permission fo configure module');
180
+                $this->displayExitError('Permissions', 'No permission fo configure module');
181 181
             }
182 182
             return false;
183 183
         }
@@ -189,10 +189,10 @@  discard block
 block discarded – undo
189 189
 	{ // TODO : try/catch here ? or within caller
190 190
 		if ($this->trapClass == null)
191 191
 		{
192
-			require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
192
+			require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
193 193
 			$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
194 194
 			//$debug_level=4;
195
-			$this->trapClass = new Trap($icingaweb2_etc);
195
+			$this->trapClass=new Trap($icingaweb2_etc);
196 196
 			//$Trap->setLogging($debug_level,'syslog');
197 197
 		}
198 198
 		return $this->trapClass;
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 	{
208 208
 		if ($this->MIBData == null)
209 209
 		{
210
-		    $dbConn = $this->getUIDatabase()->getDbConn();
210
+		    $dbConn=$this->getUIDatabase()->getDbConn();
211 211
 		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
212 212
 			$this->MIBData=new MIBLoader(
213 213
 				$this->Config()->get('config', 'snmptranslate'),
@@ -227,10 +227,10 @@  discard block
 block discarded – undo
227 227
 	protected function isDirectorInstalled()
228 228
 	{
229 229
 	    $output=array();
230
-	    exec('icingacli module list',$output);
230
+	    exec('icingacli module list', $output);
231 231
 	    foreach ($output as $line)
232 232
 		{
233
-			if (preg_match('/^director .*enabled/',$line))
233
+			if (preg_match('/^director .*enabled/', $line))
234 234
 			{
235 235
 				return true;
236 236
 			}
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 
253 253
 	public function setitemListDisplay(int $maxRows)
254 254
 	{
255
-	    return $this->getUIDatabase()->setDBConfigValue('max_rows_in_list',$maxRows);
255
+	    return $this->getUIDatabase()->setDBConfigValue('max_rows_in_list', $maxRows);
256 256
 	}
257 257
 	
258 258
     /**
@@ -262,13 +262,13 @@  discard block
 block discarded – undo
262 262
 	public function getHandlersCategory()
263 263
 	{
264 264
 	    //<index>:<name>!<index>:<name>
265
-	    $catList = $this->getUIDatabase()->getDBConfigValue('handler_categories');
266
-	    $catListArray=explode('!',$catList);
265
+	    $catList=$this->getUIDatabase()->getDBConfigValue('handler_categories');
266
+	    $catListArray=explode('!', $catList);
267 267
 	    $retArray=array();
268 268
 	    foreach ($catListArray as $category)
269 269
 	    {
270
-	        $catArray=explode(':',$category);
271
-	        $retArray[$catArray[0]] = $catArray[1];
270
+	        $catArray=explode(':', $category);
271
+	        $retArray[$catArray[0]]=$catArray[1];
272 272
 	    }
273 273
 	    return $retArray; 
274 274
 	}
@@ -278,25 +278,25 @@  discard block
 block discarded – undo
278 278
 	    $catString='';
279 279
 	    foreach ($catArray as $index => $value)
280 280
 	    {
281
-	        if ($catString != '' ) $catString .= '!';
282
-	        $catString .= $index . ':' . $value;
281
+	        if ($catString != '') $catString.='!';
282
+	        $catString.=$index.':'.$value;
283 283
 	    }
284 284
 	    $this->getUIDatabase()->setDBConfigValue('handler_categories', $catString);
285 285
 	}
286 286
 	
287 287
 	public function addHandlersCategory(string $catName)
288 288
 	{
289
-	    $catArray = $this->getHandlersCategory();
289
+	    $catArray=$this->getHandlersCategory();
290 290
 	    $i=1;
291 291
 	    while (isset($catArray[$i]) && $i < 100) $i++;
292 292
 	    if ($i == 100) throw new ProgrammingError('Category array error');
293
-	    $catArray[$i] = $catName;
293
+	    $catArray[$i]=$catName;
294 294
 	    $this->setHandlerCategory($catArray);
295 295
 	}
296 296
 	
297 297
 	public function delHandlersCategory(int $catIndex)
298 298
 	{
299
-	    $catArray = $this->getHandlersCategory();
299
+	    $catArray=$this->getHandlersCategory();
300 300
 	    unset($catArray[$catIndex]);
301 301
 	    $this->setHandlerCategory($catArray);
302 302
 	    $this->getUIDatabase()->updateHandlersOnCategoryDelete($catIndex);
@@ -304,8 +304,8 @@  discard block
 block discarded – undo
304 304
 	
305 305
 	public function renameHandlersCategory(int $catIndex, string $catName)
306 306
 	{
307
-	    $catArray = $this->getHandlersCategory();
308
-	    $catArray[$catIndex] = $catName;
307
+	    $catArray=$this->getHandlersCategory();
308
+	    $catArray[$catIndex]=$catName;
309 309
 	    $this->setHandlerCategory($catArray);
310 310
 	}
311 311
 	
Please login to merge, or discard this patch.
application/controllers/SettingsController.php 2 patches
Indentation   +231 added lines, -231 removed lines patch added patch discarded remove patch
@@ -25,16 +25,16 @@  discard block
 block discarded – undo
25 25
    */
26 26
   private function get_param()
27 27
   {
28
-      $dberrorMsg=$this->params->get('dberror');
29
-      if ($dberrorMsg != '')
30
-      {
31
-          $this->view->errorDetected=$dberrorMsg;
32
-      }
33
-      $dberrorMsg=$this->params->get('idodberror');
34
-      if ($dberrorMsg != '')
35
-      {
36
-          $this->view->errorDetected=$dberrorMsg;
37
-      }
28
+	  $dberrorMsg=$this->params->get('dberror');
29
+	  if ($dberrorMsg != '')
30
+	  {
31
+		  $this->view->errorDetected=$dberrorMsg;
32
+	  }
33
+	  $dberrorMsg=$this->params->get('idodberror');
34
+	  if ($dberrorMsg != '')
35
+	  {
36
+		  $this->view->errorDetected=$dberrorMsg;
37
+	  }
38 38
   }
39 39
   
40 40
   /**
@@ -43,22 +43,22 @@  discard block
 block discarded – undo
43 43
    */
44 44
   private function check_empty_config()
45 45
   {
46
-      $this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
47
-      if ($this->Config()->isEmpty() == true)
48
-      {
49
-          $this->Config()->setSection('config'); // Set base config section.
50
-          try
51
-          {
52
-              $this->Config()->saveIni();
53
-              $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54
-              //$emptyConfig=1;
55
-          }
56
-          catch (Exception $e)
57
-          {
58
-              $this->view->configErrorDetected=$e->getMessage();
59
-          }
46
+	  $this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
47
+	  if ($this->Config()->isEmpty() == true)
48
+	  {
49
+		  $this->Config()->setSection('config'); // Set base config section.
50
+		  try
51
+		  {
52
+			  $this->Config()->saveIni();
53
+			  $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54
+			  //$emptyConfig=1;
55
+		  }
56
+		  catch (Exception $e)
57
+		  {
58
+			  $this->view->configErrorDetected=$e->getMessage();
59
+		  }
60 60
           
61
-      }
61
+	  }
62 62
   }
63 63
   
64 64
   /**
@@ -71,56 +71,56 @@  discard block
 block discarded – undo
71 71
    */
72 72
   private function check_db()
73 73
   {
74
-      $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
-          0	=>	array('Database configuration OK','',''),
76
-          1	=>	array('Database set in config.ini','No database in config.ini',''),
77
-          2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
78
-              Url::fromPath('config/resource')),
79
-          3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
80
-              Url::fromPath('trapdirector/settings/createschema')),
81
-          4	=>	array('Schema is set','Schema is not set for ',
82
-              Url::fromPath('trapdirector/settings/createschema')),
83
-          5	=>	array('Schema is up to date','Schema is outdated :',
84
-              Url::fromPath('trapdirector/settings/updateschema')),
85
-      );
74
+	  $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
+		  0	=>	array('Database configuration OK','',''),
76
+		  1	=>	array('Database set in config.ini','No database in config.ini',''),
77
+		  2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
78
+			  Url::fromPath('config/resource')),
79
+		  3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
80
+			  Url::fromPath('trapdirector/settings/createschema')),
81
+		  4	=>	array('Schema is set','Schema is not set for ',
82
+			  Url::fromPath('trapdirector/settings/createschema')),
83
+		  5	=>	array('Schema is up to date','Schema is outdated :',
84
+			  Url::fromPath('trapdirector/settings/updateschema')),
85
+	  );
86 86
       
87
-      try {
88
-          $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
-          $dberror=array(0,'');
90
-      } catch (DBException $e) {
91
-          $dberror = $e->getArray();
92
-      }
87
+	  try {
88
+		  $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
+		  $dberror=array(0,'');
90
+	  } catch (DBException $e) {
91
+		  $dberror = $e->getArray();
92
+	  }
93 93
       
94
-      $this->view->db_error=$dberror[0];
95
-      switch ($dberror[0])
96
-      {
97
-          case 2:
98
-          case 4:
99
-              $db_message[$dberror[0]][1] .= $dberror[1];
100
-              break;
101
-          case 3:
102
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
103
-              break;
104
-          case 5:
105
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
106
-              break;
107
-          case 0:
108
-          case 1:
109
-              break;
110
-          default:
111
-              new ProgrammingError('Out of bond result from database test');
112
-      }
113
-      $this->view->message=$db_message;
94
+	  $this->view->db_error=$dberror[0];
95
+	  switch ($dberror[0])
96
+	  {
97
+		  case 2:
98
+		  case 4:
99
+			  $db_message[$dberror[0]][1] .= $dberror[1];
100
+			  break;
101
+		  case 3:
102
+			  $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
103
+			  break;
104
+		  case 5:
105
+			  $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
106
+			  break;
107
+		  case 0:
108
+		  case 1:
109
+			  break;
110
+		  default:
111
+			  new ProgrammingError('Out of bond result from database test');
112
+	  }
113
+	  $this->view->message=$db_message;
114 114
       
115
-      try {
116
-          $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
-          $dberror=array(0,'');
118
-      } catch (DBException $e) {
119
-          $dberror = $e->getArray();
120
-      }
115
+	  try {
116
+		  $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
+		  $dberror=array(0,'');
118
+	  } catch (DBException $e) {
119
+		  $dberror = $e->getArray();
120
+	  }
121 121
       
122
-      $this->view->ido_db_error=$dberror[0];
123
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
122
+	  $this->view->ido_db_error=$dberror[0];
123
+	  $this->view->ido_message='IDO Database : ' . $dberror[1];
124 124
   }
125 125
   
126 126
   /**
@@ -130,23 +130,23 @@  discard block
 block discarded – undo
130 130
    */
131 131
   private function check_api()
132 132
   {
133
-      if ($this->Config()->get('config', 'icingaAPI_host') != '')
134
-      {
135
-          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
136
-          $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
137
-          try {
138
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
139
-              //$this->view->apimessageError=false;
140
-          } catch (RuntimeException $e) {
141
-              $this->view->apimessage='API config : ' . $e->getMessage();
142
-              $this->view->apimessageError=true;
143
-          }
144
-      }
145
-      else
146
-      {
147
-          $this->view->apimessage='API parameters not configured';
148
-          $this->view->apimessageError=true;
149
-      }
133
+	  if ($this->Config()->get('config', 'icingaAPI_host') != '')
134
+	  {
135
+		  $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
136
+		  $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
137
+		  try {
138
+			  list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
139
+			  //$this->view->apimessageError=false;
140
+		  } catch (RuntimeException $e) {
141
+			  $this->view->apimessage='API config : ' . $e->getMessage();
142
+			  $this->view->apimessageError=true;
143
+		  }
144
+	  }
145
+	  else
146
+	  {
147
+		  $this->view->apimessage='API parameters not configured';
148
+		  $this->view->apimessageError=true;
149
+	  }
150 150
   }
151 151
 
152 152
   /**
@@ -157,21 +157,21 @@  discard block
 block discarded – undo
157 157
    */
158 158
   private function check_icingaweb_path()
159 159
   {
160
-      $this->view->icingaEtcWarn=0;
161
-      $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
162
-      if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
163
-      {
164
-          $output=array();
160
+	  $this->view->icingaEtcWarn=0;
161
+	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
162
+	  if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
163
+	  {
164
+		  $output=array();
165 165
           
166
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
166
+		  exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
167 167
           
168 168
           
169
-          if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
170
-          {
171
-              $this->view->icingaEtcWarn=1;
172
-              $this->view->icingaweb2_etc=$icingaweb2_etc;
173
-          }
174
-      }
169
+		  if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
170
+		  {
171
+			  $this->view->icingaEtcWarn=1;
172
+			  $this->view->icingaweb2_etc=$icingaweb2_etc;
173
+		  }
174
+	  }
175 175
       
176 176
   }
177 177
   
@@ -182,15 +182,15 @@  discard block
 block discarded – undo
182 182
    */
183 183
   private function get_db_list($allowed)
184 184
   {
185
-      $resources = array();
186
-      foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
187
-      {
188
-          if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
189
-          {
190
-              $resources[$name] = $name;
191
-          }
192
-      }
193
-      return $resources;
185
+	  $resources = array();
186
+	  foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
187
+	  {
188
+		  if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
189
+		  {
190
+			  $resources[$name] = $name;
191
+		  }
192
+	  }
193
+	  return $resources;
194 194
   }
195 195
   
196 196
   /**
@@ -199,23 +199,23 @@  discard block
 block discarded – undo
199 199
    */
200 200
   private function get_php_binary()
201 201
   {
202
-      $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
202
+	  $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
203 203
 
204
-      foreach ($phpBinary as $phpBin )
205
-      {
206
-          $output=array();
207
-          $retCode=255;
208
-          $input="154865134987aaaa";
209
-          exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
204
+	  foreach ($phpBinary as $phpBin )
205
+	  {
206
+		  $output=array();
207
+		  $retCode=255;
208
+		  $input="154865134987aaaa";
209
+		  exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
210 210
           
211
-          if (! isset($output[0])) $output[0]="NO OUT";
211
+		  if (! isset($output[0])) $output[0]="NO OUT";
212 212
           
213
-          if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
214
-          {
215
-              return $phpBin;
216
-          }          
217
-      }
218
-      return NULL;
213
+		  if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
214
+		  {
215
+			  return $phpBin;
216
+		  }          
217
+	  }
218
+	  return NULL;
219 219
   }
220 220
   
221 221
   /**
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
   public function indexAction()
235 235
   {
236 236
       
237
-    // CHeck permissions : display tests in any case, but no configuration.
237
+	// CHeck permissions : display tests in any case, but no configuration.
238 238
 	$this->view->configPermission=$this->checkModuleConfigPermission(1);
239 239
 	// But check read permission
240 240
 	$this->checkReadPermission();
@@ -242,16 +242,16 @@  discard block
 block discarded – undo
242 242
 	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');	
243 243
 	
244 244
 	// Get message : sent on configuration problems detected by controllers
245
-    $this->get_param();
245
+	$this->get_param();
246 246
     
247
-    // Test if configuration exists, if not create for installer script
247
+	// Test if configuration exists, if not create for installer script
248 248
 	$this->check_empty_config();
249 249
 
250 250
 	// Test Database
251
-    $this->check_db();
251
+	$this->check_db();
252 252
 	
253 253
 	//********* Test API
254
-    $this->check_api();
254
+	$this->check_api();
255 255
 	
256 256
 	//*********** Test snmptrapd alive and options
257 257
 	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
 	$phpBinary = $this->get_php_binary();
266 266
 	if ($phpBinary === null)
267 267
 	{
268
-	    $phpBinary = ' PHP BINARY NOT FOUND ';
268
+		$phpBinary = ' PHP BINARY NOT FOUND ';
269 269
 	    
270 270
 	}
271 271
 	
@@ -273,11 +273,11 @@  discard block
 block discarded – undo
273 273
 	$this->view->traps_in_config= $phpBinary . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
274 274
 	
275 275
 	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
276
-	    . ' -c all ' 
277
-	    . ' -d ' . $this->Module()->getBaseDir()
278
-	    . ' -p ' . $phpBinary
279
-	    . ' -a ' . exec('whoami')
280
-	    . ' -w ' . Icinga::app()->getConfigDir();
276
+		. ' -c all ' 
277
+		. ' -d ' . $this->Module()->getBaseDir()
278
+		. ' -p ' . $phpBinary
279
+		. ' -a ' . exec('whoami')
280
+		. ' -w ' . Icinga::app()->getConfigDir();
281 281
 	        
282 282
 	// ******************* configuration form setup*******************
283 283
 	$this->view->form = $form = new TrapsConfigForm();
@@ -311,15 +311,15 @@  discard block
 block discarded – undo
311 311
   public function satelliteAction()
312 312
   {
313 313
       
314
-      // CHeck permissions
315
-      $this->view->configPermission=$this->checkModuleConfigPermission();
314
+	  // CHeck permissions
315
+	  $this->view->configPermission=$this->checkModuleConfigPermission();
316 316
       
317
-      // Setup tabs
318
-      $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
317
+	  // Setup tabs
318
+	  $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
319 319
       
320
-      $this->view->masterHASet = FALSE;
320
+	  $this->view->masterHASet = FALSE;
321 321
       
322
-      $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
322
+	  $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
323 323
   }
324 324
   
325 325
   
@@ -335,8 +335,8 @@  discard block
 block discarded – undo
335 335
 	
336 336
 	try 
337 337
 	{
338
-	    $this->getUIDatabase()->testGetDb(); // Get DB in test mode
339
-	    printf('Schema already exists');
338
+		$this->getUIDatabase()->testGetDb(); // Get DB in test mode
339
+		printf('Schema already exists');
340 340
 	    
341 341
 	} 
342 342
 	catch (DBException $e) 
@@ -347,19 +347,19 @@  discard block
 block discarded – undo
347 347
 		// Get module database name
348 348
 		$dbName=$this->Config()->get('config', 'database');
349 349
 
350
-        $dbResource = ResourceFactory::getResourceConfig($dbName);
351
-        $dbType=$dbResource->get('db');
352
-        switch ($dbType) {
353
-          case 'mysql':
354
-              $dbFileExt='sql';
355
-              break;
356
-          case 'pgsql':
357
-              $dbFileExt='pgsql';
358
-              break;
359
-          default:
360
-              printf("Database configuration error : Unsuported DB");
361
-              return;
362
-        } 
350
+		$dbResource = ResourceFactory::getResourceConfig($dbName);
351
+		$dbType=$dbResource->get('db');
352
+		switch ($dbType) {
353
+		  case 'mysql':
354
+			  $dbFileExt='sql';
355
+			  break;
356
+		  case 'pgsql':
357
+			  $dbFileExt='pgsql';
358
+			  break;
359
+		  default:
360
+			  printf("Database configuration error : Unsuported DB");
361
+			  return;
362
+		} 
363 363
 
364 364
 		printf('<pre>');
365 365
 		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
@@ -383,32 +383,32 @@  discard block
 block discarded – undo
383 383
   public function updateschemaAction()
384 384
   {
385 385
 	  $this->checkModuleConfigPermission();
386
-      $this->getTabs()->add('get',array(
387
-    		'active'	=> true,
388
-    		'label'		=> $this->translate('Update Schema'),
389
-    		'url'		=> Url::fromRequest()
390
-    	));
386
+	  $this->getTabs()->add('get',array(
387
+			'active'	=> true,
388
+			'label'		=> $this->translate('Update Schema'),
389
+			'url'		=> Url::fromRequest()
390
+		));
391 391
 	  // check if needed
392 392
 	  $dberror=array();
393
-      try
394
-      {
395
-          $this->getUIDatabase()->testGetDb(); // Get DB in test mode
396
-          echo 'Schema already exists and is up to date<br>';
397
-          return;
398
-      }
399
-      catch (DBException $e)
400
-      {
401
-          $dberror=$e->getArray(); 
402
-      }
393
+	  try
394
+	  {
395
+		  $this->getUIDatabase()->testGetDb(); // Get DB in test mode
396
+		  echo 'Schema already exists and is up to date<br>';
397
+		  return;
398
+	  }
399
+	  catch (DBException $e)
400
+	  {
401
+		  $dberror=$e->getArray(); 
402
+	  }
403 403
 	  
404 404
 	  echo 'Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a><br><br>';
405 405
 	  
406 406
 	  if ($dberror[0] != 5)
407 407
 	  {
408
-	      echo 'Database does not exists or is not setup correctly<br>';
409
-	      return;
408
+		  echo 'Database does not exists or is not setup correctly<br>';
409
+		  return;
410 410
 	  }
411
-      // setup
411
+	  // setup
412 412
 	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
413 413
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
414 414
 	  $debug_level=4;
@@ -421,20 +421,20 @@  discard block
 block discarded – undo
421 421
 	  $target_version=$dberror[2];
422 422
 	  
423 423
 	  if ($this->params->get('msgok') == null) {
424
-	      // Check for messages and display if any
425
-              echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
426
-	      $Trap->setLogging(2,'syslog');
427
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
428
-	      if ($message != '')
429
-	      {
430
-	          echo 'Note :<br><pre>';
431
-	          echo $message;
432
-	          echo '</pre>';
433
-	          echo '<br>';
434
-	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
435
-	          echo '<br>';
436
-	          return;
437
-	      }
424
+		  // Check for messages and display if any
425
+			  echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
426
+		  $Trap->setLogging(2,'syslog');
427
+		  $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
428
+		  if ($message != '')
429
+		  {
430
+			  echo 'Note :<br><pre>';
431
+			  echo $message;
432
+			  echo '</pre>';
433
+			  echo '<br>';
434
+			  echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
435
+			  echo '<br>';
436
+			  return;
437
+		  }
438 438
 	  }
439 439
 	  
440 440
 	  $Trap->setLogging($debug_level,'display');
@@ -449,50 +449,50 @@  discard block
 block discarded – undo
449 449
   
450 450
   private function checkSnmpTrapd()
451 451
   {
452
-      $psOutput=array();
453
-      // First check is someone is listening to port 162. As not root, we can't have pid... 
454
-      $sspath = exec('which ss 2>/dev/null');
455
-      if(empty($sspath))
456
-      {
457
-          // RHEL based systems
458
-          $sspath = '/usr/sbin/ss';
459
-      }
460
-      if(!is_executable("$sspath"))
461
-      {
462
-          return array(1,"Can not execute $sspath");
463
-      }
464
-      exec("$sspath -lun | grep ':162 '",$psOutput);
465
-      if (count($psOutput) == 0)
466
-      {
467
-          return array(1,'Port UDP/162 is not open : is snmptrapd running?');
468
-      }
469
-      $psOutput=array();
470
-      $selinux_state = '';
471
-      if(is_executable('/usr/sbin/getenforce'))
472
-      {
473
-          $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
474
-      }
475
-      if($selinux_state !== 'Enforcing')
476
-      {
477
-          exec('ps --no-headers -o command -C snmptrapd',$psOutput);
478
-          if (count($psOutput) == 0)
479
-          {
480
-              return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
481
-          }
482
-          // Assume there is only one line... TODO : see if there is a better way to do this
483
-          $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
484
-          if (!preg_match('/-n/',$line))
485
-              return array(1,'snmptrapd has no -n option : '.$line);
486
-          if (!preg_match('/-O[^ ]*n/',$line))
487
-              return array(1,'snmptrapd has no -On option : '.$line);
488
-          if (!preg_match('/-O[^ ]*e/',$line))
489
-              return array(1,'snmptrapd has no -Oe option : '.$line);
452
+	  $psOutput=array();
453
+	  // First check is someone is listening to port 162. As not root, we can't have pid... 
454
+	  $sspath = exec('which ss 2>/dev/null');
455
+	  if(empty($sspath))
456
+	  {
457
+		  // RHEL based systems
458
+		  $sspath = '/usr/sbin/ss';
459
+	  }
460
+	  if(!is_executable("$sspath"))
461
+	  {
462
+		  return array(1,"Can not execute $sspath");
463
+	  }
464
+	  exec("$sspath -lun | grep ':162 '",$psOutput);
465
+	  if (count($psOutput) == 0)
466
+	  {
467
+		  return array(1,'Port UDP/162 is not open : is snmptrapd running?');
468
+	  }
469
+	  $psOutput=array();
470
+	  $selinux_state = '';
471
+	  if(is_executable('/usr/sbin/getenforce'))
472
+	  {
473
+		  $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
474
+	  }
475
+	  if($selinux_state !== 'Enforcing')
476
+	  {
477
+		  exec('ps --no-headers -o command -C snmptrapd',$psOutput);
478
+		  if (count($psOutput) == 0)
479
+		  {
480
+			  return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
481
+		  }
482
+		  // Assume there is only one line... TODO : see if there is a better way to do this
483
+		  $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
484
+		  if (!preg_match('/-n/',$line))
485
+			  return array(1,'snmptrapd has no -n option : '.$line);
486
+		  if (!preg_match('/-O[^ ]*n/',$line))
487
+			  return array(1,'snmptrapd has no -On option : '.$line);
488
+		  if (!preg_match('/-O[^ ]*e/',$line))
489
+			  return array(1,'snmptrapd has no -Oe option : '.$line);
490 490
 
491
-          return array(0,'snmptrapd listening to UDP/162, options : '.$line);
492
-      }
493
-      else
494
-      {
495
-          return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
496
-      }
491
+		  return array(0,'snmptrapd listening to UDP/162, options : '.$line);
492
+	  }
493
+	  else
494
+	  {
495
+		  return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
496
+	  }
497 497
   }
498 498
 }
Please login to merge, or discard this patch.
Spacing   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -72,23 +72,23 @@  discard block
 block discarded – undo
72 72
   private function check_db()
73 73
   {
74 74
       $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
-          0	=>	array('Database configuration OK','',''),
76
-          1	=>	array('Database set in config.ini','No database in config.ini',''),
77
-          2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
75
+          0	=>	array('Database configuration OK', '', ''),
76
+          1	=>	array('Database set in config.ini', 'No database in config.ini', ''),
77
+          2	=>	array('Database exists in Icingaweb2 config', 'Database does not exist in Icingaweb2 : ',
78 78
               Url::fromPath('config/resource')),
79
-          3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
79
+          3	=>	array('Database credentials OK', 'Database does not exist/invalid credentials/no schema : ',
80 80
               Url::fromPath('trapdirector/settings/createschema')),
81
-          4	=>	array('Schema is set','Schema is not set for ',
81
+          4	=>	array('Schema is set', 'Schema is not set for ',
82 82
               Url::fromPath('trapdirector/settings/createschema')),
83
-          5	=>	array('Schema is up to date','Schema is outdated :',
83
+          5	=>	array('Schema is up to date', 'Schema is outdated :',
84 84
               Url::fromPath('trapdirector/settings/updateschema')),
85 85
       );
86 86
       
87 87
       try {
88 88
           $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
-          $dberror=array(0,'');
89
+          $dberror=array(0, '');
90 90
       } catch (DBException $e) {
91
-          $dberror = $e->getArray();
91
+          $dberror=$e->getArray();
92 92
       }
93 93
       
94 94
       $this->view->db_error=$dberror[0];
@@ -96,13 +96,13 @@  discard block
 block discarded – undo
96 96
       {
97 97
           case 2:
98 98
           case 4:
99
-              $db_message[$dberror[0]][1] .= $dberror[1];
99
+              $db_message[$dberror[0]][1].=$dberror[1];
100 100
               break;
101 101
           case 3:
102
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
102
+              $db_message[$dberror[0]][1].=$dberror[1].', Message : '.$dberror[2];
103 103
               break;
104 104
           case 5:
105
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
105
+              $db_message[$dberror[0]][1].=' version '.$dberror[1].', version needed : '.$dberror[2];
106 106
               break;
107 107
           case 0:
108 108
           case 1:
@@ -114,13 +114,13 @@  discard block
 block discarded – undo
114 114
       
115 115
       try {
116 116
           $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
-          $dberror=array(0,'');
117
+          $dberror=array(0, '');
118 118
       } catch (DBException $e) {
119
-          $dberror = $e->getArray();
119
+          $dberror=$e->getArray();
120 120
       }
121 121
       
122 122
       $this->view->ido_db_error=$dberror[0];
123
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
123
+      $this->view->ido_message='IDO Database : '.$dberror[1];
124 124
   }
125 125
   
126 126
   /**
@@ -132,13 +132,13 @@  discard block
 block discarded – undo
132 132
   {
133 133
       if ($this->Config()->get('config', 'icingaAPI_host') != '')
134 134
       {
135
-          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
135
+          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'), $this->Config()->get('config', 'icingaAPI_port'));
136 136
           $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
137 137
           try {
138
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
138
+              list($this->view->apimessageError, $this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
139 139
               //$this->view->apimessageError=false;
140 140
           } catch (RuntimeException $e) {
141
-              $this->view->apimessage='API config : ' . $e->getMessage();
141
+              $this->view->apimessage='API config : '.$e->getMessage();
142 142
               $this->view->apimessageError=true;
143 143
           }
144 144
       }
@@ -163,10 +163,10 @@  discard block
 block discarded – undo
163 163
       {
164 164
           $output=array();
165 165
           
166
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
166
+          exec('cat '.$this->module->getBaseDir().'/bin/trap_in.php | grep "\$icingaweb2Etc=" ', $output);
167 167
           
168 168
           
169
-          if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
169
+          if (!isset($output[0]) || !preg_match('#"'.$icingaweb2_etc.'"#', $output[0]))
170 170
           {
171 171
               $this->view->icingaEtcWarn=1;
172 172
               $this->view->icingaweb2_etc=$icingaweb2_etc;
@@ -182,12 +182,12 @@  discard block
 block discarded – undo
182 182
    */
183 183
   private function get_db_list($allowed)
184 184
   {
185
-      $resources = array();
185
+      $resources=array();
186 186
       foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
187 187
       {
188 188
           if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
189 189
           {
190
-              $resources[$name] = $name;
190
+              $resources[$name]=$name;
191 191
           }
192 192
       }
193 193
       return $resources;
@@ -199,18 +199,18 @@  discard block
 block discarded – undo
199 199
    */
200 200
   private function get_php_binary()
201 201
   {
202
-      $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
202
+      $phpBinary=array(PHP_BINARY, PHP_BINDIR."/php", '/usr/bin/php');
203 203
 
204
-      foreach ($phpBinary as $phpBin )
204
+      foreach ($phpBinary as $phpBin)
205 205
       {
206 206
           $output=array();
207 207
           $retCode=255;
208 208
           $input="154865134987aaaa";
209
-          exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
209
+          exec("$phpBin -r \"echo '$input';\"", $output, $retCode);
210 210
           
211
-          if (! isset($output[0])) $output[0]="NO OUT";
211
+          if (!isset($output[0])) $output[0]="NO OUT";
212 212
           
213
-          if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
213
+          if ($retCode == 0 && preg_match("/$input/", $output[0]) == 1)
214 214
           {
215 215
               return $phpBin;
216 216
           }          
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 	// But check read permission
240 240
 	$this->checkReadPermission();
241 241
 	
242
-	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');	
242
+	$this->view->tabs=$this->Module()->getConfigTabs()->activate('config');	
243 243
 	
244 244
 	// Get message : sent on configuration problems detected by controllers
245 245
     $this->get_param();
@@ -254,39 +254,39 @@  discard block
 block discarded – undo
254 254
     $this->check_api();
255 255
 	
256 256
 	//*********** Test snmptrapd alive and options
257
-	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
257
+	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage)=$this->checkSnmpTrapd();
258 258
 
259 259
 	// List DB in $ressources
260
-	$resources = $this->get_db_list(array('mysql', 'pgsql')); 
260
+	$resources=$this->get_db_list(array('mysql', 'pgsql')); 
261 261
 
262 262
 	// Check standard Icingaweb2 path
263 263
 	$this->check_icingaweb_path();
264 264
 
265
-	$phpBinary = $this->get_php_binary();
265
+	$phpBinary=$this->get_php_binary();
266 266
 	if ($phpBinary === null)
267 267
 	{
268
-	    $phpBinary = ' PHP BINARY NOT FOUND ';
268
+	    $phpBinary=' PHP BINARY NOT FOUND ';
269 269
 	    
270 270
 	}
271 271
 	
272 272
 	// Setup path for mini documentation
273
-	$this->view->traps_in_config= $phpBinary . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
273
+	$this->view->traps_in_config=$phpBinary.' '.$this->Module()->getBaseDir().'/bin/trap_in.php';
274 274
 	
275
-	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
275
+	$this->view->installer=$this->Module()->getBaseDir().'/bin/installer.sh '
276 276
 	    . ' -c all ' 
277
-	    . ' -d ' . $this->Module()->getBaseDir()
278
-	    . ' -p ' . $phpBinary
279
-	    . ' -a ' . exec('whoami')
280
-	    . ' -w ' . Icinga::app()->getConfigDir();
277
+	    . ' -d '.$this->Module()->getBaseDir()
278
+	    . ' -p '.$phpBinary
279
+	    . ' -a '.exec('whoami')
280
+	    . ' -w '.Icinga::app()->getConfigDir();
281 281
 	        
282 282
 	// ******************* configuration form setup*******************
283
-	$this->view->form = $form = new TrapsConfigForm();
283
+	$this->view->form=$form=new TrapsConfigForm();
284 284
 	
285 285
 	// set default paths;
286
-	$this->view->form->setPaths($this->Module()->getBaseDir(),Icinga::app()->getConfigDir());
286
+	$this->view->form->setPaths($this->Module()->getBaseDir(), Icinga::app()->getConfigDir());
287 287
 	
288 288
 	// set default ido database
289
-	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring','backends')->get('icinga','resource'));
289
+	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring', 'backends')->get('icinga', 'resource'));
290 290
 	
291 291
 	// Make form handle request.
292 292
 	$form->setIniConfig($this->Config())
@@ -315,18 +315,18 @@  discard block
 block discarded – undo
315 315
       $this->view->configPermission=$this->checkModuleConfigPermission();
316 316
       
317 317
       // Setup tabs
318
-      $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
318
+      $this->view->tabs=$this->Module()->getConfigTabs()->activate('satellite');	
319 319
       
320
-      $this->view->masterHASet = FALSE;
320
+      $this->view->masterHASet=FALSE;
321 321
       
322
-      $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
322
+      $this->view->masterHAConf=array('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
323 323
   }
324 324
   
325 325
   
326 326
   public function createschemaAction()
327 327
   {
328 328
 	$this->checkModuleConfigPermission();
329
-	$this->getTabs()->add('create_schema',array(
329
+	$this->getTabs()->add('create_schema', array(
330 330
 		'active'	=> true,
331 331
 		'label'		=> $this->translate('Create Schema'),
332 332
 		'url'		=> Url::fromRequest()
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
 		// Get module database name
348 348
 		$dbName=$this->Config()->get('config', 'database');
349 349
 
350
-        $dbResource = ResourceFactory::getResourceConfig($dbName);
350
+        $dbResource=ResourceFactory::getResourceConfig($dbName);
351 351
         $dbType=$dbResource->get('db');
352 352
         switch ($dbType) {
353 353
           case 'mysql':
@@ -362,28 +362,28 @@  discard block
 block discarded – undo
362 362
         } 
363 363
 
364 364
 		printf('<pre>');
365
-		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
365
+		require_once $this->Module()->getBaseDir().'/bin/trap_class.php';
366 366
 		
367 367
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
368 368
 		$debug_level=4;
369
-		$Trap = new Trap($icingaweb2_etc);
370
-		$Trap->setLogging($debug_level,'display');
369
+		$Trap=new Trap($icingaweb2_etc);
370
+		$Trap->setLogging($debug_level, 'display');
371 371
 		
372 372
 		$prefix=$this->Config()->get('config', 'database_prefix');
373 373
 		// schema file : <path>/SQL/schema_v<verion>.<dbtype>
374
-		$schema=$this->Module()->getBaseDir() . 
375
-		'/SQL/schema_v'. $this->getModuleConfig()->getDbCurVersion() . '.' . $dbFileExt;
374
+		$schema=$this->Module()->getBaseDir(). 
375
+		'/SQL/schema_v'.$this->getModuleConfig()->getDbCurVersion().'.'.$dbFileExt;
376 376
 		
377
-		$Trap->trapsDB->create_schema($schema,$prefix);
377
+		$Trap->trapsDB->create_schema($schema, $prefix);
378 378
 		echo '</pre>';
379 379
 	}
380
-	echo '<br><br>Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a>';
380
+	echo '<br><br>Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a>';
381 381
   }
382 382
 
383 383
   public function updateschemaAction()
384 384
   {
385 385
 	  $this->checkModuleConfigPermission();
386
-      $this->getTabs()->add('get',array(
386
+      $this->getTabs()->add('get', array(
387 387
     		'active'	=> true,
388 388
     		'label'		=> $this->translate('Update Schema'),
389 389
     		'url'		=> Url::fromRequest()
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
           $dberror=$e->getArray(); 
402 402
       }
403 403
 	  
404
-	  echo 'Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a><br><br>';
404
+	  echo 'Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a><br><br>';
405 405
 	  
406 406
 	  if ($dberror[0] != 5)
407 407
 	  {
@@ -409,40 +409,40 @@  discard block
 block discarded – undo
409 409
 	      return;
410 410
 	  }
411 411
       // setup
412
-	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
412
+	  require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
413 413
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
414 414
 	  $debug_level=4;
415
-	  $Trap = new Trap($icingaweb2_etc);
415
+	  $Trap=new Trap($icingaweb2_etc);
416 416
 	  
417 417
 	  
418 418
 	  $prefix=$this->Config()->get('config', 'database_prefix');
419
-	  $updateSchema=$this->Module()->getBaseDir() . '/SQL/';
419
+	  $updateSchema=$this->Module()->getBaseDir().'/SQL/';
420 420
 	  
421 421
 	  $target_version=$dberror[2];
422 422
 	  
423 423
 	  if ($this->params->get('msgok') == null) {
424 424
 	      // Check for messages and display if any
425 425
               echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
426
-	      $Trap->setLogging(2,'syslog');
427
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
426
+	      $Trap->setLogging(2, 'syslog');
427
+	      $message=$Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix, true);
428 428
 	      if ($message != '')
429 429
 	      {
430 430
 	          echo 'Note :<br><pre>';
431 431
 	          echo $message;
432 432
 	          echo '</pre>';
433 433
 	          echo '<br>';
434
-	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
434
+	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="'.Url::fromPath('trapdirector/settings/updateschema').'?msgok=1">Click here to update</a>';
435 435
 	          echo '<br>';
436 436
 	          return;
437 437
 	      }
438 438
 	  }
439 439
 	  
440
-	  $Trap->setLogging($debug_level,'display');
440
+	  $Trap->setLogging($debug_level, 'display');
441 441
 	  
442
-	  echo 'Updating schema to '. $target_version . ': <br>';
442
+	  echo 'Updating schema to '.$target_version.': <br>';
443 443
 	  echo '<pre>';
444 444
 	  	  
445
-	  $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix);
445
+	  $Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix);
446 446
 	  echo '</pre>';
447 447
   }  
448 448
 
@@ -451,48 +451,48 @@  discard block
 block discarded – undo
451 451
   {
452 452
       $psOutput=array();
453 453
       // First check is someone is listening to port 162. As not root, we can't have pid... 
454
-      $sspath = exec('which ss 2>/dev/null');
455
-      if(empty($sspath))
454
+      $sspath=exec('which ss 2>/dev/null');
455
+      if (empty($sspath))
456 456
       {
457 457
           // RHEL based systems
458
-          $sspath = '/usr/sbin/ss';
458
+          $sspath='/usr/sbin/ss';
459 459
       }
460
-      if(!is_executable("$sspath"))
460
+      if (!is_executable("$sspath"))
461 461
       {
462
-          return array(1,"Can not execute $sspath");
462
+          return array(1, "Can not execute $sspath");
463 463
       }
464
-      exec("$sspath -lun | grep ':162 '",$psOutput);
464
+      exec("$sspath -lun | grep ':162 '", $psOutput);
465 465
       if (count($psOutput) == 0)
466 466
       {
467
-          return array(1,'Port UDP/162 is not open : is snmptrapd running?');
467
+          return array(1, 'Port UDP/162 is not open : is snmptrapd running?');
468 468
       }
469 469
       $psOutput=array();
470
-      $selinux_state = '';
471
-      if(is_executable('/usr/sbin/getenforce'))
470
+      $selinux_state='';
471
+      if (is_executable('/usr/sbin/getenforce'))
472 472
       {
473
-          $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
473
+          $selinux_state=exec('/usr/sbin/getenforce 2>/dev/null');
474 474
       }
475
-      if($selinux_state !== 'Enforcing')
475
+      if ($selinux_state !== 'Enforcing')
476 476
       {
477
-          exec('ps --no-headers -o command -C snmptrapd',$psOutput);
477
+          exec('ps --no-headers -o command -C snmptrapd', $psOutput);
478 478
           if (count($psOutput) == 0)
479 479
           {
480
-              return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
480
+              return array(1, "UDP/162 : OK, but no snmptrapd process (?)");
481 481
           }
482 482
           // Assume there is only one line... TODO : see if there is a better way to do this
483
-          $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
484
-          if (!preg_match('/-n/',$line))
485
-              return array(1,'snmptrapd has no -n option : '.$line);
486
-          if (!preg_match('/-O[^ ]*n/',$line))
487
-              return array(1,'snmptrapd has no -On option : '.$line);
488
-          if (!preg_match('/-O[^ ]*e/',$line))
489
-              return array(1,'snmptrapd has no -Oe option : '.$line);
483
+          $line=preg_replace('/^.*snmptrapd /', '', $psOutput[0]);
484
+          if (!preg_match('/-n/', $line))
485
+              return array(1, 'snmptrapd has no -n option : '.$line);
486
+          if (!preg_match('/-O[^ ]*n/', $line))
487
+              return array(1, 'snmptrapd has no -On option : '.$line);
488
+          if (!preg_match('/-O[^ ]*e/', $line))
489
+              return array(1, 'snmptrapd has no -Oe option : '.$line);
490 490
 
491
-          return array(0,'snmptrapd listening to UDP/162, options : '.$line);
491
+          return array(0, 'snmptrapd listening to UDP/162, options : '.$line);
492 492
       }
493 493
       else
494 494
       {
495
-          return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
495
+          return array(0, 'A daemon (hidden by SELinux) is listening on UDP/162');
496 496
       }
497 497
   }
498 498
 }
Please login to merge, or discard this patch.
application/controllers/StatusController.php 2 patches
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -21,8 +21,8 @@  discard block
 block discarded – undo
21 21
 		/************  Trapdb ***********/
22 22
 		try
23 23
 		{
24
-		    $dbConn = $this->getUIDatabase()->getDbConn();
25
-		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
24
+			$dbConn = $this->getUIDatabase()->getDbConn();
25
+			if ($dbConn === null) throw new \ErrorException('uncatched db error');
26 26
 			$query = $dbConn->select()->from(
27 27
 				$this->getModuleConfig()->getTrapTableName(),
28 28
 				array('COUNT(*)')
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 		
52 52
 		try
53 53
 		{		
54
-		    $this->view->currentLogDestination=$this->getUIDatabase()->getDBConfigValue('log_destination');
54
+			$this->view->currentLogDestination=$this->getUIDatabase()->getDBConfigValue('log_destination');
55 55
 			$this->view->logDestinations=$this->getModuleConfig()->getLogDestinations();
56 56
 			$this->view->currentLogFile=$this->getUIDatabase()->getDBConfigValue('log_file');
57 57
 			$this->view->logLevels=$this->getModuleConfig()->getlogLevels();
@@ -65,23 +65,23 @@  discard block
 block discarded – undo
65 65
 		/*************** SNMP configuration ****************/
66 66
 		try
67 67
 		{
68
-		    $this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
69
-		    $this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
-		    $this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
68
+			$this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
69
+			$this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
+			$this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
71 71
 		    
72 72
 		}
73 73
 		catch (Exception $e)
74 74
 		{
75
-		    $this->displayExitError('status',$e->getMessage());
75
+			$this->displayExitError('status',$e->getMessage());
76 76
 		}		
77 77
 		
78 78
 	} 
79 79
   
80 80
 	/** Mib management
81
-	*	Post param : action=update_mib_db : update mib database
82
-	*	Post param : ation=check_update : check if mib update is finished
83
-	*	File post : mibfile -> save mib file
84
-	*/
81
+	 *	Post param : action=update_mib_db : update mib database
82
+	 *	Post param : ation=check_update : check if mib update is finished
83
+	 *	File post : mibfile -> save mib file
84
+	 */
85 85
 	public function mibAction()
86 86
 	{
87 87
 		$this->prepareTabs()->activate('mib');
@@ -100,22 +100,22 @@  discard block
 block discarded – undo
100 100
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
101 101
 					if (preg_match('/OK/',$return))
102 102
 					{
103
-					    $this->_helper->json(array('status'=>'OK'));
103
+						$this->_helper->json(array('status'=>'OK'));
104 104
 					}
105 105
 					// Error
106 106
 					$this->_helper->json(array('status'=>$return));
107 107
 				}
108 108
 				if ($action == 'check_update')
109 109
 				{
110
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
111
-				    if ($file == false)
112
-				    {   // process is dead
113
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
114
-				        return;
115
-				    }
116
-				    $pid=fgets($file);
117
-				    $output=array();
118
-				    $retVal=0;
110
+					$file=@fopen('/tmp/trapdirector_update.pid','r');
111
+					if ($file == false)
112
+					{   // process is dead
113
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
114
+						return;
115
+					}
116
+					$pid=fgets($file);
117
+					$output=array();
118
+					$retVal=0;
119 119
 					exec('ps '.$pid,$output,$retVal);
120 120
 					if ($retVal == 0)
121 121
 					{ // process is alive
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 					}
124 124
 					else
125 125
 					{ // process is dead
126
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
126
+						$this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
127 127
 					}
128 128
 				}
129 129
 				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
@@ -131,32 +131,32 @@  discard block
 block discarded – undo
131 131
 			/** Check for mib file UPLOAD */
132 132
 			if (isset($_FILES['mibfile']))
133 133
 			{
134
-			    $name=filter_var($_FILES['mibfile']['name'],FILTER_SANITIZE_STRING);
134
+				$name=filter_var($_FILES['mibfile']['name'],FILTER_SANITIZE_STRING);
135 135
 				$DirConf=explode(':',$this->Config()->get('config', 'snmptranslate_dirs'));
136 136
 				$destDir=array_shift($DirConf);
137 137
 				if (!is_dir($destDir))
138 138
 				{
139
-				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
139
+					$this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
140 140
 				}
141 141
 				else
142 142
 				{
143
-				    if (!is_writable($destDir))
144
-				    {
145
-				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
146
-				    }
147
-				    else
148
-				    {
149
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150
-				        $sourceTmpNam=filter_var($_FILES['mibfile']['tmp_name'],FILTER_SANITIZE_STRING);
151
-				        if (move_uploaded_file($sourceTmpNam,$destination)===false)
152
-    				    {
153
-    				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154
-    				    }
155
-    				    else
156
-    				    {
157
-    				        $this->view->uploadStatus="File $name uploaded in $destDir";
158
-    				    }
159
-				    }
143
+					if (!is_writable($destDir))
144
+					{
145
+						$this->view->uploadStatus="ERROR : $destDir directory is not writable";
146
+					}
147
+					else
148
+					{
149
+						$destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150
+						$sourceTmpNam=filter_var($_FILES['mibfile']['tmp_name'],FILTER_SANITIZE_STRING);
151
+						if (move_uploaded_file($sourceTmpNam,$destination)===false)
152
+						{
153
+							$this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154
+						}
155
+						else
156
+						{
157
+							$this->view->uploadStatus="File $name uploaded in $destDir";
158
+						}
159
+					}
160 160
 				}
161 161
 
162 162
 			}
@@ -236,63 +236,63 @@  discard block
 block discarded – undo
236 236
 	/** UI options */
237 237
 	public function uimgtAction()
238 238
 	{
239
-	    $this->prepareTabs()->activate('uimgt');
239
+		$this->prepareTabs()->activate('uimgt');
240 240
 	    
241
-	    $this->view->setError='';
242
-	    $this->view->setOKMsg='';
241
+		$this->view->setError='';
242
+		$this->view->setOKMsg='';
243 243
 	    
244
-	    //max_rows=25&row_update=update
245
-	    if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
246
-	    {
247
-	        $maxRows = $this->getRequest()->getParam('max_rows');
248
-	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
249
-	        {
250
-	            $this->view->setError='Max rows must be a number';
251
-	        }
252
-	        else
253
-	        {
254
-	            $this->setitemListDisplay($maxRows);
255
-	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
256
-	        }
257
-	    }
244
+		//max_rows=25&row_update=update
245
+		if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
246
+		{
247
+			$maxRows = $this->getRequest()->getParam('max_rows');
248
+			if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
249
+			{
250
+				$this->view->setError='Max rows must be a number';
251
+			}
252
+			else
253
+			{
254
+				$this->setitemListDisplay($maxRows);
255
+				$this->view->setOKMsg='Set max rows to ' . $maxRows;
256
+			}
257
+		}
258 258
 	    
259
-	    if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
260
-	    {
261
-	        $addCat = $this->getRequest()->getParam('add_category');
262
-            $this->addHandlersCategory($addCat);
263
-	    }
259
+		if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
260
+		{
261
+			$addCat = $this->getRequest()->getParam('add_category');
262
+			$this->addHandlersCategory($addCat);
263
+		}
264 264
 	    
265
-	    if ( $this->getRequest()->getPost('type',NULL) !== NULL )
266
-	    {
267
-	        $type = $this->getRequest()->getPost('type',NULL);
268
-	        $index = $this->getRequest()->getPost('index',NULL);
269
-	        $newname = $this->getRequest()->getPost('newname',NULL);
265
+		if ( $this->getRequest()->getPost('type',NULL) !== NULL )
266
+		{
267
+			$type = $this->getRequest()->getPost('type',NULL);
268
+			$index = $this->getRequest()->getPost('index',NULL);
269
+			$newname = $this->getRequest()->getPost('newname',NULL);
270 270
 
271
-	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
272
-	            $this->_helper->json(array('status'=>'Bad index'));
271
+			if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
272
+				$this->_helper->json(array('status'=>'Bad index'));
273 273
 	        
274
-	        switch ($type)
275
-	        {
276
-	            case 'delete':
277
-	                $this->delHandlersCategory($index);
278
-	                $this->_helper->json(array('status'=>'OK'));
279
-	                return;
280
-	                break;
281
-	            case 'rename':
282
-	                $this->renameHandlersCategory($index, $newname);
283
-	                $this->_helper->json(array('status'=>'OK'));
284
-	                return;
285
-	                break;
286
-	            default:
287
-	                $this->_helper->json(array('status'=>'Unknwon command'));
288
-	                return;
289
-	                break;
290
-	        }
291
-	    }
274
+			switch ($type)
275
+			{
276
+				case 'delete':
277
+					$this->delHandlersCategory($index);
278
+					$this->_helper->json(array('status'=>'OK'));
279
+					return;
280
+					break;
281
+				case 'rename':
282
+					$this->renameHandlersCategory($index, $newname);
283
+					$this->_helper->json(array('status'=>'OK'));
284
+					return;
285
+					break;
286
+				default:
287
+					$this->_helper->json(array('status'=>'Unknwon command'));
288
+					return;
289
+					break;
290
+			}
291
+		}
292 292
 	    
293
-	    $this->view->maxRows = $this->itemListDisplay();
293
+		$this->view->maxRows = $this->itemListDisplay();
294 294
 	    
295
-	    $this->view->categories = $this->getHandlersCategory();
295
+		$this->view->categories = $this->getHandlersCategory();
296 296
 	    
297 297
 	    
298 298
 	    
@@ -341,47 +341,47 @@  discard block
 block discarded – undo
341 341
 	 */
342 342
 	public function pluginsAction()
343 343
 	{
344
-	    $this->prepareTabs()->activate('plugins');
344
+		$this->prepareTabs()->activate('plugins');
345 345
 	    
346
-	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
347
-	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
348
-	    $Trap = new Trap($icingaweb2_etc,4);
346
+		require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
347
+		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
348
+		$Trap = new Trap($icingaweb2_etc,4);
349 349
 	    
350
-	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
350
+		$this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
351 351
 	    
352
-	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
352
+		$enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
353 353
 
354
-	    $pluginList = $Trap->pluginClass->pluginList();
354
+		$pluginList = $Trap->pluginClass->pluginList();
355 355
 	    
356
-	    // Plugin list and fill function name list
357
-	    $functionList=array();
358
-	    $this->view->pluginArray=array();
359
-	    foreach ($pluginList as $plugin)
360
-	    {
361
-	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
362
-	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
363
-	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
364
-	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
365
-	        $pluginDetails->description = htmlentities($pluginDetails->description);
366
-	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
367
-	        array_push($this->view->pluginArray, $pluginDetails);
368
-	        // Get functions for function details
369
-	        foreach ($pluginDetails->funcArray as $function)
370
-	        {
371
-	            array_push($functionList,$function);
372
-	        }
373
-	    }
356
+		// Plugin list and fill function name list
357
+		$functionList=array();
358
+		$this->view->pluginArray=array();
359
+		foreach ($pluginList as $plugin)
360
+		{
361
+			$pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
362
+			$pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
363
+			$pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
364
+			$pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
365
+			$pluginDetails->description = htmlentities($pluginDetails->description);
366
+			$pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
367
+			array_push($this->view->pluginArray, $pluginDetails);
368
+			// Get functions for function details
369
+			foreach ($pluginDetails->funcArray as $function)
370
+			{
371
+				array_push($functionList,$function);
372
+			}
373
+		}
374 374
 	    
375
-	    // Function list with details
376
-	    $this->view->functionList=array();
377
-	    foreach ($functionList as $function)
378
-	    {
379
-	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
380
-	        $functionDetail->params = htmlentities($functionDetail->params);
381
-	        $functionDetail->description = htmlentities($functionDetail->description);
382
-	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
383
-	        array_push($this->view->functionList, $functionDetail);
384
-	    }
375
+		// Function list with details
376
+		$this->view->functionList=array();
377
+		foreach ($functionList as $function)
378
+		{
379
+			$functionDetail = $Trap->pluginClass->getFunctionDetails($function);
380
+			$functionDetail->params = htmlentities($functionDetail->params);
381
+			$functionDetail->description = htmlentities($functionDetail->description);
382
+			$functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
383
+			array_push($this->view->functionList, $functionDetail);
384
+		}
385 385
 
386 386
 	}
387 387
 
@@ -390,28 +390,28 @@  discard block
 block discarded – undo
390 390
 	 */
391 391
 	public function debugAction()
392 392
 	{
393
-	    $this->view->answer='No answer';
393
+		$this->view->answer='No answer';
394 394
 	    
395
-	    $postData=$this->getRequest()->getPost();
396
-	    if (isset($postData['input1']))
397
-	    {
398
-	        $input1 = $postData['input1'];
399
-	        $input2 = $postData['input2'];
400
-	        $input3 = $postData['input3'];
395
+		$postData=$this->getRequest()->getPost();
396
+		if (isset($postData['input1']))
397
+		{
398
+			$input1 = $postData['input1'];
399
+			$input2 = $postData['input2'];
400
+			$input3 = $postData['input3'];
401 401
 	        
402
-	        //$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
403
-	        try {
404
-	            $API = $this->getIdoConn();
405
-	            //$hosts = $API->getHostByIP($input1);
406
-	            $hosts = $API->getHostsIPByHostGroup($input1);
407
-	            $this->view->answer = print_r($hosts,true);
402
+			//$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
403
+			try {
404
+				$API = $this->getIdoConn();
405
+				//$hosts = $API->getHostByIP($input1);
406
+				$hosts = $API->getHostsIPByHostGroup($input1);
407
+				$this->view->answer = print_r($hosts,true);
408 408
 	            
409
-	        } catch (Exception $e)
410
-	        {
411
-	            $this->view->answer = "Exception : " . print_r($e->getMessage());
412
-	        }
409
+			} catch (Exception $e)
410
+			{
411
+				$this->view->answer = "Exception : " . print_r($e->getMessage());
412
+			}
413 413
 	        
414
-	    }
414
+		}
415 415
 	    
416 416
 	}
417 417
 	
@@ -423,36 +423,36 @@  discard block
 block discarded – undo
423 423
 		)->add('mib', array(
424 424
 			'label' => $this->translate('MIB Management'),
425 425
 			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
426
-	    )->add('uimgt', array(
427
-	        'label' => $this->translate('UI Configuration'),
428
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
429
-        )->add('services', array(
426
+		)->add('uimgt', array(
427
+			'label' => $this->translate('UI Configuration'),
428
+			'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
429
+		)->add('services', array(
430 430
 			'label' => $this->translate('Services management'),
431 431
 			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
432
-	    )->add('plugins', array(
433
-	        'label' => $this->translate('Plugins management'),
434
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
435
-	    );
432
+		)->add('plugins', array(
433
+			'label' => $this->translate('Plugins management'),
434
+			'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
435
+		);
436 436
 	} 
437 437
 }
438 438
 
439 439
 // TODO : see if useless 
440 440
 class UploadForm extends Form
441 441
 { 
442
-    public function __construct($options = null) 
443
-    {
444
-        parent::__construct($options);
445
-        $this->addElements2();
446
-    }
442
+	public function __construct($options = null) 
443
+	{
444
+		parent::__construct($options);
445
+		$this->addElements2();
446
+	}
447 447
 
448
-    public function addElements2()
449
-    {
450
-        // File Input
451
-        $file = new File('mib-file');
452
-        $file->setLabel('Mib upload');
453
-             //->setAttrib('multiple', null);
454
-        $this->addElement($file);
448
+	public function addElements2()
449
+	{
450
+		// File Input
451
+		$file = new File('mib-file');
452
+		$file->setLabel('Mib upload');
453
+			 //->setAttrib('multiple', null);
454
+		$this->addElement($file);
455 455
 		$button = new Submit("upload",array('ignore'=>false));
456 456
 		$this->addElement($button);//->setIgnore(false);
457
-    }
457
+	}
458 458
 }
Please login to merge, or discard this patch.
Spacing   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -21,19 +21,19 @@  discard block
 block discarded – undo
21 21
 		/************  Trapdb ***********/
22 22
 		try
23 23
 		{
24
-		    $dbConn = $this->getUIDatabase()->getDbConn();
24
+		    $dbConn=$this->getUIDatabase()->getDbConn();
25 25
 		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
26
-			$query = $dbConn->select()->from(
26
+			$query=$dbConn->select()->from(
27 27
 				$this->getModuleConfig()->getTrapTableName(),
28 28
 				array('COUNT(*)')
29 29
 			);			
30 30
 			$this->view->trap_count=$dbConn->fetchOne($query);
31
-			$query = $dbConn->select()->from(
31
+			$query=$dbConn->select()->from(
32 32
 				$this->getModuleConfig()->getTrapDataTableName(),
33 33
 				array('COUNT(*)')
34 34
 			);			
35 35
 			$this->view->trap_object_count=$dbConn->fetchOne($query);
36
-			$query = $dbConn->select()->from(
36
+			$query=$dbConn->select()->from(
37 37
 				$this->getModuleConfig()->getTrapRuleName(),
38 38
 				array('COUNT(*)')
39 39
 			);			
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 		}
45 45
 		catch (Exception $e)
46 46
 		{
47
-			$this->displayExitError('status',$e->getMessage());
47
+			$this->displayExitError('status', $e->getMessage());
48 48
 		}
49 49
 		
50 50
 		/*************** Log destination *******************/
@@ -59,20 +59,20 @@  discard block
 block discarded – undo
59 59
 		}
60 60
 		catch (Exception $e)
61 61
 		{
62
-			$this->displayExitError('status',$e->getMessage());
62
+			$this->displayExitError('status', $e->getMessage());
63 63
 		}
64 64
 		
65 65
 		/*************** SNMP configuration ****************/
66 66
 		try
67 67
 		{
68
-		    $this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
68
+		    $this->view->useSnmpTrapAddess=($this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1) ? TRUE : FALSE;
69 69
 		    $this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
-		    $this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
70
+		    $this->view->SnmpTrapAddressOIDDefault=($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid']) ? TRUE : FALSE;
71 71
 		    
72 72
 		}
73 73
 		catch (Exception $e)
74 74
 		{
75
-		    $this->displayExitError('status',$e->getMessage());
75
+		    $this->displayExitError('status', $e->getMessage());
76 76
 		}		
77 77
 		
78 78
 	} 
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 				if ($action == 'update_mib_db')
99 99
 				{ // Do the update in background
100 100
 					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
101
-					if (preg_match('/OK/',$return))
101
+					if (preg_match('/OK/', $return))
102 102
 					{
103 103
 					    $this->_helper->json(array('status'=>'OK'));
104 104
 					}
@@ -107,32 +107,32 @@  discard block
 block discarded – undo
107 107
 				}
108 108
 				if ($action == 'check_update')
109 109
 				{
110
-				    $file=@fopen('/tmp/trapdirector_update.pid','r');
110
+				    $file=@fopen('/tmp/trapdirector_update.pid', 'r');
111 111
 				    if ($file == false)
112 112
 				    {   // process is dead
113
-				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
113
+				        $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'Cannot open file'));
114 114
 				        return;
115 115
 				    }
116 116
 				    $pid=fgets($file);
117 117
 				    $output=array();
118 118
 				    $retVal=0;
119
-					exec('ps '.$pid,$output,$retVal);
119
+					exec('ps '.$pid, $output, $retVal);
120 120
 					if ($retVal == 0)
121 121
 					{ // process is alive
122 122
 						$this->_helper->json(array('status'=>'Alive and kicking'));
123 123
 					}
124 124
 					else
125 125
 					{ // process is dead
126
-					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
126
+					    $this->_helper->json(array('status'=>'tu quoque fili', 'err'=>'no proc'.$pid));
127 127
 					}
128 128
 				}
129
-				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
129
+				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible'));
130 130
 			}
131 131
 			/** Check for mib file UPLOAD */
132 132
 			if (isset($_FILES['mibfile']))
133 133
 			{
134
-			    $name=filter_var($_FILES['mibfile']['name'],FILTER_SANITIZE_STRING);
135
-				$DirConf=explode(':',$this->Config()->get('config', 'snmptranslate_dirs'));
134
+			    $name=filter_var($_FILES['mibfile']['name'], FILTER_SANITIZE_STRING);
135
+				$DirConf=explode(':', $this->Config()->get('config', 'snmptranslate_dirs'));
136 136
 				$destDir=array_shift($DirConf);
137 137
 				if (!is_dir($destDir))
138 138
 				{
@@ -146,9 +146,9 @@  discard block
 block discarded – undo
146 146
 				    }
147 147
 				    else
148 148
 				    {
149
-				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150
-				        $sourceTmpNam=filter_var($_FILES['mibfile']['tmp_name'],FILTER_SANITIZE_STRING);
151
-				        if (move_uploaded_file($sourceTmpNam,$destination)===false)
149
+				        $destination=$destDir.'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150
+				        $sourceTmpNam=filter_var($_FILES['mibfile']['tmp_name'], FILTER_SANITIZE_STRING);
151
+				        if (move_uploaded_file($sourceTmpNam, $destination) === false)
152 152
     				    {
153 153
     				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154 154
     				    }
@@ -164,13 +164,13 @@  discard block
 block discarded – undo
164 164
 		}
165 165
 		
166 166
 		// snmptranslate tests
167
-		$snmptranslate = $this->Config()->get('config', 'snmptranslate');
167
+		$snmptranslate=$this->Config()->get('config', 'snmptranslate');
168 168
 		$this->view->snmptranslate_bin=$snmptranslate;
169 169
 		$this->view->snmptranslate_state='warn';
170
-		if (is_executable ( $snmptranslate ))
170
+		if (is_executable($snmptranslate))
171 171
 		{
172
-			$translate=exec($snmptranslate . ' 1');
173
-			if (preg_match('/iso/',$translate))
172
+			$translate=exec($snmptranslate.' 1');
173
+			if (preg_match('/iso/', $translate))
174 174
 			{
175 175
 				$this->view->snmptranslate='works fine';
176 176
 				$this->view->snmptranslate_state='ok';
@@ -188,46 +188,46 @@  discard block
 block discarded – undo
188 188
 		// mib database
189 189
 		
190 190
 		$this->view->mibDbCount=$this->getMIB()->countObjects();
191
-		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null,21);
191
+		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null, 21);
192 192
 		
193 193
 		// mib dirs
194 194
 		$DirConf=$this->Config()->get('config', 'snmptranslate_dirs');
195
-		$dirArray=explode(':',$DirConf);
195
+		$dirArray=explode(':', $DirConf);
196 196
 
197 197
 		// Get base directories from net-snmp-config
198 198
 		$output=$matches=array();
199 199
 		$retVal=0;
200
-		$sysDirs=exec('net-snmp-config --default-mibdirs',$output,$retVal);
201
-		if ($retVal==0)
200
+		$sysDirs=exec('net-snmp-config --default-mibdirs', $output, $retVal);
201
+		if ($retVal == 0)
202 202
 		{
203
-			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
203
+			$dirArray=array_merge($dirArray, explode(':', $sysDirs));
204 204
 		}
205 205
 		else
206 206
 		{
207
-			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
208
-			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
207
+			$translateOut=exec($this->Config()->get('config', 'snmptranslate').' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
208
+			if (preg_match('/MIBDIRS.*\'([^\']+)\'/', $translateOut, $matches))
209 209
 			{
210
-				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
210
+				$dirArray=array_merge($dirArray, explode(':', $matches[1]));
211 211
 			}
212 212
 			else
213 213
 			{
214
-				array_push($dirArray,'Install net-snmp-config to see system directories');
214
+				array_push($dirArray, 'Install net-snmp-config to see system directories');
215 215
 			}
216 216
 		}
217 217
 		
218 218
 		$this->view->dirArray=$dirArray;
219 219
 		
220 220
 		$output=null;
221
-		foreach (explode(':',$DirConf) as $mibdir)
221
+		foreach (explode(':', $DirConf) as $mibdir)
222 222
 		{
223
-			exec('ls '.$mibdir.' | grep -v traplist.txt',$output);
223
+			exec('ls '.$mibdir.' | grep -v traplist.txt', $output);
224 224
 		}
225 225
 		//$i=0;$listFiles='';while (isset($output[$i])) $listFiles.=$output[$i++];
226 226
 		//$this->view->fileList=explode(' ',$listFiles);
227 227
 		$this->view->fileList=$output;
228 228
 		
229 229
 		// Zend form 
230
-		$this->view->form= new UploadForm();
230
+		$this->view->form=new UploadForm();
231 231
 		//$this->view->form= new Form('upload-form');
232 232
 		
233 233
 		
@@ -242,9 +242,9 @@  discard block
 block discarded – undo
242 242
 	    $this->view->setOKMsg='';
243 243
 	    
244 244
 	    //max_rows=25&row_update=update
245
-	    if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
245
+	    if ($this->getRequest()->getParam('max_rows', NULL) !== NULL)
246 246
 	    {
247
-	        $maxRows = $this->getRequest()->getParam('max_rows');
247
+	        $maxRows=$this->getRequest()->getParam('max_rows');
248 248
 	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
249 249
 	        {
250 250
 	            $this->view->setError='Max rows must be a number';
@@ -252,21 +252,21 @@  discard block
 block discarded – undo
252 252
 	        else
253 253
 	        {
254 254
 	            $this->setitemListDisplay($maxRows);
255
-	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
255
+	            $this->view->setOKMsg='Set max rows to '.$maxRows;
256 256
 	        }
257 257
 	    }
258 258
 	    
259
-	    if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
259
+	    if ($this->getRequest()->getParam('add_category', NULL) !== NULL)
260 260
 	    {
261
-	        $addCat = $this->getRequest()->getParam('add_category');
261
+	        $addCat=$this->getRequest()->getParam('add_category');
262 262
             $this->addHandlersCategory($addCat);
263 263
 	    }
264 264
 	    
265
-	    if ( $this->getRequest()->getPost('type',NULL) !== NULL )
265
+	    if ($this->getRequest()->getPost('type', NULL) !== NULL)
266 266
 	    {
267
-	        $type = $this->getRequest()->getPost('type',NULL);
268
-	        $index = $this->getRequest()->getPost('index',NULL);
269
-	        $newname = $this->getRequest()->getPost('newname',NULL);
267
+	        $type=$this->getRequest()->getPost('type', NULL);
268
+	        $index=$this->getRequest()->getPost('index', NULL);
269
+	        $newname=$this->getRequest()->getPost('newname', NULL);
270 270
 
271 271
 	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
272 272
 	            $this->_helper->json(array('status'=>'Bad index'));
@@ -290,9 +290,9 @@  discard block
 block discarded – undo
290 290
 	        }
291 291
 	    }
292 292
 	    
293
-	    $this->view->maxRows = $this->itemListDisplay();
293
+	    $this->view->maxRows=$this->itemListDisplay();
294 294
 	    
295
-	    $this->view->categories = $this->getHandlersCategory();
295
+	    $this->view->categories=$this->getHandlersCategory();
296 296
 	    
297 297
 	    
298 298
 	    
@@ -316,18 +316,18 @@  discard block
 block discarded – undo
316 316
 		$this->view->templateForm_output='';
317 317
 		if (isset($postData['template_name']) && isset($postData['template_revert_time']))
318 318
 		{
319
-			$template_create = 'icingacli director service create --json \'{ "check_command": "dummy", ';
320
-			$template_create .= '"check_interval": "' .$postData['template_revert_time']. '", "check_timeout": "20", "disabled": false, "enable_active_checks": true, "enable_event_handler": true, "enable_notifications": true, "enable_passive_checks": true, "enable_perfdata": true, "max_check_attempts": "1", ';
321
-			$template_create .= '"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
319
+			$template_create='icingacli director service create --json \'{ "check_command": "dummy", ';
320
+			$template_create.='"check_interval": "'.$postData['template_revert_time'].'", "check_timeout": "20", "disabled": false, "enable_active_checks": true, "enable_event_handler": true, "enable_notifications": true, "enable_passive_checks": true, "enable_perfdata": true, "max_check_attempts": "1", ';
321
+			$template_create.='"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
322 322
 			$output=array();
323 323
 			$ret_code=0;
324
-			exec($template_create,$output,$ret_code);
324
+			exec($template_create, $output, $ret_code);
325 325
 			if ($ret_code != 0)
326 326
 			{
327
-				$this->displayExitError("Status -> Services","Error creating template : ".$output[0].'<br>Command was : '.$template_create);
327
+				$this->displayExitError("Status -> Services", "Error creating template : ".$output[0].'<br>Command was : '.$template_create);
328 328
 			}
329
-			exec('icingacli director config deploy',$output,$ret_code);
330
-			$this->view->templateForm_output='Template '.$postData['template_name']. ' created';
329
+			exec('icingacli director config deploy', $output, $ret_code);
330
+			$this->view->templateForm_output='Template '.$postData['template_name'].' created';
331 331
 		}
332 332
 		
333 333
 		// template creation form
@@ -343,15 +343,15 @@  discard block
 block discarded – undo
343 343
 	{
344 344
 	    $this->prepareTabs()->activate('plugins');
345 345
 	    
346
-	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
346
+	    require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
347 347
 	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
348
-	    $Trap = new Trap($icingaweb2_etc,4);
348
+	    $Trap=new Trap($icingaweb2_etc, 4);
349 349
 	    
350
-	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
350
+	    $this->view->pluginLoaded=htmlentities($Trap->pluginClass->registerAllPlugins(false));
351 351
 	    
352
-	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
352
+	    $enabledPlugins=$Trap->pluginClass->getEnabledPlugins();
353 353
 
354
-	    $pluginList = $Trap->pluginClass->pluginList();
354
+	    $pluginList=$Trap->pluginClass->pluginList();
355 355
 	    
356 356
 	    // Plugin list and fill function name list
357 357
 	    $functionList=array();
@@ -359,16 +359,16 @@  discard block
 block discarded – undo
359 359
 	    foreach ($pluginList as $plugin)
360 360
 	    {
361 361
 	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
362
-	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
363
-	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
364
-	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
365
-	        $pluginDetails->description = htmlentities($pluginDetails->description);
366
-	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
362
+	        $pluginDetails->enabled=(in_array($plugin, $enabledPlugins)) ? true : false;
363
+	        $pluginDetails->catchAllTraps=($pluginDetails->catchAllTraps === true) ? 'Yes' : 'No';
364
+	        $pluginDetails->processTraps=($pluginDetails->processTraps === true) ? 'Yes' : 'No';
365
+	        $pluginDetails->description=htmlentities($pluginDetails->description);
366
+	        $pluginDetails->description=preg_replace('/\n/', '<br>', $pluginDetails->description);
367 367
 	        array_push($this->view->pluginArray, $pluginDetails);
368 368
 	        // Get functions for function details
369 369
 	        foreach ($pluginDetails->funcArray as $function)
370 370
 	        {
371
-	            array_push($functionList,$function);
371
+	            array_push($functionList, $function);
372 372
 	        }
373 373
 	    }
374 374
 	    
@@ -376,10 +376,10 @@  discard block
 block discarded – undo
376 376
 	    $this->view->functionList=array();
377 377
 	    foreach ($functionList as $function)
378 378
 	    {
379
-	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
380
-	        $functionDetail->params = htmlentities($functionDetail->params);
381
-	        $functionDetail->description = htmlentities($functionDetail->description);
382
-	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
379
+	        $functionDetail=$Trap->pluginClass->getFunctionDetails($function);
380
+	        $functionDetail->params=htmlentities($functionDetail->params);
381
+	        $functionDetail->description=htmlentities($functionDetail->description);
382
+	        $functionDetail->description=preg_replace('/\n/', '<br>', $functionDetail->description);
383 383
 	        array_push($this->view->functionList, $functionDetail);
384 384
 	    }
385 385
 
@@ -395,20 +395,20 @@  discard block
 block discarded – undo
395 395
 	    $postData=$this->getRequest()->getPost();
396 396
 	    if (isset($postData['input1']))
397 397
 	    {
398
-	        $input1 = $postData['input1'];
399
-	        $input2 = $postData['input2'];
400
-	        $input3 = $postData['input3'];
398
+	        $input1=$postData['input1'];
399
+	        $input2=$postData['input2'];
400
+	        $input3=$postData['input3'];
401 401
 	        
402 402
 	        //$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
403 403
 	        try {
404
-	            $API = $this->getIdoConn();
404
+	            $API=$this->getIdoConn();
405 405
 	            //$hosts = $API->getHostByIP($input1);
406
-	            $hosts = $API->getHostsIPByHostGroup($input1);
407
-	            $this->view->answer = print_r($hosts,true);
406
+	            $hosts=$API->getHostsIPByHostGroup($input1);
407
+	            $this->view->answer=print_r($hosts, true);
408 408
 	            
409 409
 	        } catch (Exception $e)
410 410
 	        {
411
-	            $this->view->answer = "Exception : " . print_r($e->getMessage());
411
+	            $this->view->answer="Exception : ".print_r($e->getMessage());
412 412
 	        }
413 413
 	        
414 414
 	    }
@@ -419,19 +419,19 @@  discard block
 block discarded – undo
419 419
 	{
420 420
 		return $this->getTabs()->add('status', array(
421 421
 			'label' => $this->translate('Status'),
422
-			'url'   => $this->getModuleConfig()->urlPath() . '/status')
422
+			'url'   => $this->getModuleConfig()->urlPath().'/status')
423 423
 		)->add('mib', array(
424 424
 			'label' => $this->translate('MIB Management'),
425
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
425
+			'url'   => $this->getModuleConfig()->urlPath().'/status/mib')
426 426
 	    )->add('uimgt', array(
427 427
 	        'label' => $this->translate('UI Configuration'),
428
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
428
+	        'url'   => $this->getModuleConfig()->urlPath().'/status/uimgt')
429 429
         )->add('services', array(
430 430
 			'label' => $this->translate('Services management'),
431
-			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
431
+			'url'   => $this->getModuleConfig()->urlPath().'/status/services')
432 432
 	    )->add('plugins', array(
433 433
 	        'label' => $this->translate('Plugins management'),
434
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
434
+	        'url'   => $this->getModuleConfig()->urlPath().'/status/plugins')
435 435
 	    );
436 436
 	} 
437 437
 }
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
 // TODO : see if useless 
440 440
 class UploadForm extends Form
441 441
 { 
442
-    public function __construct($options = null) 
442
+    public function __construct($options=null) 
443 443
     {
444 444
         parent::__construct($options);
445 445
         $this->addElements2();
@@ -448,11 +448,11 @@  discard block
 block discarded – undo
448 448
     public function addElements2()
449 449
     {
450 450
         // File Input
451
-        $file = new File('mib-file');
451
+        $file=new File('mib-file');
452 452
         $file->setLabel('Mib upload');
453 453
              //->setAttrib('multiple', null);
454 454
         $this->addElement($file);
455
-		$button = new Submit("upload",array('ignore'=>false));
456
-		$this->addElement($button);//->setIgnore(false);
455
+		$button=new Submit("upload", array('ignore'=>false));
456
+		$this->addElement($button); //->setIgnore(false);
457 457
     }
458 458
 }
Please login to merge, or discard this patch.