Passed
Push — master ( 8ef52a...4d2ca2 )
by Patrick
02:00
created
library/Trapdirector/TrapsController.php 1 patch
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.
library/Trapdirector/Icinga2Api.php 1 patch
Indentation   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -10,151 +10,151 @@
 block discarded – undo
10 10
 class Icinga2API extends IcingaApiBase
11 11
 {
12 12
     
13
-    /**
14
-     * Creates Icinga2API object
15
-     * 
16
-     * @param string $host host name or IP
17
-     * @param number $port API port
18
-     */
19
-    public function __construct($host, $port = 5665)
20
-    {
21
-        parent::__construct($host,$port);
22
-    }
23
-    /**
13
+	/**
14
+	 * Creates Icinga2API object
15
+	 * 
16
+	 * @param string $host host name or IP
17
+	 * @param number $port API port
18
+	 */
19
+	public function __construct($host, $port = 5665)
20
+	{
21
+		parent::__construct($host,$port);
22
+	}
23
+	/**
24 24
 
25 25
 /************ Host query ************/  
26 26
   
27
-    /**
28
-     * return array of host by IP (4 or 6) or name
29
-     * @param string $ip
30
-     * @throws Exception
31
-     * @return array objects : array('__name','name','display_name')
32
-     */
33
-    public function getHostByIP(string $ip) 
34
-    {
35
-        return $this->standardQuery(
36
-            'host', 
37
-            'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
38
-            array('__name','name','display_name')
39
-        );
40
-    }
27
+	/**
28
+	 * return array of host by IP (4 or 6) or name
29
+	 * @param string $ip
30
+	 * @throws Exception
31
+	 * @return array objects : array('__name','name','display_name')
32
+	 */
33
+	public function getHostByIP(string $ip) 
34
+	{
35
+		return $this->standardQuery(
36
+			'host', 
37
+			'match("*' . $ip . '*",host.address) || match("*' . $ip . '*",host.address6) || match("*' . $ip . '*",host.name) || match("*' . $ip . '*",host.display_name)',
38
+			array('__name','name','display_name')
39
+		);
40
+	}
41 41
 
42 42
     
43
-    /**
44
-     * Get host(s) by name in API
45
-     * @param string $name
46
-     * @return array|NULL[] : see getHostByIP
47
-     */
48
-    public function getHostByName(string $name)
49
-    {
50
-        return $this->getHostByIP($name);
51
-    }
43
+	/**
44
+	 * Get host(s) by name in API
45
+	 * @param string $name
46
+	 * @return array|NULL[] : see getHostByIP
47
+	 */
48
+	public function getHostByName(string $name)
49
+	{
50
+		return $this->getHostByIP($name);
51
+	}
52 52
  
53
-    /**
54
-     * Get all host and IP from hostgroup
55
-     * @param string $hostGroup
56
-     * @throws Exception
57
-     * @return array : attributes : address, address6, name
58
-     */
59
-    public function getHostsIPByHostGroup($hostGroup)
60
-    {        
61
-        return $this->standardQuery(
62
-            'host', 
63
-            '"' . $hostGroup . '" in host.groups',
64
-            array('address','address6','name')
53
+	/**
54
+	 * Get all host and IP from hostgroup
55
+	 * @param string $hostGroup
56
+	 * @throws Exception
57
+	 * @return array : attributes : address, address6, name
58
+	 */
59
+	public function getHostsIPByHostGroup($hostGroup)
60
+	{        
61
+		return $this->standardQuery(
62
+			'host', 
63
+			'"' . $hostGroup . '" in host.groups',
64
+			array('address','address6','name')
65 65
                 
66
-        );
67
-    }
66
+		);
67
+	}
68 68
     
69
-    /**
70
-     * Get all host and IP from hostgroup
71
-     * @param string $hostGroup
72
-     * @throws Exception
73
-     * @return array : attributes : address, address6, name
74
-     */
75
-    public function getHostGroupByName($name)
76
-    {
77
-        return $this->standardQuery(
78
-            'hostgroup',
79
-            'match("*' . $name . '*",hostgroup.name)',
80
-            array('name','display_name')
69
+	/**
70
+	 * Get all host and IP from hostgroup
71
+	 * @param string $hostGroup
72
+	 * @throws Exception
73
+	 * @return array : attributes : address, address6, name
74
+	 */
75
+	public function getHostGroupByName($name)
76
+	{
77
+		return $this->standardQuery(
78
+			'hostgroup',
79
+			'match("*' . $name . '*",hostgroup.name)',
80
+			array('name','display_name')
81 81
             
82
-            );
83
-    }
82
+			);
83
+	}
84 84
 
85
-    /** Get services from host in API
86
-     *	
87
-     *  @throws Exception
88
-     *	@param $id string host name
89
-     *	@return array display_name (of service), service_object_id
90
-     */
91
-    public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
92
-    {
93
-        $filter = 'match("' . $id . '!*", service.__name)';
94
-        if ($active === TRUE)
95
-        {
96
-            $filter .= ' && service.active==true';
97
-        }
98
-        if ($passive_svc === TRUE)
99
-        {
100
-            $filter .= ' && service.enable_passive_checks==true';
101
-        }
102
-        return $this->standardQuery(
103
-            'service',
104
-            $filter,
105
-            array('__name','name','display_name','active')
106
-            );
85
+	/** Get services from host in API
86
+	 *	
87
+	 *  @throws Exception
88
+	 *	@param $id string host name
89
+	 *	@return array display_name (of service), service_object_id
90
+	 */
91
+	public function getServicesByHostid(string $id, bool $active = TRUE, bool $passive_svc = TRUE)
92
+	{
93
+		$filter = 'match("' . $id . '!*", service.__name)';
94
+		if ($active === TRUE)
95
+		{
96
+			$filter .= ' && service.active==true';
97
+		}
98
+		if ($passive_svc === TRUE)
99
+		{
100
+			$filter .= ' && service.enable_passive_checks==true';
101
+		}
102
+		return $this->standardQuery(
103
+			'service',
104
+			$filter,
105
+			array('__name','name','display_name','active')
106
+			);
107 107
         
108
-    }
108
+	}
109 109
 
110
-    /**
111
-     * return array of host by IP (4 or 6) or name
112
-     * @param string $group Host group name
113
-     * @throws Exception
114
-     * @return array objects : array('name','display_name')
115
-     */
116
-    public function getHostsByGroup(string $group)
117
-    {
118
-         return $this->standardQuery(
119
-            'host',
120
-            '"' . $group . '" in host.groups',
121
-            array('name','display_name')
122
-            );
123
-    }
110
+	/**
111
+	 * return array of host by IP (4 or 6) or name
112
+	 * @param string $group Host group name
113
+	 * @throws Exception
114
+	 * @return array objects : array('name','display_name')
115
+	 */
116
+	public function getHostsByGroup(string $group)
117
+	{
118
+		 return $this->standardQuery(
119
+			'host',
120
+			'"' . $group . '" in host.groups',
121
+			array('name','display_name')
122
+			);
123
+	}
124 124
     
125
-    public function getServicesByHostGroupid(string $group)
126
-    {
127
-        $hostList = $this->getHostsByGroup($group);
128
-        //return $hostList;
129
-        $hostNum = count($hostList);
130
-        $serviceList=array();
131
-        foreach ($hostList as $curHost)
132
-        {
133
-            $services = $this->getServicesByHostid($curHost->name);
134
-            foreach ($services as $service)
135
-            {
136
-                //return $service;
137
-                if (! isset($serviceList[$service->name]))
138
-                {
139
-                    $serviceList[$service->name]=
140
-                        array('num'=> 1 ,'display_name' => $service->display_name);
141
-                }
142
-                else
143
-                {
144
-                    $serviceList[$service->name]['num']++;
145
-                }
146
-            }
147
-        }
148
-        $commonServices=array();
149
-        foreach ($serviceList as $serviceName => $values)
150
-        {
151
-            if ($values['num'] >= $hostNum)
152
-            {
153
-                $commonServices[$serviceName] = $values['display_name'];
154
-            }
155
-        }
156
-        return $commonServices;
157
-    }
125
+	public function getServicesByHostGroupid(string $group)
126
+	{
127
+		$hostList = $this->getHostsByGroup($group);
128
+		//return $hostList;
129
+		$hostNum = count($hostList);
130
+		$serviceList=array();
131
+		foreach ($hostList as $curHost)
132
+		{
133
+			$services = $this->getServicesByHostid($curHost->name);
134
+			foreach ($services as $service)
135
+			{
136
+				//return $service;
137
+				if (! isset($serviceList[$service->name]))
138
+				{
139
+					$serviceList[$service->name]=
140
+						array('num'=> 1 ,'display_name' => $service->display_name);
141
+				}
142
+				else
143
+				{
144
+					$serviceList[$service->name]['num']++;
145
+				}
146
+			}
147
+		}
148
+		$commonServices=array();
149
+		foreach ($serviceList as $serviceName => $values)
150
+		{
151
+			if ($values['num'] >= $hostNum)
152
+			{
153
+				$commonServices[$serviceName] = $values['display_name'];
154
+			}
155
+		}
156
+		return $commonServices;
157
+	}
158 158
     
159 159
 }
160 160
 
Please login to merge, or discard this patch.
library/Trapdirector/IcingaApi/IcingaApiBase.php 1 patch
Indentation   +308 added lines, -308 removed lines patch added patch discarded remove patch
@@ -8,342 +8,342 @@
 block discarded – undo
8 8
 
9 9
 class IcingaApiBase
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 $queryURL=array(
22
-        'host'  => 'objects/hosts',
23
-        'hostgroup' => 'objects/hostgroups',
24
-        'service' => 'objects/services'
25
-    );
21
+	protected $queryURL=array(
22
+		'host'  => 'objects/hosts',
23
+		'hostgroup' => 'objects/hostgroups',
24
+		'service' => 'objects/services'
25
+	);
26 26
     
27
-    protected $curl;
28
-    // http://php.net/manual/de/function.json-last-error.php#119985
29
-    protected $errorReference = [
30
-        JSON_ERROR_NONE => 'No error has occurred.',
31
-        JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
32
-        JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
33
-        JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded.',
34
-        JSON_ERROR_SYNTAX => 'Syntax error.',
35
-        JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded.',
36
-        JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded.',
37
-        JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
38
-        JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
39
-    ];
40
-    const JSON_UNKNOWN_ERROR = 'Unknown error.';
27
+	protected $curl;
28
+	// http://php.net/manual/de/function.json-last-error.php#119985
29
+	protected $errorReference = [
30
+		JSON_ERROR_NONE => 'No error has occurred.',
31
+		JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
32
+		JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
33
+		JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded.',
34
+		JSON_ERROR_SYNTAX => 'Syntax error.',
35
+		JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded.',
36
+		JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded.',
37
+		JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
38
+		JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
39
+	];
40
+	const JSON_UNKNOWN_ERROR = 'Unknown error.';
41 41
     
42
-    /**
43
-     * Creates Icinga2API object
44
-     * 
45
-     * @param string $host host name or IP
46
-     * @param number $port API port
47
-     */
48
-    public function __construct($host, $port = 5665)
49
-    {
50
-        $this->host=$host;
51
-        $this->port=$port;
52
-    }
53
-    /**
54
-     * Set user & pass
55
-     * @param string $user
56
-     * @param string $pass
57
-     */
58
-    public function setCredentials($user,$pass)
59
-    {
60
-        $this->user=$user;
61
-        $this->pass=$pass;
62
-        $this->authmethod='pass';
63
-    }
42
+	/**
43
+	 * Creates Icinga2API object
44
+	 * 
45
+	 * @param string $host host name or IP
46
+	 * @param number $port API port
47
+	 */
48
+	public function __construct($host, $port = 5665)
49
+	{
50
+		$this->host=$host;
51
+		$this->port=$port;
52
+	}
53
+	/**
54
+	 * Set user & pass
55
+	 * @param string $user
56
+	 * @param string $pass
57
+	 */
58
+	public function setCredentials($user,$pass)
59
+	{
60
+		$this->user=$user;
61
+		$this->pass=$pass;
62
+		$this->authmethod='pass';
63
+	}
64 64
     
65
-    /**
66
-     * Set user & certificate (NOT IMPLEMENTED @throws RuntimeException)
67
-     * @param string $user
68
-     * @param string $usercert
69
-     */
70
-    public function setCredentialskey($user,$usercert)
71
-    {
72
-        $this->user=$user;
73
-        $this->usercert=$usercert;
74
-        $this->authmethod='cert';
75
-        throw new RuntimeException('Certificate auth not implemented');
76
-    }
65
+	/**
66
+	 * Set user & certificate (NOT IMPLEMENTED @throws RuntimeException)
67
+	 * @param string $user
68
+	 * @param string $usercert
69
+	 */
70
+	public function setCredentialskey($user,$usercert)
71
+	{
72
+		$this->user=$user;
73
+		$this->usercert=$usercert;
74
+		$this->authmethod='cert';
75
+		throw new RuntimeException('Certificate auth not implemented');
76
+	}
77 77
 
78
-    public function test(array $permissions)
79
-    {
80
-       try
81
-        {
82
-            $result=$this->request('GET', "", NULL, NULL);
83
-        } 
84
-        catch (Exception $e)
85
-        {
86
-            return array(true, 'Error with API : '.$e->getMessage());
87
-        }
88
-        //var_dump($result);
89
-        $permOk=1;
90
-        $permMissing='';
91
-        if ($permissions === NULL || count($permissions) == 0) // If no permission check return OK after connexion
92
-        {
93
-            return array(false,'OK');
94
-        }
95
-        if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
96
-        {
78
+	public function test(array $permissions)
79
+	{
80
+	   try
81
+		{
82
+			$result=$this->request('GET', "", NULL, NULL);
83
+		} 
84
+		catch (Exception $e)
85
+		{
86
+			return array(true, 'Error with API : '.$e->getMessage());
87
+		}
88
+		//var_dump($result);
89
+		$permOk=1;
90
+		$permMissing='';
91
+		if ($permissions === NULL || count($permissions) == 0) // If no permission check return OK after connexion
92
+		{
93
+			return array(false,'OK');
94
+		}
95
+		if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
96
+		{
97 97
             
98
-            foreach ( $permissions as $mustPermission)
99
-            {
100
-                $curPermOK=0;
101
-                foreach ( $result->results[0]->permissions as $curPermission)
102
-                {
103
-                    $curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
104
-                    if (preg_match('#'.$curPermission.'#',$mustPermission))
105
-                    {
106
-                        $curPermOK=1;
107
-                        break;
108
-                    }
109
-                }
110
-                if ($curPermOK == 0)
111
-                {
112
-                    $permOk=0;
113
-                    $permMissing=$mustPermission;
114
-                    break;
115
-                }
116
-            }
117
-            if ($permOk == 0)
118
-            {
119
-                return array(true,'API connection OK, but missing permission : '.$permMissing);
120
-            }
121
-            return array(false,'API connection OK');
98
+			foreach ( $permissions as $mustPermission)
99
+			{
100
+				$curPermOK=0;
101
+				foreach ( $result->results[0]->permissions as $curPermission)
102
+				{
103
+					$curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
104
+					if (preg_match('#'.$curPermission.'#',$mustPermission))
105
+					{
106
+						$curPermOK=1;
107
+						break;
108
+					}
109
+				}
110
+				if ($curPermOK == 0)
111
+				{
112
+					$permOk=0;
113
+					$permMissing=$mustPermission;
114
+					break;
115
+				}
116
+			}
117
+			if ($permOk == 0)
118
+			{
119
+				return array(true,'API connection OK, but missing permission : '.$permMissing);
120
+			}
121
+			return array(false,'API connection OK');
122 122
             
123
-        }
124
-        return array(true,'API connection OK, but cannot get permissions');
125
-    }
123
+		}
124
+		return array(true,'API connection OK, but cannot get permissions');
125
+	}
126 126
     
127 127
     
128
-    protected function url($url) {
129
-        return sprintf('https://%s:%d/%s/%s', $this->host, $this->port, $this->version, $url);
130
-    }
128
+	protected function url($url) {
129
+		return sprintf('https://%s:%d/%s/%s', $this->host, $this->port, $this->version, $url);
130
+	}
131 131
     
132
-    /**
133
-     * Create or return curl ressource
134
-     * @throws Exception
135
-     * @return resource
136
-     */
137
-    protected function curl() {
138
-        if ($this->curl === null) {
139
-            $this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
140
-            if ($this->curl === false) {
141
-                throw new Exception('CURL INIT ERROR');
142
-            }
143
-        }
144
-        return $this->curl;
145
-    }
132
+	/**
133
+	 * Create or return curl ressource
134
+	 * @throws Exception
135
+	 * @return resource
136
+	 */
137
+	protected function curl() {
138
+		if ($this->curl === null) {
139
+			$this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
140
+			if ($this->curl === false) {
141
+				throw new Exception('CURL INIT ERROR');
142
+			}
143
+		}
144
+		return $this->curl;
145
+	}
146 146
 
147
-    /**
148
-     * Send a passive service check
149
-     * @param string $host : host name 
150
-     * @param string $service : service name
151
-     * @param int $state : state of service
152
-     * @param string $display : service passive check output
153
-     * @param string $perfdata : performance data as string
154
-     * @return array (status = true (oK) or false (nok), string message)
155
-     */
156
-    public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
157
-    {
158
-        //Send a POST request to the URL endpoint /v1/actions/process-check-result
159
-        //actions/process-check-result?service=example.localdomain!passive-ping6
160
-        $url='actions/process-check-result';
161
-        $body=array(
162
-            "filter"        => 'service.name=="'.$service.'" && service.host_name=="'.$host.'"',
163
-            'type'          => 'Service',
164
-            "exit_status"   => $state,
165
-            "plugin_output" => $display,
166
-            "performance_data" => $perfdata
167
-        );
168
-        try 
169
-        {
170
-            $result=$this->request('POST', $url, null, $body);
171
-        } catch (Exception $e) 
172
-        {
173
-            return array(false, $e->getMessage());
174
-        }
175
-        if (property_exists($result,'error') )
176
-        {
177
-            if (property_exists($result,'status'))
178
-            {
179
-                $message=$result->status;
180
-            }
181
-            else 
182
-            {
183
-                $message="Unkown status";
184
-            }
185
-            return array(false , 'Ret code ' .$result->error.' : '.$message);
186
-        }
187
-        if (property_exists($result, 'results'))
188
-        {
189
-            if (isset($result->results[0]))
190
-            {
191
-                return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
192
-            }
193
-            else
194
-            {
195
-                return array(false,'Service not found');
196
-            }
147
+	/**
148
+	 * Send a passive service check
149
+	 * @param string $host : host name 
150
+	 * @param string $service : service name
151
+	 * @param int $state : state of service
152
+	 * @param string $display : service passive check output
153
+	 * @param string $perfdata : performance data as string
154
+	 * @return array (status = true (oK) or false (nok), string message)
155
+	 */
156
+	public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
157
+	{
158
+		//Send a POST request to the URL endpoint /v1/actions/process-check-result
159
+		//actions/process-check-result?service=example.localdomain!passive-ping6
160
+		$url='actions/process-check-result';
161
+		$body=array(
162
+			"filter"        => 'service.name=="'.$service.'" && service.host_name=="'.$host.'"',
163
+			'type'          => 'Service',
164
+			"exit_status"   => $state,
165
+			"plugin_output" => $display,
166
+			"performance_data" => $perfdata
167
+		);
168
+		try 
169
+		{
170
+			$result=$this->request('POST', $url, null, $body);
171
+		} catch (Exception $e) 
172
+		{
173
+			return array(false, $e->getMessage());
174
+		}
175
+		if (property_exists($result,'error') )
176
+		{
177
+			if (property_exists($result,'status'))
178
+			{
179
+				$message=$result->status;
180
+			}
181
+			else 
182
+			{
183
+				$message="Unkown status";
184
+			}
185
+			return array(false , 'Ret code ' .$result->error.' : '.$message);
186
+		}
187
+		if (property_exists($result, 'results'))
188
+		{
189
+			if (isset($result->results[0]))
190
+			{
191
+				return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
192
+			}
193
+			else
194
+			{
195
+				return array(false,'Service not found');
196
+			}
197 197
             
198
-        }
199
-        return array(false,'Unkown result, open issue with this : '.print_r($result,true));
200
-    }
198
+		}
199
+		return array(false,'Unkown result, open issue with this : '.print_r($result,true));
200
+	}
201 201
   
202
-    /**
203
-     * Check 'result' exists and check for errors/status
204
-     * @param \stdClass $result
205
-     * @throws Exception 
206
-     */
207
-    public function checkResultStatus(\stdClass $result) 
208
-    {
209
-        if (property_exists($result,'error') )
210
-        {
211
-            if (property_exists($result,'status'))
212
-            {
213
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
214
-            }
215
-            else
216
-            {
217
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
218
-            }
219
-        }
220
-        if ( ! property_exists($result, 'results'))
221
-        {
222
-            throw new Exception('Unkown result');
223
-        }
224
-    }
202
+	/**
203
+	 * Check 'result' exists and check for errors/status
204
+	 * @param \stdClass $result
205
+	 * @throws Exception 
206
+	 */
207
+	public function checkResultStatus(\stdClass $result) 
208
+	{
209
+		if (property_exists($result,'error') )
210
+		{
211
+			if (property_exists($result,'status'))
212
+			{
213
+				throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
214
+			}
215
+			else
216
+			{
217
+				throw new Exception('Ret code ' .$result->error.' : Unkown status');
218
+			}
219
+		}
220
+		if ( ! property_exists($result, 'results'))
221
+		{
222
+			throw new Exception('Unkown result');
223
+		}
224
+	}
225 225
     
226
-    /**
227
-     * Send request to API
228
-     * @param string $method get/post/...
229
-     * @param string $url (after /v1/ )
230
-     * @param array $headers
231
-     * @param array $body 
232
-     * @throws Exception
233
-     * @return array
234
-     */
235
-    public function request($method, $url, $headers, $body) {
236
-        $auth = sprintf('%s:%s', $this->user, $this->pass);
237
-        $curlHeaders = array("Accept: application/json");
238
-        if ($body !== null) {
239
-            $body = json_encode($body);
240
-            array_push($curlHeaders, 'Content-Type: application/json');
241
-            //array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
242
-        }
243
-        //var_dump($body);
244
-        //var_dump($this->url($url));
245
-        if ($headers !== null) {
246
-            $curlFinalHeaders = array_merge($curlHeaders, $headers);
247
-        } else 
248
-        {
249
-            $curlFinalHeaders=$curlHeaders;
250
-        }
251
-        $curl = $this->curl();
252
-        $opts = array(
253
-            CURLOPT_URL		=> $this->url($url),
254
-            CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
255
-            CURLOPT_USERPWD		=> $auth,
256
-            CURLOPT_CUSTOMREQUEST	=> strtoupper($method),
257
-            CURLOPT_RETURNTRANSFER 	=> true,
258
-            CURLOPT_CONNECTTIMEOUT 	=> 10,
259
-            CURLOPT_SSL_VERIFYHOST 	=> false,
260
-            CURLOPT_SSL_VERIFYPEER 	=> false,
261
-        );
262
-        if ($body !== null) {
263
-            $opts[CURLOPT_POSTFIELDS] = $body;
264
-        }
265
-        curl_setopt_array($curl, $opts);
266
-        $res = curl_exec($curl);
267
-        if ($res === false) {
268
-            throw new Exception('CURL ERROR: ' . curl_error($curl));
269
-        }
270
-        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
271
-        if ($statusCode === 401) {
272
-            throw new Exception('Unable to authenticate, please check your API credentials');
273
-        }
274
-        return $this->fromJsonResult($res);
275
-    }
226
+	/**
227
+	 * Send request to API
228
+	 * @param string $method get/post/...
229
+	 * @param string $url (after /v1/ )
230
+	 * @param array $headers
231
+	 * @param array $body 
232
+	 * @throws Exception
233
+	 * @return array
234
+	 */
235
+	public function request($method, $url, $headers, $body) {
236
+		$auth = sprintf('%s:%s', $this->user, $this->pass);
237
+		$curlHeaders = array("Accept: application/json");
238
+		if ($body !== null) {
239
+			$body = json_encode($body);
240
+			array_push($curlHeaders, 'Content-Type: application/json');
241
+			//array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
242
+		}
243
+		//var_dump($body);
244
+		//var_dump($this->url($url));
245
+		if ($headers !== null) {
246
+			$curlFinalHeaders = array_merge($curlHeaders, $headers);
247
+		} else 
248
+		{
249
+			$curlFinalHeaders=$curlHeaders;
250
+		}
251
+		$curl = $this->curl();
252
+		$opts = array(
253
+			CURLOPT_URL		=> $this->url($url),
254
+			CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
255
+			CURLOPT_USERPWD		=> $auth,
256
+			CURLOPT_CUSTOMREQUEST	=> strtoupper($method),
257
+			CURLOPT_RETURNTRANSFER 	=> true,
258
+			CURLOPT_CONNECTTIMEOUT 	=> 10,
259
+			CURLOPT_SSL_VERIFYHOST 	=> false,
260
+			CURLOPT_SSL_VERIFYPEER 	=> false,
261
+		);
262
+		if ($body !== null) {
263
+			$opts[CURLOPT_POSTFIELDS] = $body;
264
+		}
265
+		curl_setopt_array($curl, $opts);
266
+		$res = curl_exec($curl);
267
+		if ($res === false) {
268
+			throw new Exception('CURL ERROR: ' . curl_error($curl));
269
+		}
270
+		$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
271
+		if ($statusCode === 401) {
272
+			throw new Exception('Unable to authenticate, please check your API credentials');
273
+		}
274
+		return $this->fromJsonResult($res);
275
+	}
276 276
     
277
-    /**
278
-     * 
279
-     * @param string $json json encoded 
280
-     * @throws Exception
281
-     * @return array json decoded
282
-     */
283
-    protected function fromJsonResult($json) {
284
-        $result = @json_decode($json);
285
-        //var_dump($json);
286
-        if ($result === null) {
287
-            throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
288
-        }
289
-        return $result;
290
-    }
277
+	/**
278
+	 * 
279
+	 * @param string $json json encoded 
280
+	 * @throws Exception
281
+	 * @return array json decoded
282
+	 */
283
+	protected function fromJsonResult($json) {
284
+		$result = @json_decode($json);
285
+		//var_dump($json);
286
+		if ($result === null) {
287
+			throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
288
+		}
289
+		return $result;
290
+	}
291 291
     
292
-    /**
293
-     * Return text error no json error
294
-     * @param string $errorCode
295
-     * @return string
296
-     */
297
-    protected function getLastJsonErrorMessage($errorCode) {
298
-        if (!array_key_exists($errorCode, $this->errorReference)) {
299
-            return self::JSON_UNKNOWN_ERROR;
300
-        }
301
-        return $this->errorReference[$errorCode];
302
-    }
292
+	/**
293
+	 * Return text error no json error
294
+	 * @param string $errorCode
295
+	 * @return string
296
+	 */
297
+	protected function getLastJsonErrorMessage($errorCode) {
298
+		if (!array_key_exists($errorCode, $this->errorReference)) {
299
+			return self::JSON_UNKNOWN_ERROR;
300
+		}
301
+		return $this->errorReference[$errorCode];
302
+	}
303 303
 
304
-    public function standardQuery(string $urlType , string $filter, array $attributes)
305
-    {
306
-        /*
304
+	public function standardQuery(string $urlType , string $filter, array $attributes)
305
+	{
306
+		/*
307 307
          *  curl -k -s -u  trapdirector:trapdirector -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts'
308 308
          *  -d '{"filter":"host.group==\"test_trap\"","attrs": ["address" ,"address6"]}'
309 309
          
310 310
          {"results":[{"attrs":{"__name":"Icinga host","address":"127.0.0.1","display_name":"Icinga host","name":"Icinga host"},"joins":{},"meta":{},"name":"Icinga host","type":"Host"}]}
311 311
          */
312 312
         
313
-        if (! isset($this->queryURL[$urlType] ))
314
-        {
315
-            throw new Exception("Unkown object type");
316
-        }
317
-        $url=$this->queryURL[$urlType];
318
-        $body=array();
319
-        if ($filter !== NULL)
320
-        {
321
-            $body['filter'] = $filter;
322
-        }
323
-        if (count($attributes) != 0)
324
-        {
325
-            $body['attrs'] = $attributes;
326
-        }
313
+		if (! isset($this->queryURL[$urlType] ))
314
+		{
315
+			throw new Exception("Unkown object type");
316
+		}
317
+		$url=$this->queryURL[$urlType];
318
+		$body=array();
319
+		if ($filter !== NULL)
320
+		{
321
+			$body['filter'] = $filter;
322
+		}
323
+		if (count($attributes) != 0)
324
+		{
325
+			$body['attrs'] = $attributes;
326
+		}
327 327
 
328
-        try
329
-        {
330
-            $result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
331
-        } catch (Exception $e)
332
-        {
333
-            throw new Exception($e->getMessage());
334
-        }
328
+		try
329
+		{
330
+			$result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
331
+		} catch (Exception $e)
332
+		{
333
+			throw new Exception($e->getMessage());
334
+		}
335 335
         
336
-        $this->checkResultStatus($result);
336
+		$this->checkResultStatus($result);
337 337
         
338
-        $numHost=0;
339
-        $hostArray=array();
340
-        while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
341
-        {
342
-            $hostArray[$numHost] = $result->results[$numHost]->attrs;
343
-            $numHost++;
344
-        }
345
-        return $hostArray;
346
-    }
338
+		$numHost=0;
339
+		$hostArray=array();
340
+		while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
341
+		{
342
+			$hostArray[$numHost] = $result->results[$numHost]->attrs;
343
+			$numHost++;
344
+		}
345
+		return $hostArray;
346
+	}
347 347
     
348 348
 }
349 349
 
Please login to merge, or discard this patch.
library/Trapdirector/TrapsActions/IdoDBQuery.php 1 patch
Indentation   +222 added lines, -222 removed lines patch added patch discarded remove patch
@@ -18,247 +18,247 @@
 block discarded – undo
18 18
 trait IdoDBQuery
19 19
 {
20 20
 
21
-    /** @return TrapsController */
22
-    abstract protected function getTrapCtrl();
21
+	/** @return TrapsController */
22
+	abstract protected function getTrapCtrl();
23 23
     
24
-    /** @return Zend_Db_Adapter_Abstract : returns DB connexion or null on error */
25
-    abstract public function getIdoDbConn();
24
+	/** @return Zend_Db_Adapter_Abstract : returns DB connexion or null on error */
25
+	abstract public function getIdoDbConn();
26 26
     
27
-    /** Get host(s) by IP (v4 or v6) or by name in IDO database
28
-     *	does not catch exceptions
29
-     *	@return array of objects ( name, id (object_id), display_name)
30
-     */
31
-    public function getHostByIP($ip)
32
-    {
33
-        // select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
34
-        $dbConn = $this->getIdoDbConn();
35
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
27
+	/** Get host(s) by IP (v4 or v6) or by name in IDO database
28
+	 *	does not catch exceptions
29
+	 *	@return array of objects ( name, id (object_id), display_name)
30
+	 */
31
+	public function getHostByIP($ip)
32
+	{
33
+		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
34
+		$dbConn = $this->getIdoDbConn();
35
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
36 36
         
37
-        // TODO : check for SQL injections
38
-        $query=$dbConn->select()
39
-        ->from(
40
-            array('a' => 'icinga_objects'),
41
-            array('name' => 'a.name1','id' => 'object_id'))
42
-            ->join(
43
-                array('b' => 'icinga_hosts'),
44
-                'b.host_object_id=a.object_id',
45
-                array('display_name' => 'b.display_name'))
46
-                ->where("(b.address LIKE '%".$ip."%' OR b.address6 LIKE '%".$ip."%' OR a.name1 LIKE '%".$ip."%' OR b.display_name LIKE '%".$ip."%') and a.is_active = 1");
47
-                return $dbConn->fetchAll($query);
48
-    }
37
+		// TODO : check for SQL injections
38
+		$query=$dbConn->select()
39
+		->from(
40
+			array('a' => 'icinga_objects'),
41
+			array('name' => 'a.name1','id' => 'object_id'))
42
+			->join(
43
+				array('b' => 'icinga_hosts'),
44
+				'b.host_object_id=a.object_id',
45
+				array('display_name' => 'b.display_name'))
46
+				->where("(b.address LIKE '%".$ip."%' OR b.address6 LIKE '%".$ip."%' OR a.name1 LIKE '%".$ip."%' OR b.display_name LIKE '%".$ip."%') and a.is_active = 1");
47
+				return $dbConn->fetchAll($query);
48
+	}
49 49
     
50
-    /** Get host(s) by name in IDO database
51
-     *	does not catch exceptions
52
-     *	@return array of objects ( name, id (object_id), display_name)
53
-     */
54
-    public function getHostByName($name)
55
-    {
56
-        // select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
57
-        $dbConn = $this->getIdoDbConn();
58
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
50
+	/** Get host(s) by name in IDO database
51
+	 *	does not catch exceptions
52
+	 *	@return array of objects ( name, id (object_id), display_name)
53
+	 */
54
+	public function getHostByName($name)
55
+	{
56
+		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
57
+		$dbConn = $this->getIdoDbConn();
58
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
59 59
         
60
-        // TODO : check for SQL injections
61
-        $query=$dbConn->select()
62
-        ->from(
63
-            array('a' => 'icinga_objects'),
64
-            array('name' => 'a.name1','id' => 'object_id'))
65
-            ->join(
66
-                array('b' => 'icinga_hosts'),
67
-                'b.host_object_id=a.object_id',
68
-                array('display_name' => 'b.display_name'))
69
-                ->where("a.name1 = '$name'");
70
-         return $dbConn->fetchAll($query);
71
-    }
60
+		// TODO : check for SQL injections
61
+		$query=$dbConn->select()
62
+		->from(
63
+			array('a' => 'icinga_objects'),
64
+			array('name' => 'a.name1','id' => 'object_id'))
65
+			->join(
66
+				array('b' => 'icinga_hosts'),
67
+				'b.host_object_id=a.object_id',
68
+				array('display_name' => 'b.display_name'))
69
+				->where("a.name1 = '$name'");
70
+		 return $dbConn->fetchAll($query);
71
+	}
72 72
     
73
-    /** Get host groups by  name in IDO database
74
-     *	does not catch exceptions
75
-     *	@return array of objects ( name, id (object_id), display_name)
76
-     */
77
-    public function getHostGroupByName($ip)
78
-    {
79
-        // select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
80
-        $dbConn = $this->getIdoDbConn();
81
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
82
-        // TODO : check for SQL injections
83
-        $query=$dbConn->select()
84
-        ->from(
85
-            array('a' => 'icinga_objects'),
86
-            array('name' => 'a.name1','id' => 'object_id'))
87
-            ->join(
88
-                array('b' => 'icinga_hostgroups'),
89
-                'b.hostgroup_object_id=a.object_id',
90
-                array('display_name' => 'b.alias'))
91
-                ->where("(a.name1 LIKE '%".$ip."%' OR b.alias LIKE '%".$ip."%') and a.is_active = 1");
92
-                return $dbConn->fetchAll($query);
93
-    }
73
+	/** Get host groups by  name in IDO database
74
+	 *	does not catch exceptions
75
+	 *	@return array of objects ( name, id (object_id), display_name)
76
+	 */
77
+	public function getHostGroupByName($ip)
78
+	{
79
+		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
80
+		$dbConn = $this->getIdoDbConn();
81
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
82
+		// TODO : check for SQL injections
83
+		$query=$dbConn->select()
84
+		->from(
85
+			array('a' => 'icinga_objects'),
86
+			array('name' => 'a.name1','id' => 'object_id'))
87
+			->join(
88
+				array('b' => 'icinga_hostgroups'),
89
+				'b.hostgroup_object_id=a.object_id',
90
+				array('display_name' => 'b.alias'))
91
+				->where("(a.name1 LIKE '%".$ip."%' OR b.alias LIKE '%".$ip."%') and a.is_active = 1");
92
+				return $dbConn->fetchAll($query);
93
+	}
94 94
  
95
-    /** Get host IP (v4 and v6) by name in IDO database
96
-     *	does not catch exceptions
97
-     *	@return array ( name, display_name, ip4, ip6)
98
-     */
99
-    public function getHostInfoByID($id)
100
-    {
101
-        if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
102
-        $dbConn = $this->getIdoDbConn();
103
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
104
-        $query=$dbConn->select()
105
-        ->from(
106
-            array('a' => 'icinga_objects'),
107
-            array('name' => 'a.name1'))
108
-            ->join(
109
-                array('b' => 'icinga_hosts'),
110
-                'b.host_object_id=a.object_id',
111
-                array('ip4' => 'b.address', 'ip6' => 'b.address6', 'display_name' => 'b.display_name'))
112
-                ->where("a.object_id = '".$id."'");
113
-                return $dbConn->fetchRow($query);
114
-    }
95
+	/** Get host IP (v4 and v6) by name in IDO database
96
+	 *	does not catch exceptions
97
+	 *	@return array ( name, display_name, ip4, ip6)
98
+	 */
99
+	public function getHostInfoByID($id)
100
+	{
101
+		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
102
+		$dbConn = $this->getIdoDbConn();
103
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
104
+		$query=$dbConn->select()
105
+		->from(
106
+			array('a' => 'icinga_objects'),
107
+			array('name' => 'a.name1'))
108
+			->join(
109
+				array('b' => 'icinga_hosts'),
110
+				'b.host_object_id=a.object_id',
111
+				array('ip4' => 'b.address', 'ip6' => 'b.address6', 'display_name' => 'b.display_name'))
112
+				->where("a.object_id = '".$id."'");
113
+				return $dbConn->fetchRow($query);
114
+	}
115 115
         
116
-    /** Get host by objectid  in IDO database
117
-     *	does not catch exceptions
118
-     *	@return array of objects ( id, name, display_name, ip, ip6,  )
119
-     */
120
-    public function getHostByObjectID($id) // TODO : duplicate of getHostInfoByID above
121
-    {
122
-        if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
123
-        $dbConn = $this->getIdoDbConn();
124
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
125
-        $query=$dbConn->select()
126
-        ->from(
127
-            array('a' => 'icinga_objects'),
128
-            array('name' => 'a.name1','id' => 'a.object_id'))
129
-            ->join(
130
-                array('b' => 'icinga_hosts'),
131
-                'b.host_object_id=a.object_id',
132
-                array('display_name' => 'b.display_name' , 'ip' => 'b.address', 'ip6' => 'b.address6'))
133
-                ->where('a.object_id = ?',$id);
134
-                return $dbConn->fetchRow($query);
135
-    }
116
+	/** Get host by objectid  in IDO database
117
+	 *	does not catch exceptions
118
+	 *	@return array of objects ( id, name, display_name, ip, ip6,  )
119
+	 */
120
+	public function getHostByObjectID($id) // TODO : duplicate of getHostInfoByID above
121
+	{
122
+		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
123
+		$dbConn = $this->getIdoDbConn();
124
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
125
+		$query=$dbConn->select()
126
+		->from(
127
+			array('a' => 'icinga_objects'),
128
+			array('name' => 'a.name1','id' => 'a.object_id'))
129
+			->join(
130
+				array('b' => 'icinga_hosts'),
131
+				'b.host_object_id=a.object_id',
132
+				array('display_name' => 'b.display_name' , 'ip' => 'b.address', 'ip6' => 'b.address6'))
133
+				->where('a.object_id = ?',$id);
134
+				return $dbConn->fetchRow($query);
135
+	}
136 136
     
137
-    /** Get services from object ( host_object_id) in IDO database
138
-     *	does not catch exceptions
139
-     *	@param $id	int object_id
140
-     *	@return array display_name (of service), service_object_id
141
-     */
142
-    public function getServicesByHostid($id)
143
-    {
144
-        // select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
145
-        if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
146
-        $dbConn = $this->getIdoDbConn();
147
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
148
-        $query=$dbConn->select()
149
-        ->from(
150
-            array('s' => 'icinga_services'),
151
-            array('name' => 's.display_name','id' => 's.service_object_id'))
152
-            ->join(
153
-                array('a' => 'icinga_objects'),
154
-                's.service_object_id=a.object_id',
155
-                array('is_active'=>'a.is_active','name2'=>'a.name2'))
156
-                ->where('s.host_object_id='.$id.' AND a.is_active = 1');
157
-                return $dbConn->fetchAll($query);
158
-    }
137
+	/** Get services from object ( host_object_id) in IDO database
138
+	 *	does not catch exceptions
139
+	 *	@param $id	int object_id
140
+	 *	@return array display_name (of service), service_object_id
141
+	 */
142
+	public function getServicesByHostid($id)
143
+	{
144
+		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
145
+		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
146
+		$dbConn = $this->getIdoDbConn();
147
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
148
+		$query=$dbConn->select()
149
+		->from(
150
+			array('s' => 'icinga_services'),
151
+			array('name' => 's.display_name','id' => 's.service_object_id'))
152
+			->join(
153
+				array('a' => 'icinga_objects'),
154
+				's.service_object_id=a.object_id',
155
+				array('is_active'=>'a.is_active','name2'=>'a.name2'))
156
+				->where('s.host_object_id='.$id.' AND a.is_active = 1');
157
+				return $dbConn->fetchAll($query);
158
+	}
159 159
     
160
-    /** Get services from hostgroup object id ( hostgroup_object_id) in IDO database
161
-     * 	gets all hosts in hostgroup and return common services
162
-     *	does not catch exceptions
163
-     *	@param $id	int object_id
164
-     *	@return array display_name (of service), service_object_id
165
-     */
166
-    public function getServicesByHostGroupid($id)
167
-    {
168
-        if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
169
-        $dbConn = $this->getIdoDbConn();
170
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
171
-        $query=$dbConn->select()
172
-        ->from(
173
-            array('s' => 'icinga_hostgroup_members'),
174
-            array('host_object_id' => 's.host_object_id'))
175
-            ->join(
176
-                array('a' => 'icinga_hostgroups'),
177
-                's.hostgroup_id=a.hostgroup_id',
178
-                'hostgroup_object_id')
179
-                ->where('a.hostgroup_object_id='.$id);
180
-                $hosts=$dbConn->fetchAll($query);
181
-                $common_services=array();
182
-                $num_hosts=count($hosts);
183
-                foreach ($hosts as $key => $host)
184
-                { // For each host, get all services and add in common_services if not found or add counter
185
-                    $host_services=$this->getServicesByHostid($host->host_object_id);
186
-                    foreach($host_services as $service)
187
-                    {
188
-                        if (isset($common_services[$service->name2]['num']))
189
-                        {
190
-                            $common_services[$service->name2]['num'] +=1;
191
-                        }
192
-                        else
193
-                        {
194
-                            $common_services[$service->name2]['num']=1;
195
-                            $common_services[$service->name2]['name']=$service->name;
196
-                        }
197
-                    }
198
-                }
199
-                $result=array();
160
+	/** Get services from hostgroup object id ( hostgroup_object_id) in IDO database
161
+	 * 	gets all hosts in hostgroup and return common services
162
+	 *	does not catch exceptions
163
+	 *	@param $id	int object_id
164
+	 *	@return array display_name (of service), service_object_id
165
+	 */
166
+	public function getServicesByHostGroupid($id)
167
+	{
168
+		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
169
+		$dbConn = $this->getIdoDbConn();
170
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
171
+		$query=$dbConn->select()
172
+		->from(
173
+			array('s' => 'icinga_hostgroup_members'),
174
+			array('host_object_id' => 's.host_object_id'))
175
+			->join(
176
+				array('a' => 'icinga_hostgroups'),
177
+				's.hostgroup_id=a.hostgroup_id',
178
+				'hostgroup_object_id')
179
+				->where('a.hostgroup_object_id='.$id);
180
+				$hosts=$dbConn->fetchAll($query);
181
+				$common_services=array();
182
+				$num_hosts=count($hosts);
183
+				foreach ($hosts as $key => $host)
184
+				{ // For each host, get all services and add in common_services if not found or add counter
185
+					$host_services=$this->getServicesByHostid($host->host_object_id);
186
+					foreach($host_services as $service)
187
+					{
188
+						if (isset($common_services[$service->name2]['num']))
189
+						{
190
+							$common_services[$service->name2]['num'] +=1;
191
+						}
192
+						else
193
+						{
194
+							$common_services[$service->name2]['num']=1;
195
+							$common_services[$service->name2]['name']=$service->name;
196
+						}
197
+					}
198
+				}
199
+				$result=array();
200 200
                 
201
-                //print_r($common_services);
202
-                foreach (array_keys($common_services) as $key)
203
-                {
204
-                    if ($common_services[$key]['num'] == $num_hosts)
205
-                    {
206
-                        array_push($result,array($key,$common_services[$key]['name']));
207
-                    }
208
-                }
201
+				//print_r($common_services);
202
+				foreach (array_keys($common_services) as $key)
203
+				{
204
+					if ($common_services[$key]['num'] == $num_hosts)
205
+					{
206
+						array_push($result,array($key,$common_services[$key]['name']));
207
+					}
208
+				}
209 209
                 
210
-                return $result;
211
-    }
210
+				return $result;
211
+	}
212 212
     
213
-    /** Get services object id by host name / service name in IDO database
214
-     *	does not catch exceptions
215
-     *	@param $hostname string host name
216
-     *	@param $name string service name
217
-     *	@return array  service id
218
-     */
219
-    public function getServiceIDByName($hostname,$name)
220
-    {
221
-        $dbConn = $this->getIdoDbConn();
222
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
213
+	/** Get services object id by host name / service name in IDO database
214
+	 *	does not catch exceptions
215
+	 *	@param $hostname string host name
216
+	 *	@param $name string service name
217
+	 *	@return array  service id
218
+	 */
219
+	public function getServiceIDByName($hostname,$name)
220
+	{
221
+		$dbConn = $this->getIdoDbConn();
222
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
223 223
         
224
-        if ($name == null)
225
-        {
226
-            return array();
227
-        }
224
+		if ($name == null)
225
+		{
226
+			return array();
227
+		}
228 228
         
229
-        $query=$dbConn->select()
230
-        ->from(
231
-            array('s' => 'icinga_services'),
232
-            array('name' => 's.display_name','id' => 's.service_object_id'))
233
-            ->join(
234
-                array('a' => 'icinga_objects'),
235
-                's.service_object_id=a.object_id',
236
-                'is_active')
237
-                ->where('a.name2=\''.$name.'\' AND a.name1=\''.$hostname.'\' AND a.is_active = 1');
229
+		$query=$dbConn->select()
230
+		->from(
231
+			array('s' => 'icinga_services'),
232
+			array('name' => 's.display_name','id' => 's.service_object_id'))
233
+			->join(
234
+				array('a' => 'icinga_objects'),
235
+				's.service_object_id=a.object_id',
236
+				'is_active')
237
+				->where('a.name2=\''.$name.'\' AND a.name1=\''.$hostname.'\' AND a.is_active = 1');
238 238
                 
239
-                return $dbConn->fetchAll($query);
240
-    }
239
+				return $dbConn->fetchAll($query);
240
+	}
241 241
     
242
-    /** Get object name from object_id  in IDO database
243
-     *	does not catch exceptions
244
-     *	@param int $id object_id (default to null, used first if not null)
245
-     *	@return array name1 (host) name2 (service)
246
-     */
247
-    public function getObjectNameByid($id)
248
-    {
249
-        // select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
250
-        if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
251
-        $dbConn = $this->getIdoDbConn();
252
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
242
+	/** Get object name from object_id  in IDO database
243
+	 *	does not catch exceptions
244
+	 *	@param int $id object_id (default to null, used first if not null)
245
+	 *	@return array name1 (host) name2 (service)
246
+	 */
247
+	public function getObjectNameByid($id)
248
+	{
249
+		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
250
+		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
251
+		$dbConn = $this->getIdoDbConn();
252
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
253 253
         
254
-        $query=$dbConn->select()
255
-        ->from(
256
-            array('a' => 'icinga_objects'),
257
-            array('name1' => 'a.name1','name2' => 'a.name2'))
258
-            ->where('a.object_id='.$id.' AND a.is_active = 1');
254
+		$query=$dbConn->select()
255
+		->from(
256
+			array('a' => 'icinga_objects'),
257
+			array('name1' => 'a.name1','name2' => 'a.name2'))
258
+			->where('a.object_id='.$id.' AND a.is_active = 1');
259 259
             
260
-            return $dbConn->fetchRow($query);
261
-    }
260
+			return $dbConn->fetchRow($query);
261
+	}
262 262
     
263 263
     
264 264
 }
265 265
\ No newline at end of file
Please login to merge, or discard this patch.
configuration.php 1 patch
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -6,8 +6,8 @@
 block discarded – undo
6 6
 $this->providePermission('trapdirector/config', $this->translate('Allow to create and modify traps services'));
7 7
 
8 8
 $this->provideConfigTab('config', array(
9
-    'title' => 'Configuration',
10
-    'url'   => 'settings'
9
+	'title' => 'Configuration',
10
+	'url'   => 'settings'
11 11
 ));
12 12
 
13 13
 /**
Please login to merge, or discard this patch.
application/controllers/StatusController.php 1 patch
Indentation   +187 added lines, -187 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
 			}
@@ -172,16 +172,16 @@  discard block
 block discarded – undo
172 172
 			$translate=exec($snmptranslate . ' 1');
173 173
 			if (preg_match('/iso/',$translate))
174 174
 			{
175
-			    $translate=exec($snmptranslate . ' 1.3.6.1.4');
176
-			    if (preg_match('/private/',$translate))
177
-			    {		    
178
-    				$this->view->snmptranslate='works fine';
179
-    				$this->view->snmptranslate_state='ok';
180
-			    }
181
-			    else
182
-			    {
183
-			        $this->view->snmptranslate='works fine but missing basic MIBs';
184
-			    }
175
+				$translate=exec($snmptranslate . ' 1.3.6.1.4');
176
+				if (preg_match('/private/',$translate))
177
+				{		    
178
+					$this->view->snmptranslate='works fine';
179
+					$this->view->snmptranslate_state='ok';
180
+				}
181
+				else
182
+				{
183
+					$this->view->snmptranslate='works fine but missing basic MIBs';
184
+				}
185 185
 			}
186 186
 			else
187 187
 			{
@@ -244,63 +244,63 @@  discard block
 block discarded – undo
244 244
 	/** UI options */
245 245
 	public function uimgtAction()
246 246
 	{
247
-	    $this->prepareTabs()->activate('uimgt');
247
+		$this->prepareTabs()->activate('uimgt');
248 248
 	    
249
-	    $this->view->setError='';
250
-	    $this->view->setOKMsg='';
249
+		$this->view->setError='';
250
+		$this->view->setOKMsg='';
251 251
 	    
252
-	    //max_rows=25&row_update=update
253
-	    if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
254
-	    {
255
-	        $maxRows = $this->getRequest()->getParam('max_rows');
256
-	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257
-	        {
258
-	            $this->view->setError='Max rows must be a number';
259
-	        }
260
-	        else
261
-	        {
262
-	            $this->setitemListDisplay($maxRows);
263
-	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
264
-	        }
265
-	    }
252
+		//max_rows=25&row_update=update
253
+		if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
254
+		{
255
+			$maxRows = $this->getRequest()->getParam('max_rows');
256
+			if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257
+			{
258
+				$this->view->setError='Max rows must be a number';
259
+			}
260
+			else
261
+			{
262
+				$this->setitemListDisplay($maxRows);
263
+				$this->view->setOKMsg='Set max rows to ' . $maxRows;
264
+			}
265
+		}
266 266
 	    
267
-	    if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
268
-	    {
269
-	        $addCat = $this->getRequest()->getParam('add_category');
270
-            $this->addHandlersCategory($addCat);
271
-	    }
267
+		if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
268
+		{
269
+			$addCat = $this->getRequest()->getParam('add_category');
270
+			$this->addHandlersCategory($addCat);
271
+		}
272 272
 	    
273
-	    if ( $this->getRequest()->getPost('type',NULL) !== NULL )
274
-	    {
275
-	        $type = $this->getRequest()->getPost('type',NULL);
276
-	        $index = $this->getRequest()->getPost('index',NULL);
277
-	        $newname = $this->getRequest()->getPost('newname',NULL);
273
+		if ( $this->getRequest()->getPost('type',NULL) !== NULL )
274
+		{
275
+			$type = $this->getRequest()->getPost('type',NULL);
276
+			$index = $this->getRequest()->getPost('index',NULL);
277
+			$newname = $this->getRequest()->getPost('newname',NULL);
278 278
 
279
-	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280
-	            $this->_helper->json(array('status'=>'Bad index'));
279
+			if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280
+				$this->_helper->json(array('status'=>'Bad index'));
281 281
 	        
282
-	        switch ($type)
283
-	        {
284
-	            case 'delete':
285
-	                $this->delHandlersCategory($index);
286
-	                $this->_helper->json(array('status'=>'OK'));
287
-	                return;
288
-	                break;
289
-	            case 'rename':
290
-	                $this->renameHandlersCategory($index, $newname);
291
-	                $this->_helper->json(array('status'=>'OK'));
292
-	                return;
293
-	                break;
294
-	            default:
295
-	                $this->_helper->json(array('status'=>'Unknwon command'));
296
-	                return;
297
-	                break;
298
-	        }
299
-	    }
282
+			switch ($type)
283
+			{
284
+				case 'delete':
285
+					$this->delHandlersCategory($index);
286
+					$this->_helper->json(array('status'=>'OK'));
287
+					return;
288
+					break;
289
+				case 'rename':
290
+					$this->renameHandlersCategory($index, $newname);
291
+					$this->_helper->json(array('status'=>'OK'));
292
+					return;
293
+					break;
294
+				default:
295
+					$this->_helper->json(array('status'=>'Unknwon command'));
296
+					return;
297
+					break;
298
+			}
299
+		}
300 300
 	    
301
-	    $this->view->maxRows = $this->itemListDisplay();
301
+		$this->view->maxRows = $this->itemListDisplay();
302 302
 	    
303
-	    $this->view->categories = $this->getHandlersCategory();
303
+		$this->view->categories = $this->getHandlersCategory();
304 304
 	    
305 305
 	    
306 306
 	    
@@ -349,47 +349,47 @@  discard block
 block discarded – undo
349 349
 	 */
350 350
 	public function pluginsAction()
351 351
 	{
352
-	    $this->prepareTabs()->activate('plugins');
352
+		$this->prepareTabs()->activate('plugins');
353 353
 	    
354
-	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
355
-	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
356
-	    $Trap = new Trap($icingaweb2_etc,4);
354
+		require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
355
+		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
356
+		$Trap = new Trap($icingaweb2_etc,4);
357 357
 	    
358
-	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
358
+		$this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
359 359
 	    
360
-	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
360
+		$enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
361 361
 
362
-	    $pluginList = $Trap->pluginClass->pluginList();
362
+		$pluginList = $Trap->pluginClass->pluginList();
363 363
 	    
364
-	    // Plugin list and fill function name list
365
-	    $functionList=array();
366
-	    $this->view->pluginArray=array();
367
-	    foreach ($pluginList as $plugin)
368
-	    {
369
-	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
370
-	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
371
-	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
372
-	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
373
-	        $pluginDetails->description = htmlentities($pluginDetails->description);
374
-	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
375
-	        array_push($this->view->pluginArray, $pluginDetails);
376
-	        // Get functions for function details
377
-	        foreach ($pluginDetails->funcArray as $function)
378
-	        {
379
-	            array_push($functionList,$function);
380
-	        }
381
-	    }
364
+		// Plugin list and fill function name list
365
+		$functionList=array();
366
+		$this->view->pluginArray=array();
367
+		foreach ($pluginList as $plugin)
368
+		{
369
+			$pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
370
+			$pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
371
+			$pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
372
+			$pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
373
+			$pluginDetails->description = htmlentities($pluginDetails->description);
374
+			$pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
375
+			array_push($this->view->pluginArray, $pluginDetails);
376
+			// Get functions for function details
377
+			foreach ($pluginDetails->funcArray as $function)
378
+			{
379
+				array_push($functionList,$function);
380
+			}
381
+		}
382 382
 	    
383
-	    // Function list with details
384
-	    $this->view->functionList=array();
385
-	    foreach ($functionList as $function)
386
-	    {
387
-	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
388
-	        $functionDetail->params = htmlentities($functionDetail->params);
389
-	        $functionDetail->description = htmlentities($functionDetail->description);
390
-	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
391
-	        array_push($this->view->functionList, $functionDetail);
392
-	    }
383
+		// Function list with details
384
+		$this->view->functionList=array();
385
+		foreach ($functionList as $function)
386
+		{
387
+			$functionDetail = $Trap->pluginClass->getFunctionDetails($function);
388
+			$functionDetail->params = htmlentities($functionDetail->params);
389
+			$functionDetail->description = htmlentities($functionDetail->description);
390
+			$functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
391
+			array_push($this->view->functionList, $functionDetail);
392
+		}
393 393
 
394 394
 	}
395 395
 
@@ -398,47 +398,47 @@  discard block
 block discarded – undo
398 398
 	 */
399 399
 	public function debugAction()
400 400
 	{
401
-	    $this->view->answer='No answer';
402
-	    $this->view->input1 = '';
401
+		$this->view->answer='No answer';
402
+		$this->view->input1 = '';
403 403
 	    
404
-	    $postData=$this->getRequest()->getPost();
405
-	    if (isset($postData['input1']))
406
-	    {
407
-	        $input1 = $postData['input1'];
408
-	        $input2 = $postData['input2'];
409
-	        $input3 = $postData['input3'];
410
-	        $this->view->input1 = $input1;
411
-	        //$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
412
-	        try {
413
-	            $this->view->answer = 'Answer : ';
414
-	            $API = $this->getIdoConn();
415
-	            $DB = $this->getUIDatabase();
404
+		$postData=$this->getRequest()->getPost();
405
+		if (isset($postData['input1']))
406
+		{
407
+			$input1 = $postData['input1'];
408
+			$input2 = $postData['input2'];
409
+			$input3 = $postData['input3'];
410
+			$this->view->input1 = $input1;
411
+			//$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
412
+			try {
413
+				$this->view->answer = 'Answer : ';
414
+				$API = $this->getIdoConn();
415
+				$DB = $this->getUIDatabase();
416 416
 
417
-	            //$hosts = $DB->getServicesByHostGroupid($input1);
418
-	            //$this->view->answer .= 'services : '.print_r($hosts,true);
417
+				//$hosts = $DB->getServicesByHostGroupid($input1);
418
+				//$this->view->answer .= 'services : '.print_r($hosts,true);
419 419
 	            
420
-	            $hosts = $API->getServicesByHostGroupid($input1);
421
-	            $this->view->answer .= 'services : '.print_r($hosts,true);
420
+				$hosts = $API->getServicesByHostGroupid($input1);
421
+				$this->view->answer .= 'services : '.print_r($hosts,true);
422 422
 	            
423 423
 
424 424
 	            
425
-	            return;
426
-	            $hosts = $API->getHostByIP($input1);
427
-	            $this->view->answer .= 'Host : '. print_r($hosts,true);
428
-	            $hosts = $API->getHostGroupByName($input1);
429
-	            $this->view->answer .= 'Group : '.print_r($hosts,true);
430
-	            $hosts = $API->getServicesByHostid($input1);
431
-	            $this->view->answer .= 'service : '.print_r($hosts,true);
425
+				return;
426
+				$hosts = $API->getHostByIP($input1);
427
+				$this->view->answer .= 'Host : '. print_r($hosts,true);
428
+				$hosts = $API->getHostGroupByName($input1);
429
+				$this->view->answer .= 'Group : '.print_r($hosts,true);
430
+				$hosts = $API->getServicesByHostid($input1);
431
+				$this->view->answer .= 'service : '.print_r($hosts,true);
432 432
 	            
433
-	            /* $hosts = $API->getHostsIPByHostGroup($input1);
433
+				/* $hosts = $API->getHostsIPByHostGroup($input1);
434 434
 	            $this->view->answer .= "\n Hostgrp : " . print_r($hosts,true); */
435 435
 	            
436
-	        } catch (Exception $e)
437
-	        {
438
-	            $this->view->answer = "Exception : " . print_r($e);
439
-	        }
436
+			} catch (Exception $e)
437
+			{
438
+				$this->view->answer = "Exception : " . print_r($e);
439
+			}
440 440
 	        
441
-	    }
441
+		}
442 442
 	    
443 443
 	}
444 444
 	
@@ -450,36 +450,36 @@  discard block
 block discarded – undo
450 450
 		)->add('mib', array(
451 451
 			'label' => $this->translate('MIB Management'),
452 452
 			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
453
-	    )->add('uimgt', array(
454
-	        'label' => $this->translate('UI Configuration'),
455
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
456
-        )->add('services', array(
453
+		)->add('uimgt', array(
454
+			'label' => $this->translate('UI Configuration'),
455
+			'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
456
+		)->add('services', array(
457 457
 			'label' => $this->translate('Services management'),
458 458
 			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
459
-	    )->add('plugins', array(
460
-	        'label' => $this->translate('Plugins management'),
461
-	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
462
-	    );
459
+		)->add('plugins', array(
460
+			'label' => $this->translate('Plugins management'),
461
+			'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
462
+		);
463 463
 	} 
464 464
 }
465 465
 
466 466
 // TODO : see if useless 
467 467
 class UploadForm extends Form
468 468
 { 
469
-    public function __construct($options = null) 
470
-    {
471
-        parent::__construct($options);
472
-        $this->addElements2();
473
-    }
469
+	public function __construct($options = null) 
470
+	{
471
+		parent::__construct($options);
472
+		$this->addElements2();
473
+	}
474 474
 
475
-    public function addElements2()
476
-    {
477
-        // File Input
478
-        $file = new File('mib-file');
479
-        $file->setLabel('Mib upload');
480
-             //->setAttrib('multiple', null);
481
-        $this->addElement($file);
475
+	public function addElements2()
476
+	{
477
+		// File Input
478
+		$file = new File('mib-file');
479
+		$file->setLabel('Mib upload');
480
+			 //->setAttrib('multiple', null);
481
+		$this->addElement($file);
482 482
 		$button = new Submit("upload",array('ignore'=>false));
483 483
 		$this->addElement($button);//->setIgnore(false);
484
-    }
484
+	}
485 485
 }
Please login to merge, or discard this patch.
application/controllers/SettingsController.php 1 patch
Indentation   +231 added lines, -231 removed lines patch added patch discarded remove patch
@@ -25,16 +25,16 @@  discard block
 block discarded – undo
25 25
    */
26 26
   private function get_param()
27 27
   {
28
-      $dberrorMsg=$this->params->get('dberror');
29
-      if ($dberrorMsg != '')
30
-      {
31
-          $this->view->errorDetected=$dberrorMsg;
32
-      }
33
-      $dberrorMsg=$this->params->get('idodberror');
34
-      if ($dberrorMsg != '')
35
-      {
36
-          $this->view->errorDetected=$dberrorMsg;
37
-      }
28
+	  $dberrorMsg=$this->params->get('dberror');
29
+	  if ($dberrorMsg != '')
30
+	  {
31
+		  $this->view->errorDetected=$dberrorMsg;
32
+	  }
33
+	  $dberrorMsg=$this->params->get('idodberror');
34
+	  if ($dberrorMsg != '')
35
+	  {
36
+		  $this->view->errorDetected=$dberrorMsg;
37
+	  }
38 38
   }
39 39
   
40 40
   /**
@@ -43,22 +43,22 @@  discard block
 block discarded – undo
43 43
    */
44 44
   private function check_empty_config()
45 45
   {
46
-      $this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
47
-      if ($this->Config()->isEmpty() == true)
48
-      {
49
-          $this->Config()->setSection('config'); // Set base config section.
50
-          try
51
-          {
52
-              $this->Config()->saveIni();
53
-              $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54
-              //$emptyConfig=1;
55
-          }
56
-          catch (Exception $e)
57
-          {
58
-              $this->view->configErrorDetected=$e->getMessage();
59
-          }
46
+	  $this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
47
+	  if ($this->Config()->isEmpty() == true)
48
+	  {
49
+		  $this->Config()->setSection('config'); // Set base config section.
50
+		  try
51
+		  {
52
+			  $this->Config()->saveIni();
53
+			  $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54
+			  //$emptyConfig=1;
55
+		  }
56
+		  catch (Exception $e)
57
+		  {
58
+			  $this->view->configErrorDetected=$e->getMessage();
59
+		  }
60 60
           
61
-      }
61
+	  }
62 62
   }
63 63
   
64 64
   /**
@@ -71,56 +71,56 @@  discard block
 block discarded – undo
71 71
    */
72 72
   private function check_db()
73 73
   {
74
-      $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
-          0	=>	array('Database configuration OK','',''),
76
-          1	=>	array('Database set in config.ini','No database in config.ini',''),
77
-          2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
78
-              Url::fromPath('config/resource')),
79
-          3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
80
-              Url::fromPath('trapdirector/settings/createschema')),
81
-          4	=>	array('Schema is set','Schema is not set for ',
82
-              Url::fromPath('trapdirector/settings/createschema')),
83
-          5	=>	array('Schema is up to date','Schema is outdated :',
84
-              Url::fromPath('trapdirector/settings/updateschema')),
85
-      );
74
+	  $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
+		  0	=>	array('Database configuration OK','',''),
76
+		  1	=>	array('Database set in config.ini','No database in config.ini',''),
77
+		  2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
78
+			  Url::fromPath('config/resource')),
79
+		  3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
80
+			  Url::fromPath('trapdirector/settings/createschema')),
81
+		  4	=>	array('Schema is set','Schema is not set for ',
82
+			  Url::fromPath('trapdirector/settings/createschema')),
83
+		  5	=>	array('Schema is up to date','Schema is outdated :',
84
+			  Url::fromPath('trapdirector/settings/updateschema')),
85
+	  );
86 86
       
87
-      try {
88
-          $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
-          $dberror=array(0,'');
90
-      } catch (DBException $e) {
91
-          $dberror = $e->getArray();
92
-      }
87
+	  try {
88
+		  $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
+		  $dberror=array(0,'');
90
+	  } catch (DBException $e) {
91
+		  $dberror = $e->getArray();
92
+	  }
93 93
       
94
-      $this->view->db_error=$dberror[0];
95
-      switch ($dberror[0])
96
-      {
97
-          case 2:
98
-          case 4:
99
-              $db_message[$dberror[0]][1] .= $dberror[1];
100
-              break;
101
-          case 3:
102
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
103
-              break;
104
-          case 5:
105
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
106
-              break;
107
-          case 0:
108
-          case 1:
109
-              break;
110
-          default:
111
-              new ProgrammingError('Out of bond result from database test');
112
-      }
113
-      $this->view->message=$db_message;
94
+	  $this->view->db_error=$dberror[0];
95
+	  switch ($dberror[0])
96
+	  {
97
+		  case 2:
98
+		  case 4:
99
+			  $db_message[$dberror[0]][1] .= $dberror[1];
100
+			  break;
101
+		  case 3:
102
+			  $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
103
+			  break;
104
+		  case 5:
105
+			  $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
106
+			  break;
107
+		  case 0:
108
+		  case 1:
109
+			  break;
110
+		  default:
111
+			  new ProgrammingError('Out of bond result from database test');
112
+	  }
113
+	  $this->view->message=$db_message;
114 114
       
115
-      try {
116
-          $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
-          $dberror=array(0,'');
118
-      } catch (DBException $e) {
119
-          $dberror = $e->getArray();
120
-      }
115
+	  try {
116
+		  $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
+		  $dberror=array(0,'');
118
+	  } catch (DBException $e) {
119
+		  $dberror = $e->getArray();
120
+	  }
121 121
       
122
-      $this->view->ido_db_error=$dberror[0];
123
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
122
+	  $this->view->ido_db_error=$dberror[0];
123
+	  $this->view->ido_message='IDO Database : ' . $dberror[1];
124 124
   }
125 125
   
126 126
   /**
@@ -130,23 +130,23 @@  discard block
 block discarded – undo
130 130
    */
131 131
   private function check_api()
132 132
   {
133
-      if ($this->Config()->get('config', 'icingaAPI_host') != '')
134
-      {
135
-          $apitest=new Icinga2API($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
136
-          $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
137
-          try {
138
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
139
-              //$this->view->apimessageError=false;
140
-          } catch (RuntimeException $e) {
141
-              $this->view->apimessage='API config : ' . $e->getMessage();
142
-              $this->view->apimessageError=true;
143
-          }
144
-      }
145
-      else
146
-      {
147
-          $this->view->apimessage='API parameters not configured';
148
-          $this->view->apimessageError=true;
149
-      }
133
+	  if ($this->Config()->get('config', 'icingaAPI_host') != '')
134
+	  {
135
+		  $apitest=new Icinga2API($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
136
+		  $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
137
+		  try {
138
+			  list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
139
+			  //$this->view->apimessageError=false;
140
+		  } catch (RuntimeException $e) {
141
+			  $this->view->apimessage='API config : ' . $e->getMessage();
142
+			  $this->view->apimessageError=true;
143
+		  }
144
+	  }
145
+	  else
146
+	  {
147
+		  $this->view->apimessage='API parameters not configured';
148
+		  $this->view->apimessageError=true;
149
+	  }
150 150
   }
151 151
 
152 152
   /**
@@ -157,21 +157,21 @@  discard block
 block discarded – undo
157 157
    */
158 158
   private function check_icingaweb_path()
159 159
   {
160
-      $this->view->icingaEtcWarn=0;
161
-      $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
162
-      if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
163
-      {
164
-          $output=array();
160
+	  $this->view->icingaEtcWarn=0;
161
+	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
162
+	  if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
163
+	  {
164
+		  $output=array();
165 165
           
166
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
166
+		  exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
167 167
           
168 168
           
169
-          if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
170
-          {
171
-              $this->view->icingaEtcWarn=1;
172
-              $this->view->icingaweb2_etc=$icingaweb2_etc;
173
-          }
174
-      }
169
+		  if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
170
+		  {
171
+			  $this->view->icingaEtcWarn=1;
172
+			  $this->view->icingaweb2_etc=$icingaweb2_etc;
173
+		  }
174
+	  }
175 175
       
176 176
   }
177 177
   
@@ -182,15 +182,15 @@  discard block
 block discarded – undo
182 182
    */
183 183
   private function get_db_list($allowed)
184 184
   {
185
-      $resources = array();
186
-      foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
187
-      {
188
-          if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
189
-          {
190
-              $resources[$name] = $name;
191
-          }
192
-      }
193
-      return $resources;
185
+	  $resources = array();
186
+	  foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
187
+	  {
188
+		  if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
189
+		  {
190
+			  $resources[$name] = $name;
191
+		  }
192
+	  }
193
+	  return $resources;
194 194
   }
195 195
   
196 196
   /**
@@ -199,23 +199,23 @@  discard block
 block discarded – undo
199 199
    */
200 200
   private function get_php_binary()
201 201
   {
202
-      $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
202
+	  $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
203 203
 
204
-      foreach ($phpBinary as $phpBin )
205
-      {
206
-          $output=array();
207
-          $retCode=255;
208
-          $input="154865134987aaaa";
209
-          exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
204
+	  foreach ($phpBinary as $phpBin )
205
+	  {
206
+		  $output=array();
207
+		  $retCode=255;
208
+		  $input="154865134987aaaa";
209
+		  exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
210 210
           
211
-          if (! isset($output[0])) $output[0]="NO OUT";
211
+		  if (! isset($output[0])) $output[0]="NO OUT";
212 212
           
213
-          if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
214
-          {
215
-              return $phpBin;
216
-          }          
217
-      }
218
-      return NULL;
213
+		  if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
214
+		  {
215
+			  return $phpBin;
216
+		  }          
217
+	  }
218
+	  return NULL;
219 219
   }
220 220
   
221 221
   /**
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
   public function indexAction()
235 235
   {
236 236
       
237
-    // CHeck permissions : display tests in any case, but no configuration.
237
+	// CHeck permissions : display tests in any case, but no configuration.
238 238
 	$this->view->configPermission=$this->checkModuleConfigPermission(1);
239 239
 	// But check read permission
240 240
 	$this->checkReadPermission();
@@ -242,16 +242,16 @@  discard block
 block discarded – undo
242 242
 	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');	
243 243
 	
244 244
 	// Get message : sent on configuration problems detected by controllers
245
-    $this->get_param();
245
+	$this->get_param();
246 246
     
247
-    // Test if configuration exists, if not create for installer script
247
+	// Test if configuration exists, if not create for installer script
248 248
 	$this->check_empty_config();
249 249
 
250 250
 	// Test Database
251
-    $this->check_db();
251
+	$this->check_db();
252 252
 	
253 253
 	//********* Test API
254
-    $this->check_api();
254
+	$this->check_api();
255 255
 	
256 256
 	//*********** Test snmptrapd alive and options
257 257
 	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
 	$phpBinary = $this->get_php_binary();
266 266
 	if ($phpBinary === null)
267 267
 	{
268
-	    $phpBinary = ' PHP BINARY NOT FOUND ';
268
+		$phpBinary = ' PHP BINARY NOT FOUND ';
269 269
 	    
270 270
 	}
271 271
 	
@@ -273,11 +273,11 @@  discard block
 block discarded – undo
273 273
 	$this->view->traps_in_config= $phpBinary . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
274 274
 	
275 275
 	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
276
-	    . ' -c all ' 
277
-	    . ' -d ' . $this->Module()->getBaseDir()
278
-	    . ' -p ' . $phpBinary
279
-	    . ' -a ' . exec('whoami')
280
-	    . ' -w ' . Icinga::app()->getConfigDir();
276
+		. ' -c all ' 
277
+		. ' -d ' . $this->Module()->getBaseDir()
278
+		. ' -p ' . $phpBinary
279
+		. ' -a ' . exec('whoami')
280
+		. ' -w ' . Icinga::app()->getConfigDir();
281 281
 	        
282 282
 	// ******************* configuration form setup*******************
283 283
 	$this->view->form = $form = new TrapsConfigForm();
@@ -311,15 +311,15 @@  discard block
 block discarded – undo
311 311
   public function satelliteAction()
312 312
   {
313 313
       
314
-      // CHeck permissions
315
-      $this->view->configPermission=$this->checkModuleConfigPermission();
314
+	  // CHeck permissions
315
+	  $this->view->configPermission=$this->checkModuleConfigPermission();
316 316
       
317
-      // Setup tabs
318
-      $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
317
+	  // Setup tabs
318
+	  $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
319 319
       
320
-      $this->view->masterHASet = FALSE;
320
+	  $this->view->masterHASet = FALSE;
321 321
       
322
-      $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
322
+	  $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
323 323
   }
324 324
   
325 325
   
@@ -335,8 +335,8 @@  discard block
 block discarded – undo
335 335
 	
336 336
 	try 
337 337
 	{
338
-	    $this->getUIDatabase()->testGetDb(); // Get DB in test mode
339
-	    printf('Schema already exists');
338
+		$this->getUIDatabase()->testGetDb(); // Get DB in test mode
339
+		printf('Schema already exists');
340 340
 	    
341 341
 	} 
342 342
 	catch (DBException $e) 
@@ -347,19 +347,19 @@  discard block
 block discarded – undo
347 347
 		// Get module database name
348 348
 		$dbName=$this->Config()->get('config', 'database');
349 349
 
350
-        $dbResource = ResourceFactory::getResourceConfig($dbName);
351
-        $dbType=$dbResource->get('db');
352
-        switch ($dbType) {
353
-          case 'mysql':
354
-              $dbFileExt='sql';
355
-              break;
356
-          case 'pgsql':
357
-              $dbFileExt='pgsql';
358
-              break;
359
-          default:
360
-              printf("Database configuration error : Unsuported DB");
361
-              return;
362
-        } 
350
+		$dbResource = ResourceFactory::getResourceConfig($dbName);
351
+		$dbType=$dbResource->get('db');
352
+		switch ($dbType) {
353
+		  case 'mysql':
354
+			  $dbFileExt='sql';
355
+			  break;
356
+		  case 'pgsql':
357
+			  $dbFileExt='pgsql';
358
+			  break;
359
+		  default:
360
+			  printf("Database configuration error : Unsuported DB");
361
+			  return;
362
+		} 
363 363
 
364 364
 		printf('<pre>');
365 365
 		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
@@ -383,32 +383,32 @@  discard block
 block discarded – undo
383 383
   public function updateschemaAction()
384 384
   {
385 385
 	  $this->checkModuleConfigPermission();
386
-      $this->getTabs()->add('get',array(
387
-    		'active'	=> true,
388
-    		'label'		=> $this->translate('Update Schema'),
389
-    		'url'		=> Url::fromRequest()
390
-    	));
386
+	  $this->getTabs()->add('get',array(
387
+			'active'	=> true,
388
+			'label'		=> $this->translate('Update Schema'),
389
+			'url'		=> Url::fromRequest()
390
+		));
391 391
 	  // check if needed
392 392
 	  $dberror=array();
393
-      try
394
-      {
395
-          $this->getUIDatabase()->testGetDb(); // Get DB in test mode
396
-          echo 'Schema already exists and is up to date<br>';
397
-          return;
398
-      }
399
-      catch (DBException $e)
400
-      {
401
-          $dberror=$e->getArray(); 
402
-      }
393
+	  try
394
+	  {
395
+		  $this->getUIDatabase()->testGetDb(); // Get DB in test mode
396
+		  echo 'Schema already exists and is up to date<br>';
397
+		  return;
398
+	  }
399
+	  catch (DBException $e)
400
+	  {
401
+		  $dberror=$e->getArray(); 
402
+	  }
403 403
 	  
404 404
 	  echo 'Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a><br><br>';
405 405
 	  
406 406
 	  if ($dberror[0] != 5)
407 407
 	  {
408
-	      echo 'Database does not exists or is not setup correctly<br>';
409
-	      return;
408
+		  echo 'Database does not exists or is not setup correctly<br>';
409
+		  return;
410 410
 	  }
411
-      // setup
411
+	  // setup
412 412
 	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
413 413
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
414 414
 	  $debug_level=4;
@@ -421,20 +421,20 @@  discard block
 block discarded – undo
421 421
 	  $target_version=$dberror[2];
422 422
 	  
423 423
 	  if ($this->params->get('msgok') == null) {
424
-	      // Check for messages and display if any
425
-              echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
426
-	      $Trap->setLogging(2,'syslog');
427
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
428
-	      if ($message != '')
429
-	      {
430
-	          echo 'Note :<br><pre>';
431
-	          echo $message;
432
-	          echo '</pre>';
433
-	          echo '<br>';
434
-	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
435
-	          echo '<br>';
436
-	          return;
437
-	      }
424
+		  // Check for messages and display if any
425
+			  echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
426
+		  $Trap->setLogging(2,'syslog');
427
+		  $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
428
+		  if ($message != '')
429
+		  {
430
+			  echo 'Note :<br><pre>';
431
+			  echo $message;
432
+			  echo '</pre>';
433
+			  echo '<br>';
434
+			  echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
435
+			  echo '<br>';
436
+			  return;
437
+		  }
438 438
 	  }
439 439
 	  
440 440
 	  $Trap->setLogging($debug_level,'display');
@@ -449,50 +449,50 @@  discard block
 block discarded – undo
449 449
   
450 450
   private function checkSnmpTrapd()
451 451
   {
452
-      $psOutput=array();
453
-      // First check is someone is listening to port 162. As not root, we can't have pid... 
454
-      $sspath = exec('which ss 2>/dev/null');
455
-      if(empty($sspath))
456
-      {
457
-          // RHEL based systems
458
-          $sspath = '/usr/sbin/ss';
459
-      }
460
-      if(!is_executable("$sspath"))
461
-      {
462
-          return array(1,"Can not execute $sspath");
463
-      }
464
-      exec("$sspath -lun | grep ':162 '",$psOutput);
465
-      if (count($psOutput) == 0)
466
-      {
467
-          return array(1,'Port UDP/162 is not open : is snmptrapd running?');
468
-      }
469
-      $psOutput=array();
470
-      $selinux_state = '';
471
-      if(is_executable('/usr/sbin/getenforce'))
472
-      {
473
-          $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
474
-      }
475
-      if($selinux_state !== 'Enforcing')
476
-      {
477
-          exec('ps --no-headers -o command -C snmptrapd',$psOutput);
478
-          if (count($psOutput) == 0)
479
-          {
480
-              return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
481
-          }
482
-          // Assume there is only one line... TODO : see if there is a better way to do this
483
-          $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
484
-          if (!preg_match('/-n/',$line))
485
-              return array(1,'snmptrapd has no -n option : '.$line);
486
-          if (!preg_match('/-O[^ ]*n/',$line))
487
-              return array(1,'snmptrapd has no -On option : '.$line);
488
-          if (!preg_match('/-O[^ ]*e/',$line))
489
-              return array(1,'snmptrapd has no -Oe option : '.$line);
452
+	  $psOutput=array();
453
+	  // First check is someone is listening to port 162. As not root, we can't have pid... 
454
+	  $sspath = exec('which ss 2>/dev/null');
455
+	  if(empty($sspath))
456
+	  {
457
+		  // RHEL based systems
458
+		  $sspath = '/usr/sbin/ss';
459
+	  }
460
+	  if(!is_executable("$sspath"))
461
+	  {
462
+		  return array(1,"Can not execute $sspath");
463
+	  }
464
+	  exec("$sspath -lun | grep ':162 '",$psOutput);
465
+	  if (count($psOutput) == 0)
466
+	  {
467
+		  return array(1,'Port UDP/162 is not open : is snmptrapd running?');
468
+	  }
469
+	  $psOutput=array();
470
+	  $selinux_state = '';
471
+	  if(is_executable('/usr/sbin/getenforce'))
472
+	  {
473
+		  $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
474
+	  }
475
+	  if($selinux_state !== 'Enforcing')
476
+	  {
477
+		  exec('ps --no-headers -o command -C snmptrapd',$psOutput);
478
+		  if (count($psOutput) == 0)
479
+		  {
480
+			  return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
481
+		  }
482
+		  // Assume there is only one line... TODO : see if there is a better way to do this
483
+		  $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
484
+		  if (!preg_match('/-n/',$line))
485
+			  return array(1,'snmptrapd has no -n option : '.$line);
486
+		  if (!preg_match('/-O[^ ]*n/',$line))
487
+			  return array(1,'snmptrapd has no -On option : '.$line);
488
+		  if (!preg_match('/-O[^ ]*e/',$line))
489
+			  return array(1,'snmptrapd has no -Oe option : '.$line);
490 490
 
491
-          return array(0,'snmptrapd listening to UDP/162, options : '.$line);
492
-      }
493
-      else
494
-      {
495
-          return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
496
-      }
491
+		  return array(0,'snmptrapd listening to UDP/162, options : '.$line);
492
+	  }
493
+	  else
494
+	  {
495
+		  return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
496
+	  }
497 497
   }
498 498
 }
Please login to merge, or discard this patch.