Passed
Push — master ( 409614...84c1e8 )
by Patrick
02:14
created

HelperController::pluginAction()   A

Complexity

Conditions 4
Paths 7

Size

Total Lines 30
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 16
c 1
b 0
f 0
nc 7
nop 0
dl 0
loc 30
rs 9.7333
1
<?php
2
3
namespace Icinga\Module\Trapdirector\Controllers;
4
5
//use Icinga\Web\Controller;
6
//use Icinga\Web\Url;
7
use Exception;
8
use Icinga\Module\Trapdirector\TrapsController;
9
use Trapdirector\Trap;
10
11
class HelperController extends TrapsController
12
{
13
	
14
	/** Get host list with filter (IP or name) : host=<filter>
15
	*	returns in JSON : status=>OK/NOK  hosts=>array of hosts
16
	*/
17
	public function gethostsAction()
18
	{
19
		$postData=$this->getRequest()->getPost();
20
		
21
		$hostFilter = $this->checkPostVar($postData, 'hostFilter', '.*');
22
		
23
		$retHosts=array('status'=>'OK','hosts' => array());
24
25
		$hosts=$this->getHostByIP($hostFilter);
26
		foreach ($hosts as $val)
27
		{
28
			array_push($retHosts['hosts'],$val->name);
29
		}
30
		
31
		$this->_helper->json($retHosts);
32
	}
33
	
34
	/** Get hostgroup list with filter (name) : hostgroup=<hostFilter>
35
	*	returns in JSON : status=>OK/NOK  hosts=>array of hosts
36
	*/
37
	public function gethostgroupsAction()
38
	{
39
		$postData=$this->getRequest()->getPost();
40
		
41
		$hostFilter = $this->checkPostVar($postData, 'hostfilter', '.*');
42
		
43
		$retHosts=array('status'=>'OK','hosts' => array());
44
45
		$hosts=$this->getHostGroupByName($hostFilter);
46
		foreach ($hosts as $val)
47
		{
48
			array_push($retHosts['hosts'],$val->name);
49
		}
50
		
51
		$this->_helper->json($retHosts);
52
	}
53
	
54
	/** Get service list by host name ( host=<host> )
55
	*	returns in JSON : 
56
	*		status=>OK/No services found/More than one host matches
57
	*		services=>array of services (name)
58
	*		hostid = host object id or -1 if not found.
59
	*/
60
	public function getservicesAction()
61
	{
62
		$postData=$this->getRequest()->getPost();
63
		
64
		$host=$this->checkPostVar($postData, 'host', '.*');
0 ignored issues
show
Unused Code introduced by
The assignment to $host is dead and can be removed.
Loading history...
65
		if (isset($postData['host']))
66
		{
67
			$host=$postData['host'];
68
		}
69
		else
70
		{
71
			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
72
			return;
73
		}
74
		
75
		$hostArray=$this->getHostByName($host);
76
		if (count($hostArray) > 1)
77
		{	
78
			$this->_helper->json(array('status'=>'More than one host matches','hostid' => -1));
79
			return;
80
		}
81
		else if (count($hostArray) == 0)
82
		{
83
			$this->_helper->json(array('status'=>'No host matches','hostid' => -1));
84
			return;
85
		}
86
		$services=$this->getServicesByHostid($hostArray[0]->id);
87
		if (count($services) < 1)
88
		{
89
			$this->_helper->json(array('status'=>'No services found for host','hostid' => $hostArray[0]->id));
90
			return;
91
		}
92
		$retServices=array('status'=>'OK','services' => array(),'hostid' => $hostArray[0]->id);
93
		foreach ($services as $val)
94
		{
95
			array_push($retServices['services'],array($val->id , $val->name));
96
		}
97
		$this->_helper->json($retServices);
98
	}
99
	
100
	/** Get service list by host group ( name=<host> )
101
	*	returns in JSON : 
102
	*		status=>OK/No services found/More than one host matches
103
	*		services=>array of services (name)
104
	*		groupid = group object id or -1 if not found.
105
	*/
106
	public function gethostgroupservicesAction()
107
	{
108
		$postData=$this->getRequest()->getPost();
109
		
110
		$host = $this->checkPostVar($postData, 'host', '.*');
111
		
112
		$hostArray=$this->getHostGroupByName($host);
113
		if (count($hostArray) > 1)
114
		{	
115
			$this->_helper->json(array('status'=>'More than one hostgroup matches','hostid' => -1));
116
			return;
117
		}
118
		else if (count($hostArray) == 0)
119
		{
120
			$this->_helper->json(array('status'=>'No hostgroup matches','hostid' => -1));
121
			return;
122
		}
123
		$services=$this->getServicesByHostGroupid($hostArray[0]->id);
124
		if (count($services) < 1)
125
		{
126
			$this->_helper->json(array('status'=>'No services found for hostgroup','hostid' => $hostArray[0]->id));
127
			return;
128
		}
129
		$retServices=array('status'=>'OK','services' => $services,'hostid' => $hostArray[0]->id);
130
		
131
		$this->_helper->json($retServices);
132
	}
133
134
	/** Get traps from mib  : entry : mib=<mib>
135
	*	returns in JSON : 
136
	*		status=>OK/No mib/Error getting mibs
137
	*		traps=>array of array( oid -> name)
138
	*/
139
	public function gettrapsAction()
140
	{
141
		$postData=$this->getRequest()->getPost();
142
		
143
		$mib = $this->checkPostVar($postData, 'mib', '.*');
144
145
		try
146
		{
147
			$traplist=$this->getMIB()->getTrapList($mib);
148
			$retTraps=array('status'=>'OK','traps' => $traplist);
149
		} 
150
		catch (Exception $e) 
151
		{ 
152
			$retTraps=array('status' => 'Error getting mibs');
153
		}
154
		$this->_helper->json($retTraps);
155
	}	
156
157
	/** Get trap objects from mib  : entry : trap=<oid>
158
	*	returns in JSON : 
159
	*		status=>OK/no trap/not found
160
	*		objects=>array of array( oid -> name, oid->mib)
161
	*/
162
	public function gettrapobjectsAction()
163
	{
164
		$postData=$this->getRequest()->getPost();
165
		
166
		$trap = $this->checkPostVar($postData, 'trap', '.*');
167
		
168
		try
169
		{
170
			$objectlist=$this->getMIB()->getObjectList($trap);
0 ignored issues
show
Bug introduced by
$trap of type string is incompatible with the type integer expected by parameter $trap of Icinga\Module\TrapDirect...Loader::getObjectList(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

170
			$objectlist=$this->getMIB()->getObjectList(/** @scrutinizer ignore-type */ $trap);
Loading history...
171
			$retObjects=array('status'=>'OK','objects' => $objectlist);
172
		} 
173
		catch (Exception $e) 
174
		{ 
175
			$retObjects=array('status' => 'not found');
176
		}
177
		$this->_helper->json($retObjects);
178
	}	
179
	
180
	/** Get list of all loaded mibs : entry : none
181
	*	return : array of strings.
182
	*/
183
	public function getmiblistAction()
184
	{
185
		try
186
		{
187
			$miblist=$this->getMIB()->getMIBList();
188
		} 
189
		catch (Exception $e) 
190
		{ 
191
			$miblist=array('Error getting mibs');
192
		}
193
		$this->_helper->json($miblist);
194
	}
195
	
196
	/** Get MIB::Name from OID : entry : oid
197
	*		status=>OK/No oid/not found
198
	*		mib=>string
199
	*		name=>string
200
	*/	
201
	public function translateoidAction()
202
	{
203
		$postData=$this->getRequest()->getPost();
204
		
205
		$oid = $this->checkPostVar($postData, 'oid', '.*');
206
		
207
		// Try to get oid name from snmptranslate
208
		if (($object=$this->getMIB()->translateOID($oid)) == null)
209
		{
210
			$this->_helper->json(array('status'=>'Not found'));
211
			return;
212
		}
213
		else
214
		{
215
			$this->_helper->json(
216
				array('status'=>'OK',
217
					'mib' => $object['mib'], 
218
					'name' => $object['name'],
219
					'type' => $object['type'],
220
					'type_enum' => $object['type_enum'],
221
				    'description' => $object['description']
222
				)
223
			);
224
		}
225
226
	}
227
	
228
	/** Save or execute database purge of <n> days
229
	*	days=>int 
230
	*	action=>save/execute
231
	*	return : status=>OK/Message error
232
	*/
233
	public function dbmaintenanceAction()
234
	{
235
		
236
		$postData=$this->getRequest()->getPost();
237
		
238
		$days = $this->checkPostVar($postData, 'days', '^[0-9]+$');
239
240
		$action = $this->checkPostVar($postData, 'action', 'save|execute');
241
		
242
		if ($action == 'save')
243
		{
244
			try
245
			{
246
				$this->setDBConfigValue('db_remove_days',$days);
247
			}
248
			catch (Exception $e)
249
			{
250
				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
251
				return;
252
			}
253
			$this->_helper->json(array('status'=>'OK'));
254
			return;
255
		}
256
		if ($action == 'execute')
257
		{
258
			try
259
			{
260
				require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
261
				$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
262
				$debug_level=4;
263
				$trap = new Trap($icingaweb2_etc);
264
				$trap->setLogging($debug_level,'syslog');
265
				$trap->eraseOldTraps($days);
0 ignored issues
show
Bug introduced by
$days of type string is incompatible with the type integer expected by parameter $days of Trapdirector\Trap::eraseOldTraps(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

265
				$trap->eraseOldTraps(/** @scrutinizer ignore-type */ $days);
Loading history...
266
			}
267
			catch (Exception $e)
268
			{
269
				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage() ));
270
				return;
271
			}			
272
			$this->_helper->json(array('status'=>'OK'));
273
		}
274
			
275
	}	
276
277
	/** Save log output to db
278
	*	destination=>log destination 
279
	*	file=>file name
280
	*	level => int 
281
	*	return : status=>OK/Message error
282
	*/
283
	public function logdestinationAction()
284
	{
285
		$postData=$this->getRequest()->getPost();
286
		
287
		$destination = $this->checkPostVar($postData, 'destination', '.*');
288
		$logDest=$this->getModuleConfig()->getLogDestinations();
289
		if (!isset($logDest[$destination]))
290
		{
291
			$this->_helper->json(array('status'=>'invalid destination : '.$destination));
292
			return;
293
		}
294
295
		if (isset($postData['file']))
296
		{ 
297
			$file=$postData['file'];
298
			$fileHandler=@fopen($file,'w');
299
			if ($fileHandler == false)
300
			{   // File os note writabe / cannot create
301
			    $this->_helper->json(array('status'=>'File not writable :  '.$file));
302
			    return;
303
			}
304
		}
305
		else
306
		{
307
			if ($destination != 'file')
308
			{
309
				$file=null;
310
			}
311
			else
312
			{
313
				$this->_helper->json(array('status'=>'No file'));
314
				return;
315
			}
316
		}
317
318
		$level = $this->checkPostVar($postData, 'level', '[0-9]');
319
				
320
		try
321
		{
322
			$this->setDBConfigValue('log_destination',$destination);
323
			$this->setDBConfigValue('log_file',$file);
324
			$this->setDBConfigValue('log_level',$level);
325
		}
326
		catch (Exception $e)
327
		{
328
			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
329
			return;
330
		}
331
		$this->_helper->json(array('status'=>'OK'));
332
		return;
333
			
334
	}	
335
	
336
	/** Test a rule evaluation
337
	 *	rule=>rule to evaluate
338
	 *	action=>'evaluate'
339
	 *	return : status=>OK/Message error & message : return of evaluation
340
	 */
341
	public function testruleAction()
342
	{
343
	    
344
	    $postData=$this->getRequest()->getPost();
345
	   
346
	    $rule = $this->checkPostVar($postData, 'rule', '.*');
347
348
	    $action = $this->checkPostVar($postData, 'action', 'evaluate');
349
350
	    if ($action == 'evaluate')
351
	    {
352
	        try
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);
357
	            // Cleanup spaces before eval
358
	            $rule=$trap->ruleClass->eval_cleanup($rule);
359
	            // Eval
360
	            $item=0;
361
	            $rule=$trap->ruleClass->evaluation($rule,$item);
362
	        }
363
	        catch (Exception $e)
364
	        {
365
	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
366
	            return;
367
	        }
368
	        $return=($rule==true)?'true':'false';
369
	        $this->_helper->json(array('status'=>'OK', 'message' => $return));
370
	    }
371
	    
372
	}	
373
374
	/** Test a rule evaluation
375
	 *	name    => name of plugin
376
	 *	action  => enable | disable
377
	 *	return : status=>OK/Message error
378
	 */
379
	public function pluginAction()
380
	{
381
	    $postData=$this->getRequest()->getPost();
382
	    
383
	    $pluginName = $this->checkPostVar($postData, 'name', '.*');
384
	    
385
	    $action = $this->checkPostVar($postData, 'action', 'enable|disable');
386
	    
387
        try
388
        {
389
            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
390
            $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
391
            $trap = new Trap($icingaweb2_etc);
392
            // Enable plugin.
393
            $action=($action == 'enable') ? true : false;
394
            $retVal=$trap->pluginClass->enablePlugin($pluginName, $action);
395
            
396
        }
397
        catch (Exception $e)
398
        {
399
            $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
400
            return;
401
        }
402
        if ($retVal === true)
403
        {
404
            $this->_helper->json(array('status'=>'OK'));
405
        }
406
        else
407
        {
408
            $this->_helper->json(array('status'=>'Error, see logs'));
409
        }
410
	}
411
	
412
	/** Function evaluation
413
	 *	function    => name of function
414
	 *	action      => evaluate
415
	 *	return : status=>OK/Message error & message : return of evaluation ('true' or 'false' )
416
	 */
417
	public function functionAction()
418
	{
419
	    $postData=$this->getRequest()->getPost();
420
	    
421
	    $functionString = $this->checkPostVar($postData, 'function', '.*');
422
	    
423
	    $this->checkPostVar($postData, 'action', 'evaluate');
424
	    
425
	    // Only one action possible for now, no tests on action.
426
	    try
427
	    {
428
	        require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
429
	        $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
430
	        $trap = new Trap($icingaweb2_etc);
431
	        // load all plugins in case tested function is not enabled.
432
	        $trap->pluginClass->registerAllPlugins(false);
433
	        // Clean all spaces
434
	        $functionString = $trap->ruleClass->eval_cleanup($functionString);
435
	        // Eval functions
436
	        $result = $trap->pluginClass->evaluateFunctionString($functionString);	        
437
	    }
438
	    catch (Exception $e)
439
	    {
440
	        $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
441
	        return;
442
	    }
443
	    
444
        $result = ($result === true)?'True':'False';
445
        $this->_helper->json(array('status'=>'OK','message' => $result));
446
	}
447
448
    /**************   Utilities **********************/
449
450
	private function checkPostVar(array $postData,string $postVar, string $validRegexp) : string
451
	{
452
	    if (!isset ($postData[$postVar]))
453
	    {
454
	        $this->_helper->json(array('status'=>'No ' . $postVar));
455
	        return '';
456
	    }
457
	    if (preg_match('/'.$validRegexp.'/', $postData[$postVar]) != 1)
458
	    {
459
	        $this->_helper->json(array('status'=>'Unknown ' . $postVar . ' value '.$postData[$postVar]));
460
	        return '';
461
	    }
462
	    return $postData[$postVar];
463
	}
464
}
465