Completed
Pull Request — master (#5230)
by
unknown
04:02
created

html/includes/api_functions.inc.php (2 issues)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
 * LibreNMS
5
 *
6
 * Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
7
 *
8
 * This program is free software: you can redistribute it and/or modify it
9
 * under the terms of the GNU General Public License as published by the
10
 * Free Software Foundation, either version 3 of the License, or (at your
11
 * option) any later version.  Please see LICENSE.txt at the top level of
12
 * the source code distribution for details.
13
 */
14
15
function authToken(\Slim\Route $route)
16
{
17
    $app   = \Slim\Slim::getInstance();
18
    $token = $app->request->headers->get('X-Auth-Token');
19
    if (isset($token) && !empty($token)) {
20
        if (!function_exists('get_user')) {
21
            $username = dbFetchCell('SELECT `U`.`username` FROM `api_tokens` AS AT JOIN `users` AS U ON `AT`.`user_id`=`U`.`user_id` WHERE `AT`.`token_hash`=?', array($token));
22
        } else {
23
            $username = get_user(dbFetchCell('SELECT `AT`.`user_id` FROM `api_tokens` AS AT WHERE `AT`.`token_hash`=?', array($token)));
24
        }
25
        if (!empty($username)) {
26
            $authenticated = true;
27
        } else {
28
            $authenticated = false;
29
        }
30
    } else {
31
        $authenticated = false;
32
    }
33
34
    if ($authenticated === false) {
35
        $app->response->setStatus(401);
36
        $output = array(
37
            'status'  => 'error',
38
            'message' => 'API Token is missing or invalid; please supply a valid token',
39
        );
40
        echo _json_encode($output);
41
        $app->stop();
42
    }
43
}
44
45
46
47
function get_graph_by_port_hostname()
48
{
49
    // This will return a graph for a given port by the ifName
50
    global $config;
51
    $app          = \Slim\Slim::getInstance();
52
    $router       = $app->router()->getCurrentRoute()->getParams();
53
    $hostname     = $router['hostname'];
54
    $vars         = array();
55
    $vars['port'] = urldecode($router['ifname']);
56
    $vars['type'] = $router['type'] ?: 'port_bits';
57
    if (!empty($_GET['from'])) {
58
        $vars['from'] = $_GET['from'];
59
    }
60
61
    if (!empty($_GET['to'])) {
62
        $vars['to'] = $_GET['to'];
63
    }
64
65
    if ($_GET['ifDescr'] == true) {
66
        $port = 'ifDescr';
67
    } else {
68
        $port = 'ifName';
69
    }
70
71
    $vars['width']  = $_GET['width'] ?: 1075;
72
    $vars['height'] = $_GET['height'] ?: 300;
73
    $auth           = '1';
74
    $vars['id']     = dbFetchCell("SELECT `P`.`port_id` FROM `ports` AS `P` JOIN `devices` AS `D` ON `P`.`device_id` = `D`.`device_id` WHERE `D`.`hostname`=? AND `P`.`$port`=?", array($hostname, $vars['port']));
75
    $app->response->headers->set('Content-Type', 'image/png');
76
    include 'includes/graphs/graph.inc.php';
77
}
78
79
80
function get_port_stats_by_port_hostname()
81
{
82
    // This will return port stats based on a devices hostname and ifName
83
    global $config;
84
    $app       = \Slim\Slim::getInstance();
85
    $router    = $app->router()->getCurrentRoute()->getParams();
86
    $hostname  = $router['hostname'];
87
    $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
88
    $ifName    = urldecode($router['ifname']);
89
    $port     = dbFetchRow('SELECT * FROM `ports` WHERE `device_id`=? AND `ifName`=? AND `deleted` = 0', array($device_id, $ifName));
90
91
    $in_rate = $port['ifInOctets_rate'] * 8;
92
    $out_rate = $port['ifOutOctets_rate'] * 8;
93
    $port['in_rate'] = formatRates($in_rate);
94
    $port['out_rate'] = formatRates($out_rate);
95
    $port['in_perc'] = number_format($in_rate / $port['ifSpeed'] * 100, 2, '.', '');
96
    $port['out_perc'] = number_format($out_rate / $port['ifSpeed'] * 100, 2, '.', '');
97
    $port['in_pps'] = format_bi($port['ifInUcastPkts_rate']);
98
    $port['out_pps'] = format_bi($port['ifOutUcastPkts_rate']);
99
    
100
    $output    = array(
101
        'status' => 'ok',
102
        'port'   => $port,
103
    );
104
    $app->response->headers->set('Content-Type', 'application/json');
105
    echo _json_encode($output);
106
}
107
108
109
function get_graph_generic_by_hostname()
110
{
111
    // This will return a graph type given a device id.
112
    global $config;
113
    $app          = \Slim\Slim::getInstance();
114
    $router       = $app->router()->getCurrentRoute()->getParams();
115
    $hostname     = $router['hostname'];
116
    $vars         = array();
117
    $vars['type'] = $router['type'] ?: 'device_uptime';
118
119
    // use hostname as device_id if it's all digits
120
    $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
121
    $device = device_by_id_cache($device_id);
122
123
    if (!empty($_GET['from'])) {
124
        $vars['from'] = $_GET['from'];
125
    }
126
127
    if (!empty($_GET['to'])) {
128
        $vars['to'] = $_GET['to'];
129
    }
130
131
    $vars['width']  = $_GET['width'] ?: 1075;
132
    $vars['height'] = $_GET['height'] ?: 300;
133
    $auth           = '1';
134
    $vars['device'] = dbFetchCell('SELECT `D`.`device_id` FROM `devices` AS `D` WHERE `D`.`hostname`=?', array($hostname));
135
    $app->response->headers->set('Content-Type', 'image/png');
136
    include 'includes/graphs/graph.inc.php';
137
}
138
139
140
function get_device()
141
{
142
    // return details of a single device
143
    $app = \Slim\Slim::getInstance();
144
    $app->response->headers->set('Content-Type', 'application/json');
145
    $router   = $app->router()->getCurrentRoute()->getParams();
146
    $hostname = $router['hostname'];
147
148
    // use hostname as device_id if it's all digits
149
    $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
150
151
    // find device matching the id
152
    $device = device_by_id_cache($device_id);
153
    if (!$device) {
154
        $app->response->setStatus(404);
155
        $output = array(
156
            'status'  => 'error',
157
            'message' => "Device $hostname does not exist",
158
        );
159
        echo _json_encode($output);
160
        $app->stop();
161
    } else {
162
        $output = array(
163
            'status'  => 'ok',
164
            'devices' => array($device),
165
        );
166
        echo _json_encode($output);
167
    }
168
}
169
170
171
function list_devices()
172
{
173
    // This will return a list of devices
174
    global $config;
175
    $app   = \Slim\Slim::getInstance();
176
    $order = $_GET['order'];
177
    $type  = $_GET['type'];
178
    $query = mres($_GET['query']);
179
    $param = array();
180
    $join = '';
181
    if (empty($order)) {
182
        $order = 'hostname';
183
    }
184
185
    if (stristr($order, ' desc') === false && stristr($order, ' asc') === false) {
186
        $order = '`'.$order.'` ASC';
187
    }
188
189
    if ($type == 'all' || empty($type)) {
190
        $sql = '1';
191
    } elseif ($type == 'ignored') {
192
        $sql = "`ignore`='1' AND `disabled`='0'";
193
    } elseif ($type == 'up') {
194
        $sql = "`status`='1' AND `ignore`='0' AND `disabled`='0'";
195
    } elseif ($type == 'down') {
196
        $sql = "`status`='0' AND `ignore`='0' AND `disabled`='0'";
197
    } elseif ($type == 'disabled') {
198
        $sql = "`disabled`='1'";
199
    } elseif ($type == 'mac') {
200
        $join = " LEFT JOIN `ports` ON `devices`.`device_id`=`ports`.`device_id` LEFT JOIN `ipv4_mac` ON `ports`.`port_id`=`ipv4_mac`.`port_id` ";
201
        $sql = "`ipv4_mac`.`mac_address`=?";
202
        $param[] = $query;
203
    } elseif ($type == 'ipv4') {
204
        $join = " LEFT JOIN `ports` ON `devices`.`device_id`=`ports`.`device_id` LEFT JOIN `ipv4_addresses` ON `ports`.`port_id`=`ipv4_addresses`.`port_id` ";
205
        $sql = "`ipv4_addresses`.`ipv4_address`=?";
206
        $param[] = $query;
207
    } elseif ($type == 'ipv6') {
208
        $join = " LEFT JOIN `ports` ON `devices`.`device_id`=`ports`.`device_id` LEFT JOIN `ipv6_addresses` ON `ports`.`port_id`=`ipv6_addresses`.`port_id` ";
209
        $sql = "`ipv6_addresses`.`ipv6_address`=? OR `ipv6_addresses`.`ipv6_compressed`=?";
210
        $param = array($query,$query);
211
    } else {
212
        $sql = '1';
213
    }
214
    $devices = array();
215
    foreach (dbFetchRows("SELECT * FROM `devices` $join WHERE $sql ORDER by $order", $param) as $device) {
216
        $device['ip'] = inet6_ntop($device['ip']);
217
        $devices[] = $device;
218
    }
219
220
    $count = count($devices);
221
222
    $output = array(
223
        'status'  => 'ok',
224
        'count'   => $count,
225
        'devices' => $devices,
226
    );
227
    $app->response->headers->set('Content-Type', 'application/json');
228
    echo _json_encode($output);
229
}
230
231
232
function add_device()
233
{
234
    // This will add a device using the data passed encoded with json
235
    // FIXME: Execution flow through this function could be improved
236
    global $config;
237
    $app  = \Slim\Slim::getInstance();
238
    $data = json_decode(file_get_contents('php://input'), true);
239
    // Default status & code to error and change it if we need to.
240
    $status = 'error';
241
    $code   = 500;
242
    // keep scrutinizer from complaining about snmpver not being set for all execution paths
243
    $snmpver = 'v2c';
244
    if (empty($data)) {
245
        $message = 'No information has been provided to add this new device';
246
    } elseif (empty($data['hostname'])) {
247
        $message = 'Missing the device hostname';
248
    }
249
250
    $hostname     = $data['hostname'];
251
    $port         = $data['port'] ? mres($data['port']) : $config['snmp']['port'];
252
    $transport    = $data['transport'] ? mres($data['transport']) : 'udp';
253
    $poller_group = $data['poller_group'] ? mres($data['poller_group']) : 0;
254
    $force_add    = $data['force_add'] ? mres($data['force_add']) : 0;
255
    if ($data['version'] == 'v1' || $data['version'] == 'v2c') {
256
        if ($data['community']) {
257
            $config['snmp']['community'] = array($data['community']);
258
        }
259
260
        $snmpver = mres($data['version']);
261 View Code Duplication
    } elseif ($data['version'] == 'v3') {
262
        $v3 = array(
263
            'authlevel'  => mres($data['authlevel']),
264
            'authname'   => mres($data['authname']),
265
            'authpass'   => mres($data['authpass']),
266
            'authalgo'   => mres($data['authalgo']),
267
            'cryptopass' => mres($data['cryptopass']),
268
            'cryptoalgo' => mres($data['cryptoalgo']),
269
        );
270
271
        array_push($config['snmp']['v3'], $v3);
272
        $snmpver = 'v3';
273
    } else {
274
        $code    = 400;
275
        $status  = 'error';
276
        $message = "You haven't specified an SNMP version to use";
277
    }
278
    if (empty($message)) {
279
        try {
280
            $device_id = addHost($hostname, $snmpver, $port, $transport, $poller_group, $force_add);
281
            $code    = 201;
282
            $status  = 'ok';
283
            $message = "Device $hostname ($device_id) has been added successfully";
284
        } catch (Exception $e) {
285
            $message = $e->getMessage();
286
        }
287
    }
288
289
    $app->response->setStatus($code);
290
    $output = array(
291
        'status'  => $status,
292
        'message' => $message,
293
    );
294
    $app->response->headers->set('Content-Type', 'application/json');
295
    echo _json_encode($output);
296
}
297
298
299
function del_device()
300
{
301
    // This will add a device using the data passed encoded with json
302
    global $config;
303
    $app      = \Slim\Slim::getInstance();
304
    $router   = $app->router()->getCurrentRoute()->getParams();
305
    $hostname = $router['hostname'];
306
    // Default status to error and change it if we need to.
307
    $status = 'error';
308
    $code   = 500;
309
    if (empty($hostname) || $config['api_demo'] == 1) {
310
        $message = 'No hostname has been provided to delete';
311
        if ($config['api_demo'] == 1) {
312
            $message = "This feature isn\'t available in the demo";
313
        }
314
315
        $output = array(
316
            'status'  => $status,
317
            'message' => $message,
318
        );
319
    } else {
320
        // allow deleting by device_id or hostname
321
        $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
322
        $device    = null;
323
        if ($device_id) {
324
            // save the current details for returning to the client on successful delete
325
            $device = device_by_id_cache($device_id);
326
        }
327
328
        if ($device) {
329
            $response = delete_device($device_id);
330
            if (empty($response)) {
331
                // FIXME: Need to provide better diagnostics out of delete_device
332
                $output = array(
333
                    'status'  => $status,
334
                    'message' => 'Device deletion failed',
335
                );
336
            } else {
337
                // deletion succeeded - include old device details in response
338
                $code   = 200;
339
                $status = 'ok';
340
                $output = array(
341
                    'status'  => $status,
342
                    'message' => $response,
343
                    'devices' => array($device),
344
                );
345
            }
346
        } else {
347
            // no device matching the name
348
            $code   = 404;
349
            $output = array(
350
                'status'  => $status,
351
                'message' => "Device $hostname not found",
352
            );
353
        }
354
    }
355
356
    $app->response->setStatus($code);
357
    $app->response->headers->set('Content-Type', 'application/json');
358
    echo _json_encode($output);
359
}
360
361
362
function get_vlans()
363
{
364
    // This will list all vlans for a given device
365
    global $config;
366
    $app      = \Slim\Slim::getInstance();
367
    $router   = $app->router()->getCurrentRoute()->getParams();
368
    $hostname = $router['hostname'];
369
    $code     = 500;
370
    if (empty($hostname)) {
371
        $output = $output = array(
372
            'status'  => 'error',
373
            'message' => 'No hostname has been provided',
374
        );
375
    } else {
376
        include_once '../includes/functions.php';
377
        $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
378
        $device    = null;
379
        if ($device_id) {
380
            // save the current details for returning to the client on successful delete
381
            $device = device_by_id_cache($device_id);
382
        }
383
384
        if ($device) {
385
            $vlans       = dbFetchRows('SELECT vlan_vlan,vlan_domain,vlan_name,vlan_type,vlan_mtu FROM vlans WHERE `device_id` = ?', array($device_id));
386
            $total_vlans = count($vlans);
387
            $code        = 200;
388
            $output      = array(
389
                'status' => 'ok',
390
                'count'  => $total_vlans,
391
                'vlans'  => $vlans,
392
            );
393
        } else {
394
            $code   = 404;
395
            $output = array(
396
                'status' => 'error', "Device $hostname not found"
397
            );
398
        }
399
    }
400
401
    $app->response->setStatus($code);
402
    $app->response->headers->set('Content-Type', 'application/json');
403
    echo _json_encode($output);
404
}
405
406
407
function show_endpoints()
408
{
409
    global $config;
410
    $app    = \Slim\Slim::getInstance();
411
    $routes = $app->router()->getNamedRoutes();
412
    $output = array();
413
    foreach ($routes as $route) {
414
        $output[$route->getName()] = $config['base_url'].$route->getPattern();
415
    }
416
417
    $app->response->setStatus('200');
418
    $app->response->headers->set('Content-Type', 'application/json');
419
    echo _json_encode($output);
420
}
421
422
423
function list_bgp()
424
{
425
    global $config;
426
    $app        = \Slim\Slim::getInstance();
427
    $code       = 500;
428
    $status     = 'error';
429
    $message    = 'Error retrieving bgpPeers';
430
    $sql        = '';
431
    $sql_params = array();
432
    $hostname   = $_GET['hostname'];
433
    $device_id  = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
434
    if (is_numeric($device_id)) {
435
        $sql        = ' AND `device_id`=?';
436
        $sql_params = array($device_id);
437
    }
438
439
    $bgp_sessions       = dbFetchRows("SELECT * FROM bgpPeers WHERE `bgpPeerState` IS NOT NULL AND `bgpPeerState` != '' $sql", $sql_params);
440
    $total_bgp_sessions = count($bgp_sessions);
441
    if (is_numeric($total_bgp_sessions)) {
442
        $code    = 200;
443
        $status  = 'ok';
444
        $message = '';
445
    }
446
447
    $output = array(
448
        'status'       => "$status",
449
        'err-msg'      => $message,
450
        'count'        => $total_bgp_sessions,
451
        'bgp_sessions' => $bgp_sessions,
452
    );
453
    $app->response->setStatus($code);
454
    $app->response->headers->set('Content-Type', 'application/json');
455
    echo _json_encode($output);
456
}
457
458
459
function get_graph_by_portgroup()
460
{
461
    global $config;
462
    $app    = \Slim\Slim::getInstance();
463
    $router = $app->router()->getCurrentRoute()->getParams();
464
    $group  = $router['group'];
465
    $vars   = array();
466
    if (!empty($_GET['from'])) {
467
        $vars['from'] = $_GET['from'];
468
    }
469
470
    if (!empty($_GET['to'])) {
471
        $vars['to'] = $_GET['to'];
472
    }
473
474
    $vars['width']  = $_GET['width'] ?: 1075;
475
    $vars['height'] = $_GET['height'] ?: 300;
476
    $auth           = '1';
477
478
    $ports = get_ports_from_type(explode(',', $group));
479
    $if_list     = '';
480
    $seperator   = '';
481
    foreach ($ports as $port) {
482
        $if_list  .= $seperator.$port['port_id'];
483
        $seperator = ',';
484
    }
485
486
    unset($seperator);
487
    $vars['type'] = 'multiport_bits_separate';
488
    $vars['id']   = $if_list;
489
    $app->response->headers->set('Content-Type', 'image/png');
490
    include 'includes/graphs/graph.inc.php';
491
}
492
493
494
function get_components()
495
{
496
    global $config;
497
    $code     = 200;
498
    $status   = 'ok';
499
    $message  = '';
500
    $app      = \Slim\Slim::getInstance();
501
    $router   = $app->router()->getCurrentRoute()->getParams();
502
    $hostname = $router['hostname'];
503
504
    // Do some filtering if the user requests.
505
    $options = array();
506
    // We need to specify the label as this is a LIKE query
507 View Code Duplication
    if (isset($_GET['label'])) {
508
        // set a label like filter
509
        $options['filter']['label'] = array('LIKE',$_GET['label']);
510
        unset($_GET['label']);
511
    }
512
    // Add the rest of the options with an equals query
513
    foreach ($_GET as $k => $v) {
514
        $options['filter'][$k] = array('=',$v);
515
    }
516
517
    // use hostname as device_id if it's all digits
518
    $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
519
    $COMPONENT = new LibreNMS\Component();
520
    $components = $COMPONENT->getComponents($device_id, $options);
521
522
    $output       = array(
523
        'status'  => "$status",
524
        'err-msg' => $message,
525
        'count'   => count($components[$device_id]),
526
        'components'  => $components[$device_id],
527
    );
528
    $app->response->setStatus($code);
529
    $app->response->headers->set('Content-Type', 'application/json');
530
    echo _json_encode($output);
531
}
532
533
534
function add_components()
535
{
536
    global $config;
537
    $code     = 200;
538
    $status   = 'ok';
539
    $message  = '';
540
    $app      = \Slim\Slim::getInstance();
541
    $router   = $app->router()->getCurrentRoute()->getParams();
542
    $hostname = $router['hostname'];
543
    $ctype = $router['type'];
544
545
    // use hostname as device_id if it's all digits
546
    $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
547
    $COMPONENT = new LibreNMS\Component();
548
    $component = $COMPONENT->createComponent($device_id, $ctype);
549
550
    $output       = array(
551
        'status'  => "$status",
552
        'err-msg' => $message,
553
        'count'   => count($component),
554
        'components'  => $component,
555
    );
556
    $app->response->setStatus($code);
557
    $app->response->headers->set('Content-Type', 'application/json');
558
    echo _json_encode($output);
559
}
560
561
562
function edit_components()
563
{
564
    global $config;
565
    $app      = \Slim\Slim::getInstance();
566
    $router   = $app->router()->getCurrentRoute()->getParams();
567
    $hostname = $router['hostname'];
568
    $data = json_decode(file_get_contents('php://input'), true);
569
570
    // use hostname as device_id if it's all digits
571
    $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
572
    $COMPONENT = new LibreNMS\Component();
573
574 View Code Duplication
    if ($COMPONENT->setComponentPrefs($device_id, $data)) {
575
        // Edit Success.
576
        $code     = 200;
577
        $status   = 'ok';
578
        $message  = '';
579
    } else {
580
        // Edit Failure.
581
        $code     = 500;
582
        $status   = 'error';
583
        $message  = 'Components could not be edited.';
584
    }
585
586
    $output       = array(
587
        'status'  => "$status",
588
        'err-msg' => $message,
589
        'count'   => count($data),
590
    );
591
592
    $app->response->setStatus($code);
593
    $app->response->headers->set('Content-Type', 'application/json');
594
    echo _json_encode($output);
595
}
596
597
598
function delete_components()
599
{
600
    global $config;
601
    $app      = \Slim\Slim::getInstance();
602
    $router   = $app->router()->getCurrentRoute()->getParams();
603
    $cid = $router['component'];
604
605
    $COMPONENT = new LibreNMS\Component();
606 View Code Duplication
    if ($COMPONENT->deleteComponent($cid)) {
607
        // Edit Success.
608
        $code     = 200;
609
        $status   = 'ok';
610
        $message  = '';
611
    } else {
612
        // Edit Failure.
613
        $code     = 500;
614
        $status   = 'error';
615
        $message  = 'Components could not be deleted.';
616
    }
617
618
    $output       = array(
619
        'status'  => "$status",
620
        'err-msg' => $message,
621
    );
622
623
    $app->response->setStatus($code);
624
    $app->response->headers->set('Content-Type', 'application/json');
625
    echo _json_encode($output);
626
}
627
628
629
function get_graphs()
630
{
631
    global $config;
632
    $code     = 200;
633
    $status   = 'ok';
634
    $message  = '';
635
    $app      = \Slim\Slim::getInstance();
636
    $router   = $app->router()->getCurrentRoute()->getParams();
637
    $hostname = $router['hostname'];
638
639
    // FIXME: this has some overlap with html/pages/device/graphs.inc.php
640
    // use hostname as device_id if it's all digits
641
    $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
642
    $graphs    = array();
643
    $graphs[]  = array(
644
        'desc' => 'Poller Time',
645
        'name' => 'device_poller_perf',
646
    );
647
    $graphs[]  = array(
648
        'desc' => 'Ping Response',
649
        'name' => 'device_ping_perf',
650
    );
651
    foreach (dbFetchRows('SELECT * FROM device_graphs WHERE device_id = ? ORDER BY graph', array($device_id)) as $graph) {
652
        $desc     = $config['graph_types']['device'][$graph['graph']]['descr'];
653
        $graphs[] = array(
654
            'desc' => $desc,
655
            'name' => 'device_'.$graph['graph'],
656
        );
657
    }
658
659
    $total_graphs = count($graphs);
660
    $output       = array(
661
        'status'  => "$status",
662
        'err-msg' => $message,
663
        'count'   => $total_graphs,
664
        'graphs'  => $graphs,
665
    );
666
    $app->response->setStatus($code);
667
    $app->response->headers->set('Content-Type', 'application/json');
668
    echo _json_encode($output);
669
}
670
671
672
function get_port_graphs()
673
{
674
    global $config;
675
    $app      = \Slim\Slim::getInstance();
676
    $router   = $app->router()->getCurrentRoute()->getParams();
677
    $hostname = $router['hostname'];
678
    if (isset($_GET['columns'])) {
679
        $columns = $_GET['columns'];
680
    } else {
681
        $columns = 'ifName';
682
    }
683
684
    // use hostname as device_id if it's all digits
685
    $device_id   = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
686
    $ports       = dbFetchRows("SELECT $columns FROM `ports` WHERE `device_id` = ? AND `deleted` = '0' ORDER BY `ifIndex` ASC", array($device_id));
687
    $total_ports = count($ports);
688
    $output      = array(
689
        'status'  => 'ok',
690
        'err-msg' => '',
691
        'count'   => $total_ports,
692
        'ports'   => $ports,
693
    );
694
    $app->response->setStatus('200');
695
    $app->response->headers->set('Content-Type', 'application/json');
696
    echo _json_encode($output);
697
}
698
699
function get_port_stack()
700
{
701
    global $config;
702
    $app      = \Slim\Slim::getInstance();
703
    $router   = $app->router()->getCurrentRoute()->getParams();
704
    $hostname = $router['hostname'];
705
    // use hostname as device_id if it's all digits
706
    $device_id      = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
707
708
    if (isset($_GET['valid_mappings'])) {
709
        $mappings       = dbFetchRows("SELECT * FROM `ports_stack` WHERE (`device_id` = ? AND `ifStackStatus` = 'active' AND (`port_id_high` != '0' AND `port_id_low` != '0')) ORDER BY `port_id_high` ASC", array($device_id));
710
    } else {
711
        $mappings       = dbFetchRows("SELECT * FROM `ports_stack` WHERE `device_id` = ? AND `ifStackStatus` = 'active' ORDER BY `port_id_high` ASC", array($device_id));
712
    }
713
714
    $total_mappings = count($mappings);
715
    $output         = array(
716
        'status'  => 'ok',
717
        'err-msg' => '',
718
        'count'   => $total_mappings,
719
        'mappings'   => $mappings,
720
    );
721
    $app->response->setStatus('200');
722
    $app->response->headers->set('Content-Type', 'application/json');
723
    echo _json_encode($output);
724
}
725
726
function list_alert_rules()
727
{
728
    global $config;
729
    $app    = \Slim\Slim::getInstance();
730
    $router = $app->router()->getCurrentRoute()->getParams();
731
    $sql    = '';
732
    $param  = array();
733 View Code Duplication
    if (isset($router['id']) && $router['id'] > 0) {
734
        $rule_id = mres($router['id']);
735
        $sql     = 'WHERE id=?';
736
        $param   = array($rule_id);
737
    }
738
739
    $rules       = dbFetchRows("SELECT * FROM `alert_rules` $sql", $param);
740
    $total_rules = count($rules);
741
    $output      = array(
742
        'status'  => 'ok',
743
        'err-msg' => '',
744
        'count'   => $total_rules,
745
        'rules'   => $rules,
746
    );
747
    $app->response->setStatus('200');
748
    $app->response->headers->set('Content-Type', 'application/json');
749
    echo _json_encode($output);
750
}
751
752
753
function list_alerts()
754
{
755
    global $config;
756
    $app    = \Slim\Slim::getInstance();
757
    $router = $app->router()->getCurrentRoute()->getParams();
758
    if (isset($_GET['state'])) {
759
        $param = array(mres($_GET['state']));
760
    } else {
761
        $param = array('1');
762
    }
763
764
    $sql = '';
765 View Code Duplication
    if (isset($router['id']) && $router['id'] > 0) {
766
        $alert_id = mres($router['id']);
767
        $sql      = 'AND id=?';
768
        array_push($param, $alert_id);
769
    }
770
771
    $alerts       = dbFetchRows("SELECT `D`.`hostname`, `A`.*, `R`.`severity` FROM `alerts` AS `A`, `devices` AS `D`, `alert_rules` AS `R` WHERE `D`.`device_id` = `A`.`device_id` AND `A`.`rule_id` = `R`.`id` AND `A`.`state` IN (?) $sql", $param);
772
    $total_alerts = count($alerts);
773
    $output       = array(
774
        'status'  => 'ok',
775
        'err-msg' => '',
776
        'count'   => $total_alerts,
777
        'alerts'  => $alerts,
778
    );
779
    $app->response->setStatus('200');
780
    $app->response->headers->set('Content-Type', 'application/json');
781
    echo _json_encode($output);
782
}
783
784
785
function add_edit_rule()
786
{
787
    global $config;
788
    $app  = \Slim\Slim::getInstance();
789
    $data = json_decode(file_get_contents('php://input'), true);
790
791
    $status  = 'error';
792
    $message = '';
793
    $code    = 500;
794
795
    $rule_id = mres($data['rule_id']);
796
797
    $device_id = mres($data['device_id']);
798
    if (empty($device_id) && !isset($rule_id)) {
799
        $message = 'Missing the device id or global device id (-1)';
800
    } elseif ($device_id == 0) {
801
        $device_id = '-1';
802
    }
803
804
    $rule = $data['rule'];
805
    if (empty($rule)) {
806
        $message = 'Missing the alert rule';
807
    }
808
809
    $name = mres($data['name']);
810
    if (empty($name)) {
811
        $message = 'Missing the alert rule name';
812
    }
813
814
    $severity = mres($data['severity']);
815
    $sevs     = array(
816
        'ok',
817
        'warning',
818
        'critical',
819
    );
820
    if (!in_array($severity, $sevs)) {
821
        $message = 'Missing the severity';
822
    }
823
824
    $disabled = mres($data['disabled']);
825
    if ($disabled != '0' && $disabled != '1') {
826
        $disabled = 0;
827
    }
828
829
    $count     = mres($data['count']);
830
    $mute      = mres($data['mute']);
831
    $delay     = mres($data['delay']);
832
    $delay_sec = convert_delay($delay);
833
    if ($mute == 1) {
834
        $mute = true;
835
    } else {
836
        $mute = false;
837
    }
838
839
    $extra      = array(
840
        'mute'  => $mute,
841
        'count' => $count,
842
        'delay' => $delay_sec,
843
    );
844
    $extra_json = json_encode($extra);
845
846
    if (!isset($rule_id)) {
847
        if (dbFetchCell('SELECT `name` FROM `alert_rules` WHERE `name`=?', array($name)) == $name) {
848
            $message = 'Addition failed : Name has already been used';
849
        }
850
    } else {
851
        if (dbFetchCell("SELECT name FROM alert_rules WHERE name=? AND id !=? ", array($name, $rule_id)) == $name) {
852
            $message = 'Edition failed : Name has already been used';
853
        }
854
    }
855
856
    if (empty($message)) {
857
        if (is_numeric($rule_id)) {
858
            if (dbUpdate(array('name' => $name, 'rule' => $rule, 'severity' => $severity, 'disabled' => $disabled, 'extra' => $extra_json), 'alert_rules', 'id=?', array($rule_id)) >= 0) {
859
                $status = 'ok';
860
                $code   = 200;
861
            } else {
862
                $message = 'Failed to update existing alert rule';
863
            }
864
        } elseif (dbInsert(array('name' => $name, 'device_id' => $device_id, 'rule' => $rule, 'severity' => $severity, 'disabled' => $disabled, 'extra' => $extra_json), 'alert_rules')) {
865
            $status = 'ok';
866
            $code   = 200;
867
        } else {
868
            $message = 'Failed to create new alert rule';
869
        }
870
    }
871
872
    $output = array(
873
        'status'  => $status,
874
        'err-msg' => $message,
875
    );
876
    $app->response->setStatus($code);
877
    $app->response->headers->set('Content-Type', 'application/json');
878
    echo _json_encode($output);
879
}
880
881
882 View Code Duplication
function delete_rule()
883
{
884
    global $config;
885
    $app     = \Slim\Slim::getInstance();
886
    $router  = $app->router()->getCurrentRoute()->getParams();
887
    $rule_id = mres($router['id']);
888
    $status  = 'error';
889
    $err_msg = '';
890
    $message = '';
891
    $code    = 500;
892
    if (is_numeric($rule_id)) {
893
        $status = 'ok';
894
        $code   = 200;
895
        if (dbDelete('alert_rules', '`id` =  ? LIMIT 1', array($rule_id))) {
896
            $message = 'Alert rule has been removed';
897
        } else {
898
            $message = 'No alert rule by that ID';
899
        }
900
    } else {
901
        $err_msg = 'Invalid rule id has been provided';
902
    }
903
904
    $output = array(
905
        'status'  => $status,
906
        'err-msg' => $err_msg,
907
        'message' => $message,
908
    );
909
    $app->response->setStatus($code);
910
    $app->response->headers->set('Content-Type', 'application/json');
911
    echo _json_encode($output);
912
}
913
914
915 View Code Duplication
function ack_alert()
916
{
917
    global $config;
918
    $app      = \Slim\Slim::getInstance();
919
    $router   = $app->router()->getCurrentRoute()->getParams();
920
    $alert_id = mres($router['id']);
921
    $status   = 'error';
922
    $err_msg  = '';
923
    $message  = '';
924
    $code     = 500;
925
    if (is_numeric($alert_id)) {
926
        $status = 'ok';
927
        $code   = 200;
928
        if (dbUpdate(array('state' => 2), 'alerts', '`id` = ? LIMIT 1', array($alert_id))) {
929
            $message = 'Alert has been acknowledged';
930
        } else {
931
            $message = 'No alert by that ID';
932
        }
933
    } else {
934
        $err_msg = 'Invalid alert has been provided';
935
    }
936
937
    $output = array(
938
        'status'  => $status,
939
        'err-msg' => $err_msg,
940
        'message' => $message,
941
    );
942
    $app->response->setStatus($code);
943
    $app->response->headers->set('Content-Type', 'application/json');
944
    echo _json_encode($output);
945
}
946
947 View Code Duplication
function unmute_alert()
948
{
949
    global $config;
950
    $app      = \Slim\Slim::getInstance();
951
    $router   = $app->router()->getCurrentRoute()->getParams();
952
    $alert_id = mres($router['id']);
953
    $status   = 'error';
954
    $err_msg  = '';
955
    $message  = '';
956
    $code     = 500;
957
    if (is_numeric($alert_id)) {
958
        $status = 'ok';
959
        $code   = 200;
960
        if (dbUpdate(array('state' => 1), 'alerts', '`id` = ? LIMIT 1', array($alert_id))) {
961
            $message = 'Alert has been unmuted';
962
        } else {
963
            $message = 'No alert by that ID';
964
        }
965
    } else {
966
        $err_msg = 'Invalid alert has been provided';
967
    }
968
969
    $output = array(
970
        'status'  => $status,
971
        'err-msg' => $err_msg,
972
        'message' => $message,
973
    );
974
    $app->response->setStatus($code);
975
    $app->response->headers->set('Content-Type', 'application/json');
976
    echo _json_encode($output);
977
}
978
979
980
function get_inventory()
981
{
982
    global $config;
983
    $app      = \Slim\Slim::getInstance();
984
    $router   = $app->router()->getCurrentRoute()->getParams();
985
    $status   = 'error';
986
    $err_msg  = '';
987
    $code     = 500;
988
    $hostname = $router['hostname'];
989
    // use hostname as device_id if it's all digits
990
    $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
991
    $sql       = '';
992
    $params    = array();
993 View Code Duplication
    if (isset($_GET['entPhysicalClass']) && !empty($_GET['entPhysicalClass'])) {
994
        $sql     .= ' AND entPhysicalClass=?';
995
        $params[] = mres($_GET['entPhysicalClass']);
996
    }
997
998 View Code Duplication
    if (isset($_GET['entPhysicalContainedIn']) && !empty($_GET['entPhysicalContainedIn'])) {
999
        $sql     .= ' AND entPhysicalContainedIn=?';
1000
        $params[] = mres($_GET['entPhysicalContainedIn']);
1001
    } else {
1002
        $sql .= ' AND entPhysicalContainedIn="0"';
1003
    }
1004
1005
    if (!is_numeric($device_id)) {
1006
        $err_msg   = 'Invalid device provided';
1007
        $total_inv = 0;
1008
        $inventory = array();
1009
    } else {
1010
        $inventory = dbFetchRows("SELECT * FROM `entPhysical` WHERE 1 $sql", $params);
1011
        $code      = 200;
1012
        $status    = 'ok';
1013
        $total_inv = count($inventory);
1014
    }
1015
1016
    $output = array(
1017
        'status'    => $status,
1018
        'err-msg'   => $err_msg,
1019
        'count'     => $total_inv,
1020
        'inventory' => $inventory,
1021
    );
1022
    $app->response->setStatus($code);
1023
    $app->response->headers->set('Content-Type', 'application/json');
1024
    echo _json_encode($output);
1025
}
1026
1027
1028
function list_oxidized()
1029
{
1030
    global $config;
1031
    $app = \Slim\Slim::getInstance();
1032
    $app->response->headers->set('Content-Type', 'application/json');
1033
1034
    $devices = array();
1035
    $device_types = "'".implode("','", $config['oxidized']['ignore_types'])."'";
1036
    $device_os    = "'".implode("','", $config['oxidized']['ignore_os'])."'";
1037
    foreach (dbFetchRows("SELECT hostname,os,location FROM `devices` LEFT JOIN devices_attribs AS `DA` ON devices.device_id = DA.device_id AND `DA`.attrib_type='override_Oxidized_disable' WHERE `disabled`='0' AND `ignore` = 0 AND (DA.attrib_value = 'false' OR DA.attrib_value IS NULL) AND (`type` NOT IN ($device_types) AND `os` NOT IN ($device_os))") as $device) {
1038
        if ($config['oxidized']['group_support'] == "true") {
1039 View Code Duplication
            foreach ($config['oxidized']['group']['hostname'] as $host_group) {
1040
                if (preg_match($host_group['regex'].'i', $device['hostname'])) {
1041
                    $device['group'] = $host_group['group'];
1042
                    break;
1043
                }
1044
            }
1045
            if (empty($device['group'])) {
1046
                foreach ($config['oxidized']['group']['os'] as $host_group) {
1047
                    if ($host_group['match'] === $device['os']) {
1048
                        $device['group'] = $host_group['group'];
1049
                        break;
1050
                    }
1051
                }
1052
            }
1053
            if (empty($device['group'])) {
1054 View Code Duplication
                foreach ($config['oxidized']['group']['location'] as $host_group) {
1055
                    if (preg_match($host_group['regex'].'i', $device['location'])) {
1056
                        $device['group'] = $host_group['group'];
1057
                        break;
1058
                    }
1059
                }
1060
            }
1061
            if (empty($device['group']) && !empty($config['oxidized']['default_group'])) {
1062
                $device['group'] = $config['oxidized']['default_group'];
1063
            }
1064
        }
1065
        unset($device['location']);
1066
        $devices[] = $device;
1067
    }
1068
1069
    $app->response->headers->set('Content-Type', 'application/json');
1070
    echo _json_encode($devices);
1071
}
1072
1073
function list_bills()
1074
{
1075
    global $config;
1076
    $app = \Slim\Slim::getInstance();
1077
    $router = $app->router()->getCurrentRoute()->getParams();
1078
    $status = 'ok';
1079
    $err_msg = '';
1080
    $message = '';
1081
    $code = 200;
1082
    $bills = array();
1083
    $bill_id = mres($router['bill_id']);
1084
    $bill_ref = mres($_GET['ref']);
1085
    $bill_custid = mres($_GET['custid']);
1086
    if (!empty($bill_custid)) {
1087
        $sql   = '`bill_custid` = ?';
1088
        $param = array($bill_custid);
1089
    } elseif (!empty($bill_ref)) {
1090
        $sql   = '`bill_ref` = ?';
1091
        $param = array($bill_ref);
1092
    } elseif (is_numeric($bill_id)) {
1093
        $sql   = '`bills`.`bill_id` = ?';
1094
        $param = array($bill_id);
1095
    } else {
1096
        $sql   = '';
1097
        $param = array();
1098
    }
1099
1100
    if (count($param) >= 1) {
1101
        $sql = "WHERE $sql";
1102
    }
1103
1104
    foreach (dbFetchRows("SELECT `bills`.*,COUNT(port_id) AS `ports_total` FROM `bills` LEFT JOIN `bill_ports` ON `bill_ports`.`bill_id`=`bills`.`bill_id` $sql GROUP BY `bill_name`,`bill_ref` ORDER BY `bill_name`", $param) as $bill) {
1105
        $rate_data    = $bill;
1106
        $allowed = '';
1107
        $used = '';
1108
        $percent = '';
1109
        $overuse = '';
1110
1111
        if ($bill['bill_type'] == "cdr") {
1112
            $allowed = format_si($bill['bill_cdr'])."bps";
1113
            $used    = format_si($rate_data['rate_95th'])."bps";
1114
            $percent = round(($rate_data['rate_95th'] / $bill['bill_cdr']) * 100, 2);
1115
            $overuse = $rate_data['rate_95th'] - $bill['bill_cdr'];
1116
            $overuse = (($overuse <= 0) ? "-" : format_si($overuse));
1117
        } elseif ($bill['bill_type'] == "quota") {
1118
            $allowed = format_bytes_billing($bill['bill_quota']);
1119
            $used    = format_bytes_billing($rate_data['total_data']);
1120
            $percent = round(($rate_data['total_data'] / ($bill['bill_quota'])) * 100, 2);
1121
            $overuse = $rate_data['total_data'] - $bill['bill_quota'];
1122
            $overuse = (($overuse <= 0) ? "-" : format_bytes_billing($overuse));
1123
        }
1124
        $bill['allowed'] = $allowed;
1125
        $bill['used'] = $used;
1126
        $bill['percent'] = $percent;
1127
        $bill['overuse'] = $overuse;
1128
        $bills[] = $bill;
1129
    }
1130
    $count = count($bills);
1131
    $output = array(
1132
        'status' => $status,
1133
        'message' => $message,
1134
        'err-msg' => $err_msg,
1135
        'count' => $count,
1136
        'bills' => $bills
1137
    );
1138
    $app->response->setStatus($code);
1139
    $app->response->headers->set('Content-Type', 'application/json');
1140
    echo _json_encode($output);
1141
}
1142
1143
function update_device()
1144
{
1145
    global $config;
1146
    $app = \Slim\Slim::getInstance();
1147
    $router = $app->router()->getCurrentRoute()->getParams();
1148
    $status   = 'error';
1149
    $code     = 500;
1150
    $hostname = $router['hostname'];
1151
    // use hostname as device_id if it's all digits
1152
    $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
1153
    $data = json_decode(file_get_contents('php://input'), true);
1154
    $bad_fields = array('device_id','hostname');
1155
    if (empty($data['field'])) {
1156
        $message = 'Device field to patch has not been supplied';
1157
    } elseif (in_array($data['field'], $bad_fields)) {
1158
        $message = 'Device field is not allowed to be updated';
1159
    } else {
1160
        if (is_array($data['field']) && is_array($data['data'])) {
1161
            foreach ($data['field'] as $tmp_field) {
1162
                if (in_array($tmp_field, $bad_fields)) {
1163
                    $message = 'Device field is not allowed to be updated';
1164
                }
1165
            }
1166
            if ($message == '' && count($data['field']) == count($data['data'])) {
1167
                for ($x=0; $x<count($data['field']); $x++) {
1168
                    $update[mres($data['field'][$x])] = mres($data['data'][$x]);
1169
                }
1170 View Code Duplication
                if (dbUpdate($update, 'devices', '`device_id`=?', array($device_id)) >= 0) {
1171
                    $status = 'ok';
1172
                    $code = 200;
1173
                    $message = 'Device fields have been updated';
1174
                } else {
1175
                    $message = 'Device fields failed to be updated';
1176
                }
1177
            } elseif ($message == '') {
1178
                $message = 'Device fields failed to be updated as the number of fields ('.count($data['field']).') does not match the supplied data ('.count($data['data']).')';
1179
            }
1180
        } elseif (dbUpdate(array(mres($data['field']) => mres($data['data'])), 'devices', '`device_id`=?', array($device_id)) >= 0) {
1181
            $status = 'ok';
1182
            $message = 'Device ' . mres($data['field']) . ' field has been updated';
1183
            $code = 200;
1184
        } else {
1185
            $message = 'Device ' . mres($data['field']) . ' field failed to be updated';
1186
        }
1187
    }
1188
    $output = array(
1189
        'status'  => $status,
1190
        'message' => $message,
1191
    );
1192
    $app->response->setStatus($code);
1193
    $app->response->headers->set('Content-Type', 'application/json');
1194
    echo _json_encode($output);
1195
}
1196
1197
function get_device_groups()
1198
{
1199
    $app = \Slim\Slim::getInstance();
1200
    $router = $app->router()->getCurrentRoute()->getParams();
1201
    $status   = 'error';
1202
    $code     = 404;
1203
    $hostname = $router['hostname'];
1204
    // use hostname as device_id if it's all digits
1205
    $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
1206
    if (is_numeric($device_id)) {
1207
        $groups = GetGroupsFromDevice($device_id, 1);
1208
    } else {
1209
        $groups = GetDeviceGroups();
1210
    }
1211
    if (empty($groups)) {
1212
        $message = 'No device groups found';
1213
    } else {
1214
        $status = 'ok';
1215
        $code = 200;
1216
        $message = 'Found ' . count($groups) . ' device groups';
1217
    }
1218
1219
    $output = array(
1220
        'status'  => $status,
1221
        'message' => $message,
1222
        'count'   => count($groups),
1223
        'groups'  => $groups,
1224
    );
1225
    $app->response->setStatus($code);
1226
    $app->response->headers->set('Content-Type', 'application/json');
1227
    echo _json_encode($output);
1228
}
1229
1230
function get_devices_by_group()
1231
{
1232
    $app      = \Slim\Slim::getInstance();
1233
    $router   = $app->router()->getCurrentRoute()->getParams();
1234
    $status   = 'error';
1235
    $code     = 404;
1236
    $count    = 0;
1237
    $name = urldecode($router['name']);
1238
    $devices = array();
1239
    if (empty($name)) {
1240
        $message = 'No device group name provided';
1241
    } else {
1242
        $group_id = dbFetchCell("SELECT `id` FROM `device_groups` WHERE `name`=?", array($name));
1243
        $devices = GetDevicesFromGroup($group_id, true);
1244
        $count = count($devices);
1245 View Code Duplication
        if (empty($devices)) {
1246
            $message = 'No devices found in group ' . $name;
1247
        } else {
1248
            $message = "Found $count in group $name";
1249
            $status = 'ok';
1250
            $code = 200;
1251
        }
1252
    }
1253
    $output = array(
1254
        'status'  => $status,
1255
        'message' => $message,
1256
        'count'   => $count,
1257
        'devices' => $devices,
1258
    );
1259
1260
    $app->response->setStatus($code);
1261
    $app->response->headers->set('Content-Type', 'application/json');
1262
    echo _json_encode($output);
1263
}
1264
1265
function list_ipsec()
1266
{
1267
    $app      = \Slim\Slim::getInstance();
1268
    $router   = $app->router()->getCurrentRoute()->getParams();
1269
    $status   = 'error';
1270
    $code     = 404;
1271
    $message  = '';
1272
    $hostname = $router['hostname'];
1273
    // use hostname as device_id if it's all digits
1274
    $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
1275
    if (!is_numeric($device_id)) {
1276
        $message = "No valid hostname or device ID provided";
1277
    } else {
1278
        $ipsec  = dbFetchRows("SELECT `D`.`hostname`, `I`.* FROM `ipsec_tunnels` AS `I`, `devices` AS `D` WHERE `I`.`device_id`=? AND `D`.`device_id` = `I`.`device_id`", array($device_id));
1279
        $total  = count($ipsec);
1280
        $status = 'ok';
1281
        $code   = 200;
1282
    }
1283
1284
    $output  = array(
1285
        'status'  => $status,
1286
        'err-msg' => $message,
1287
        'count'   => $total,
0 ignored issues
show
The variable $total does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1288
        'ipsec'  => $ipsec,
1289
    );
1290
    $app->response->setStatus($code);
1291
    $app->response->headers->set('Content-Type', 'application/json');
1292
    echo _json_encode($output);
1293
}
1294
1295
function list_arp()
1296
{
1297
    $app      = \Slim\Slim::getInstance();
1298
    $router   = $app->router()->getCurrentRoute()->getParams();
1299
    $status   = 'error';
1300
    $code     = 404;
1301
    $message  = '';
1302
    $ip       = $router['ip'];
1303
    if (empty($ip)) {
1304
        $message = "No valid IP provided";
1305
    } else {
1306
        $code = 200;
1307
        $status = 'ok';
1308
        if ($ip === "all") {
1309
            $hostname =  mres($_GET['device']);
1310
            $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
1311
            $arp = dbFetchRows("SELECT `ipv4_mac`.* FROM `ipv4_mac` LEFT JOIN `ports` ON `ipv4_mac`.`port_id` = `ports`.`port_id` WHERE `ports`.`device_id` = ?", array($device_id));
1312
        } else {
1313
            $arp = dbFetchRows("SELECT * FROM `ipv4_mac` WHERE `ipv4_address`=?", array($ip));
1314
        }
1315
        $total  = count($arp);
1316
    }
1317
    $output  = array(
1318
        'status'  => $status,
1319
        'err-msg' => $message,
1320
        'count'   => $total,
0 ignored issues
show
The variable $total does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1321
        'arp'  => $arp,
1322
    );
1323
    $app->response->setStatus($code);
1324
    $app->response->headers->set('Content-Type', 'application/json');
1325
    echo _json_encode($output);
1326
}
1327
function list_services()
1328
{
1329
    global $config;
1330
    $app      = \Slim\Slim::getInstance();
1331
    $router   = $app->router()->getCurrentRoute()->getParams();
1332
    $status   = 'ok';
1333
    $code     = 200;
1334
    $message  = '';
1335
    $host_par = array();
1336
    $sql_param = array();
1337
    $services = array();
1338
    $where    = '';
1339
    $devicewhere = '';
1340
    
1341
    // Filter BY STATE
1342
    if (isset($_GET['state'])) {
1343
        $where  = " AND S.service_status= ? AND S.service_disabled='0' AND S.service_ignore='0'";
1344
        $host_par[] = $_GET['state'];
1345
        
1346
        if (!is_numeric($_GET['state'])) {
1347
            $status   = 'error';
1348
            $message = "No valid service state provided, valid option is 0=Ok, 1=Warning, 2=Critical";
1349
        }
1350
    }
1351
    
1352
    // GET BY HOST
1353
    if (isset($router['hostname'])) {
1354
        $hostname = $router['hostname'];
1355
        $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
1356
        
1357
        $where .= " AND S.device_id = ?";
1358
        $host_par[] = $device_id;
1359
        
1360
        if (!is_numeric($device_id)) {
1361
            $status   = 'error';
1362
            $message = "No valid hostname or device id provided";
1363
        }
1364
    }
1365
1366
    // DEVICE
1367
    $host_sql = 'SELECT * FROM devices AS D, services AS S WHERE D.device_id = S.device_id '.$where.' GROUP BY D.hostname ORDER BY D.hostname';
1368
    
1369
    // SERVICE
1370
    foreach (dbFetchRows($host_sql, $host_par) as $device) {
1371
        $device_id = $device['device_id'];
1372
        $sql_param[0] = $device_id;
1373
        
1374
        // FILTER BY TYPE
1375
        if (isset($_GET['type'])) {
1376
            $devicewhere  = " AND `service_type` LIKE ?";
1377
            $sql_param[1] = $_GET['type'];
1378
        }
1379
1380
        $services[] = dbFetchRows("SELECT * FROM `services` WHERE `device_id` = ?".$devicewhere, $sql_param);
1381
    }
1382
    $count = count($services);
1383
    $output = array(
1384
        'status'  => $status,
1385
        'err-msg' => $message,
1386
        'count'   => $count,
1387
        'services' => $services,
1388
    );
1389
1390
    $app->response->setStatus($code);
1391
    $app->response->headers->set('Content-Type', 'application/json');
1392
    echo _json_encode($output);
1393
}
1394