Passed
Push — master ( 6b0d98...409614 )
by Patrick
02:00
created

HelperController::gettrapsAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 2
eloc 8
c 2
b 0
f 1
nc 2
nop 0
dl 0
loc 16
rs 10
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
		if (isset($postData['destination']))
287
		{
288
			$destination=$postData['destination'];
289
			$logDest=$this->getModuleConfig()->getLogDestinations();
290
			if (!isset($logDest[$destination]))
291
			{
292
				$this->_helper->json(array('status'=>'invalid destination : '.$destination));
293
				return;
294
			}
295
		}
296
		else
297
		{
298
			$this->_helper->json(array('status'=>'No destination'));
299
		}
300
		if (isset($postData['file']))
301
		{ 
302
			$file=$postData['file'];
303
			$fileHandler=@fopen($file,'w');
304
			if ($fileHandler == false)
305
			{   // File os note writabe / cannot create
306
			    $this->_helper->json(array('status'=>'File not writable :  '.$file));
307
			    return;
308
			}
309
		}
310
		else
311
		{
312
			if ($destination != 'file')
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $destination does not seem to be defined for all execution paths leading up to this point.
Loading history...
313
			{
314
				$file=null;
315
			}
316
			else
317
			{
318
				$this->_helper->json(array('status'=>'No file'));
319
				return;
320
			}
321
		}
322
323
		if (isset($postData['level']))
324
		{ 
325
			$level=$postData['level'];
326
		}
327
		else
328
		{
329
			$this->_helper->json(array('status'=>'No level'));
330
			return;
331
		}
332
		
333
		try
334
		{
335
			$this->setDBConfigValue('log_destination',$destination);
336
			$this->setDBConfigValue('log_file',$file);
337
			$this->setDBConfigValue('log_level',$level);
338
		}
339
		catch (Exception $e)
340
		{
341
			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
342
			return;
343
		}
344
		$this->_helper->json(array('status'=>'OK'));
345
		return;
346
			
347
	}	
348
	
349
	/** Test a rule evaluation
350
	 *	rule=>rule to evaluate
351
	 *	action=>'evaluate'
352
	 *	return : status=>OK/Message error & message : return of evaluation
353
	 */
354
	public function testruleAction()
355
	{
356
	    
357
	    $postData=$this->getRequest()->getPost();
358
	    if (isset($postData['rule']))
359
	    {
360
	        $rule=$postData['rule'];
361
	    }
362
	    else
363
	    {
364
	        $this->_helper->json(array('status'=>'No Rule'));
365
	    }
366
	    if (isset($postData['action']))
367
	    {
368
	        $action=$postData['action'];
369
	        if ($action != 'evaluate')
370
	        {
371
	            $this->_helper->json(array('status'=>'unknown action '.$action));
372
	            return;
373
	        }
374
	    }
375
	    else
376
	    {
377
	        $this->_helper->json(array('status'=>'No action'));
378
	        return;
379
	    }
380
	    if ($action == 'evaluate')
381
	    {
382
	        try
383
	        {
384
	            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
385
	            $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
386
	            $Trap = new Trap($icingaweb2_etc);
387
	            // Cleanup spaces before eval
388
	            $rule=$Trap->ruleClass->eval_cleanup($rule);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $rule does not seem to be defined for all execution paths leading up to this point.
Loading history...
389
	            // Eval
390
	            $item=0;
391
	            $rule=$Trap->ruleClass->evaluation($rule,$item);
392
	        }
393
	        catch (Exception $e)
394
	        {
395
	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
396
	            return;
397
	        }
398
	        $return=($rule==true)?'true':'false';
399
	        $this->_helper->json(array('status'=>'OK', 'message' => $return));
400
	    }
401
	    
402
	}	
403
404
	/** Test a rule evaluation
405
	 *	name    => name of plugin
406
	 *	action  => enable | disable
407
	 *	return : status=>OK/Message error
408
	 */
409
	public function pluginAction()
410
	{
411
	    $postData=$this->getRequest()->getPost();
412
	    if (isset($postData['name']))
413
	    {
414
	        $pluginName=$postData['name'];
415
	    }
416
	    else
417
	    {
418
	        $this->_helper->json(array('status'=>'No plugin name'));
419
	    }
420
	    if (isset($postData['action']))
421
	    {
422
	        $action=$postData['action'];
423
	        if ($action != 'enable' && $action != 'disable')
424
	        {
425
	            $this->_helper->json(array('status'=>'unknown action '.$action));
426
	            return;
427
	        }
428
	    }
429
	    else
430
	    {
431
	        $this->_helper->json(array('status'=>'No action'));
432
	        return;
433
	    }
434
435
        try
436
        {
437
            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
438
            $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
439
            $Trap = new Trap($icingaweb2_etc);
440
            // Enable plugin.
441
            $action=($action == 'enable') ? true : false;
442
            $retVal=$Trap->pluginClass->enablePlugin($pluginName, $action);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $pluginName does not seem to be defined for all execution paths leading up to this point.
Loading history...
443
            
444
        }
445
        catch (Exception $e)
446
        {
447
            $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
448
            return;
449
        }
450
        if ($retVal === true)
451
        {
452
            $this->_helper->json(array('status'=>'OK'));
453
        }
454
        else
455
        {
456
            $this->_helper->json(array('status'=>'Error, see logs'));
457
        }
458
	}
459
	
460
	/** Function evaluation
461
	 *	function    => name of function
462
	 *	action      => evaluate
463
	 *	return : status=>OK/Message error & message : return of evaluation ('true' or 'false' )
464
	 */
465
	public function functionAction()
466
	{
467
	    $postData=$this->getRequest()->getPost();
468
	    if (isset($postData['function']))
469
	    {
470
	        $functionString=$postData['function'];
471
	    }
472
	    else
473
	    {
474
	        $this->_helper->json(array('status'=>'No function name'));
475
	    }
476
	    if (isset($postData['action']))
477
	    {
478
	        $action=$postData['action'];
479
	        if ($action != 'evaluate')
480
	        {
481
	            $this->_helper->json(array('status'=>'unknown action '.$action));
482
	            return;
483
	        }
484
	    }
485
	    else
486
	    {
487
	        $this->_helper->json(array('status'=>'No action'));
488
	        return;
489
	    }
490
	    
491
	    try
492
	    {
493
	        require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
494
	        $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
495
	        $Trap = new Trap($icingaweb2_etc);
496
	        // load all plugins in case tested function is not enabled.
497
	        $Trap->pluginClass->registerAllPlugins(false);
498
	        // Clean all spaces
499
	        $functionString = $Trap->ruleClass->eval_cleanup($functionString);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $functionString does not seem to be defined for all execution paths leading up to this point.
Loading history...
500
	        // Eval functions
501
	        $result = $Trap->pluginClass->evaluateFunctionString($functionString);	        
502
	    }
503
	    catch (Exception $e)
504
	    {
505
	        $this->_helper->json(array('status'=>'Action error : '.$e->getMessage() ));
506
	        return;
507
	    }
508
	    
509
        $result = ($result === true)?'True':'False';
510
        $this->_helper->json(array('status'=>'OK','message' => $result));
511
	}
512
513
    /**************   Utilities **********************/
514
515
	private function checkPostVar(array $postData,string $postVar, string $validRegexp) : string
516
	{
517
	    if (!isset ($postData[$postVar]))
518
	    {
519
	        $this->_helper->json(array('status'=>'No ' . $postVar));
520
	        return '';
521
	    }
522
	    if (preg_match('/'.$validRegexp.'/', $postData[$postVar]) != 1)
523
	    {
524
	        $this->_helper->json(array('status'=>'Unknown ' . $postVar . ' value '.$postData[$postVar]));
525
	        return '';
526
	    }
527
	    return $postData[$postVar];
528
	}
529
}
530