Repository navigation
Expand file tree
/
Copy pathrouter-devices.php
More file actions
1205 lines (1023 loc) · 43 KB
/
Copy pathrouter-devices.php
File metadata and controls
1205 lines (1023 loc) · 43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types = 1);
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDTool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
chdir('../../');
require('./include/auth.php');
require_once($config['library_path'] . '/poller.php');
require_once(__DIR__ . '/includes/functions.php');
set_default_action();
set_request_var('tab', 'devices');
switch (get_request_var('action')) {
case 'viewdebug':
plugin_routerconfigs_view_device_debug();
break;
case 'viewconfig':
view_device_config();
break;
case 'actions':
actions_devices();
break;
case 'save':
save_devices();
break;
case 'edit':
if (read_config_option('routerconfigs_presentation') == 'console') {
top_header();
} else {
general_header();
}
display_tabs();
edit_devices();
bottom_footer();
break;
default:
if (read_config_option('routerconfigs_presentation') == 'console') {
top_header();
} else {
general_header();
}
display_tabs();
show_devices();
bottom_footer();
break;
}
/**
* Displays the raw, base64-decoded debug log captured for a device's
* last connection attempt. Invoked from this file's dispatcher when the
* request's 'action' is 'viewdebug'.
*
* @return void Redirects back to the list if the device isn't found;
* otherwise outputs the debug log HTML directly.
*/
function plugin_routerconfigs_view_device_debug() {
// ================= input validation =================
get_filter_request_var('id');
// ====================================================
$device = [];
if (!isempty_request_var('id')) {
$device = db_fetch_row_prepared('SELECT *
FROM plugin_routerconfigs_devices
WHERE id = ?',
[get_request_var('id')]);
}
if (isset($device['id'])) {
if (read_config_option('routerconfigs_presentation') == 'console') {
top_header();
} else {
general_header();
}
display_tabs();
html_start_box('', '100%', false, 4, 'center', '');
form_alternate_row();
print '<td><h2>' . __('Debug for %s (%s)<br><br>', html_escape($device['hostname']), html_escape($device['ipaddress']), 'routerconfigs');
print '</h2><textarea rows=36 cols=120>';
print html_escape(base64_decode($device['debug'], true));
print '</textarea></td></tr>';
html_end_box(false);
} else {
header('Location: router-devices.php?header=false');
exit;
}
}
/**
* Displays the most recent stored backup configuration file for a
* device. Invoked from this file's dispatcher when the request's
* 'action' is 'viewconfig'.
*
* @return void Outputs the backup file content via
* plugin_routerconfigs_view_device_config().
*/
function view_device_config() {
// ================= input validation =================
get_filter_request_var('id');
// ====================================================
$device = [];
plugin_routerconfigs_view_device_config(0, get_request_var('id'), 'router-devices.php');
}
/**
* Builds the "No Change" sentinel value used by the bulk device-edit
* confirmation form so that leaving a field alone is distinguishable from
* selecting an empty value (e.g. Disabled, or the Inherit connection type).
*
* @return string The sentinel value.
*/
function plugin_routerconfigs_bulk_nochange(): string {
return '__nochange__';
}
/**
* Loads an id => name option list for a bulk-edit dropdown from a simple
* two-column SQL query. Used for the Account and Device Type selectors.
*
* @param string $sql The SQL returning id and name columns.
*
* @return array<int|string, string> The id => name option map.
*/
function plugin_routerconfigs_bulk_options_sql(string $sql): array {
$options = [];
foreach (db_fetch_assoc_prepared($sql, []) as $r) {
$options[$r['id']] = $r['name'];
}
return $options;
}
/**
* Renders one row of the bulk device-edit confirmation form: a labelled
* dropdown whose first option is "No Change" (the sentinel) followed by
* the supplied value => label options.
*
* @param string $label The field label.
* @param string $name The POSTed field name (bulk_*).
* @param array $options The value => label options to offer.
*
* @return void Outputs an HTML table row directly.
*/
function plugin_routerconfigs_bulk_edit_row(string $label, string $name, array $options): void {
$nochange = plugin_routerconfigs_bulk_nochange();
print "<tr class='even'><td class='nowrap' style='padding-left:10px;width:25%;'>" . html_escape($label) . "</td><td>";
print "<select name='" . html_escape($name) . "' id='" . html_escape($name) . "'>";
print "<option value='" . html_escape($nochange) . "' selected>" . __esc('No Change', 'routerconfigs') . '</option>';
foreach ($options as $value => $text) {
print "<option value='" . html_escape((string) $value) . "'>" . html_escape((string) $text) . '</option>';
}
print '</select></td></tr>';
}
/**
* Reads the bulk device-edit confirmation form and returns the validated
* column => value map of the fields the operator actually changed (fields
* left on the "No Change" sentinel are omitted). Values are checked by
* plugin_routerconfigs_bulk_edit_validate(); when any is invalid, an error
* is raised for each and null is returned so nothing is applied. Invoked
* from actions_devices().
*
* @return array<string, int|string>|null The column => value map to apply,
* or null when a value is invalid.
*/
function plugin_routerconfigs_bulk_edit_set(): ?array {
$nochange = plugin_routerconfigs_bulk_nochange();
$input = [];
foreach (['enabled', 'sched_type', 'recur_every', 'connecttype', 'account', 'devicetype'] as $column) {
if (isset_request_var('bulk_' . $column) && get_nfilter_request_var('bulk_' . $column) !== $nochange) {
$input[$column] = get_nfilter_request_var('bulk_' . $column);
}
}
$result = plugin_routerconfigs_bulk_edit_validate($input);
if (cacti_sizeof($result['errors'])) {
foreach ($result['errors'] as $index => $error) {
raise_message('bulk_edit_invalid_' . $index, $error, MESSAGE_LEVEL_ERROR);
}
return null;
}
return $result['set'];
}
/**
* Handles the bulk-actions form for the Devices list (delete/enable/
* disable/clear SSH host key/manual backup). Manual backup launches a
* background router-download.php process immediately without a
* confirmation step; the other actions render a confirmation dialog on
* first display and apply the chosen action to each selected device once
* confirmed. Invoked from this file's dispatcher when the request's
* 'action' is 'actions'.
*
* @return void Either redirects back to the list after applying the
* action, or prints the confirmation dialog and returns
* nothing.
*
* @global array $rc_device_actions Map of bulk-action ids to their
* display labels, used for the
* confirmation dialog title.
* @global array $config Cacti global configuration array;
* used to resolve the PHP binary and
* router-download.php path for the
* manual backup action.
*/
function actions_devices() {
global $rc_device_actions, $rc_connection_types, $rc_schedules_recur, $config;
if (isset_request_var('selected_items')) {
$selected_items = sanitize_unserialize_selected_items(get_nfilter_request_var('selected_items'));
if ($selected_items != false) {
switch(get_nfilter_request_var('drp_action')) {
case RCONFIG_DEVICE_DELETE:
for ($i = 0; $i < cacti_count($selected_items); $i++) {
db_execute_prepared('DELETE FROM plugin_routerconfigs_devices
WHERE id = ?',
[$selected_items[$i]]);
}
break;
case RCONFIG_DEVICE_ENABLE:
for ($i = 0; $i < cacti_count($selected_items); $i++) {
db_execute_prepared('UPDATE plugin_routerconfigs_devices
SET enabled="on"
WHERE id = ?',
[$selected_items[$i]]);
}
break;
case RCONFIG_DEVICE_DISABLE:
for ($i = 0; $i < cacti_count($selected_items); $i++) {
db_execute_prepared('UPDATE plugin_routerconfigs_devices
SET enabled=""
WHERE id = ?',
[$selected_items[$i]]);
}
break;
case RCONFIG_DEVICE_CLEAR_SSH_HOSTKEY:
for ($i = 0; $i < cacti_count($selected_items); $i++) {
plugin_routerconfigs_clear_ssh_hostkey($selected_items[$i], 'device action by user ' . ($_SESSION['sess_user_id'] ?? 'unknown'));
}
break;
case RCONFIG_DEVICE_EDIT:
$set = plugin_routerconfigs_bulk_edit_set();
if ($set === null) {
break;
}
if (cacti_sizeof($set)) {
$result = plugin_routerconfigs_bulk_edit_apply($selected_items, $set, time());
if (cacti_sizeof($result['invalid'])) {
raise_message('bulk_edit_invalid_schedule', __('No devices were changed: the new schedule cannot run on device id(s) %s, because their Months, Days of Month, Weeks of Month or Days of Week are missing or never occur. Set the schedule on those devices individually.', implode(', ', $result['invalid']), 'routerconfigs'), MESSAGE_LEVEL_ERROR);
} else {
raise_message('bulk_edit_done', __('Updated settings on %d device(s).', $result['updated'], 'routerconfigs'), MESSAGE_LEVEL_INFO);
}
} else {
raise_message('bulk_edit_none', __('No settings were changed; every field was left on "No Change".', 'routerconfigs'), MESSAGE_LEVEL_WARN);
}
break;
}
}
header('Location: router-devices.php?header=false');
exit;
}
// setup some variables
$device_list = '';
$device_array = [];
// loop through each of the devices selected on the previous page and get more info about them
foreach ($_POST as $var => $val) {
if (preg_match('/^chk_([0-9]+)$/', $var, $matches)) {
// ================= input validation =================
input_validate_input_number($matches[1]);
// ====================================================
$device_list .= '<li>' . db_fetch_cell_prepared('SELECT hostname
FROM plugin_routerconfigs_devices
WHERE id = ?',
[$matches[1]]) . '</li>';
$device_array[] = $matches[1];
}
}
if (cacti_sizeof($device_array)) {
if (get_nfilter_request_var('drp_action') == RCONFIG_DEVICE_BACKUP) { // Backup
$command_string = trim(read_config_option('path_php_binary'));
if (trim($command_string) == '') {
$command_string = 'php';
}
$extra_args = ' -q ' . $config['base_path'] . '/plugins/routerconfigs/router-download.php' .
' --devices=' . implode(',',$device_array);
plugin_routerconfigs_log(__("DEBUG: Executing manual backup using '%s' with arguments '%s'",$command_string,$extra_args,'routerconfigs'));
exec_background($command_string, $extra_args);
raise_message('backup_started', __('Router Backup started. Check the Date Backup column or the Cacti Log for completion status and timing', 'routerconfigs'), MESSAGE_LEVEL_INFO);
header('Location: router-devices.php?header=false');
exit;
}
}
if (read_config_option('routerconfigs_presentation') == 'console') {
top_header();
} else {
general_header();
}
form_start('router-devices.php');
$drp_action = (int) get_nfilter_request_var('drp_action');
if ($drp_action > 0 && array_key_exists($drp_action, $rc_device_actions)) {
html_start_box($rc_device_actions[$drp_action], '60%', false, 3, 'center', '');
} else {
html_start_box('', '60%', false, 3, 'center', '');
}
if (cacti_sizeof($device_array)) {
switch ($drp_action) {
case RCONFIG_DEVICE_DELETE:
print "<tr>
<td colspan='2' class='textArea'>
<p>" . __('Click \'Continue\' to Delete the following device(s).', 'routerconfigs') . "</p>
<p><ul>$device_list</ul></p>
</td>
</tr>";
$save_html = "<input class='cactiReturnTo' type='button' value='" . __esc('Cancel', 'routerconfigs') . "'> <input type='submit' value='" . __esc('Continue', 'routerconfigs') . "' title='" . __esc('Delete Device(s)', 'routerconfigs') . "'>";
break;
case RCONFIG_DEVICE_ENABLE:
print "<tr>
<td colspan='2' class='textArea'>
<p>" . __('Click \'Continue\' to Enable the following device(s).', 'routerconfigs') . "</p>
<p><ul>$device_list</ul></p>
</td>
</tr>";
$save_html = "<input class='cactiReturnTo' type='button' value='" . __esc('Cancel', 'routerconfigs') . "'> <input type='submit' value='" . __esc('Continue', 'routerconfigs') . "' title='" . __esc('Enable Device(s)', 'routerconfigs') . "'>";
break;
case RCONFIG_DEVICE_DISABLE:
print "<tr>
<td colspan='2' class='textArea'>
<p>" . __('Click \'Continue\' to Disable the following device(s).', 'routerconfigs') . "</p>
<p><ul>$device_list</ul></p>
</td>
</tr>";
$save_html = "<input class='cactiReturnTo' type='button' value='" . __esc('Cancel', 'routerconfigs') . "'> <input type='submit' value='" . __esc('Continue', 'routerconfigs') . "' title='" . __esc('Disable Device(s)', 'routerconfigs') . "'>";
break;
case RCONFIG_DEVICE_CLEAR_SSH_HOSTKEY:
print "<tr>
<td colspan='2' class='textArea'>
<p>" . __('Click \'Continue\' to clear the stored SSH host key for the following device(s). The next SSH connection will trust and record the key it receives.', 'routerconfigs') . "</p>
<p><ul>$device_list</ul></p>
</td>
</tr>";
$save_html = "<input class='cactiReturnTo' type='button' value='" . __esc('Cancel', 'routerconfigs') . "'> <input type='submit' value='" . __esc('Continue', 'routerconfigs') . "' title='" . __esc('Clear SSH Host Key(s)', 'routerconfigs') . "'>";
break;
case RCONFIG_DEVICE_EDIT:
print "<tr>
<td colspan='2' class='textArea'>
<p>" . __('Set one or more of the following settings on the selected device(s). Fields left on \'No Change\' are not modified.', 'routerconfigs') . "</p>
<p><ul>$device_list</ul></p>
</td>
</tr>";
plugin_routerconfigs_bulk_edit_row(__('Enabled', 'routerconfigs'), 'bulk_enabled', [
'on' => __('Enabled', 'routerconfigs'),
'' => __('Disabled', 'routerconfigs'),
]);
plugin_routerconfigs_bulk_edit_row(__('Schedule Type', 'routerconfigs'), 'bulk_sched_type', plugin_routerconfigs_sched_bulk_types());
plugin_routerconfigs_bulk_edit_row(__('Rerun Every', 'routerconfigs'), 'bulk_recur_every', $rc_schedules_recur);
plugin_routerconfigs_bulk_edit_row(__('Connection Type', 'routerconfigs'), 'bulk_connecttype', $rc_connection_types);
plugin_routerconfigs_bulk_edit_row(__('Authentication Account', 'routerconfigs'), 'bulk_account', plugin_routerconfigs_bulk_options_sql('SELECT id, name FROM plugin_routerconfigs_accounts ORDER BY name'));
plugin_routerconfigs_bulk_edit_row(__('Device Type', 'routerconfigs'), 'bulk_devicetype', plugin_routerconfigs_bulk_options_sql('SELECT id, name FROM plugin_routerconfigs_devicetypes ORDER BY name'));
$save_html = "<input class='cactiReturnTo' type='button' value='" . __esc('Cancel', 'routerconfigs') . "'> <input type='submit' value='" . __esc('Continue', 'routerconfigs') . "' title='" . __esc('Apply settings to Device(s)', 'routerconfigs') . "'>";
break;
default:
$save_html = "<input class='cactiReturnTo' type='button' value='" . __esc('Return', 'routerconfigs') . "'>";
break;
}
} else {
print "<tr><td class='even'><span class='textError'>" . __('You must select at least Router Device.', 'routerconfigs') . "</span></td></tr>\n";
$save_html = "<input class='cactiReturnTo' type='button' value='" . __esc('Return', 'routerconfigs') . "'>";
}
print "<tr>
<td class='saveRow'>
<input type='hidden' name='action' value='actions'>
<input type='hidden' name='selected_items' value='" . serialize($device_array) . "'>
<input type='hidden' name='drp_action' value='" . get_request_var('drp_action') . "'>
$save_html
</td>
</tr>";
html_end_box();
form_end();
bottom_footer();
}
/**
* Validates and saves a single router device's configuration (hostname/
* IP, account/device type, connection settings, schedule), clearing the
* recorded SSH host key when the device's IP address has changed so the
* next connection re-trusts the new endpoint's key. Invoked from this
* file's dispatcher when the request's 'action' is 'save'.
*
* @return void Redirects back to the edit form for this device (or the
* list, on success); does not return a value.
*/
function save_devices() {
// ================= input validation =================
get_filter_request_var('id');
get_filter_request_var('devicetype');
get_filter_request_var('sched_type');
get_filter_request_var('recur_every');
// ====================================================
$previous_endpoint = false;
if (isset_request_var('id')) {
$save['id'] = get_request_var('id');
if ($save['id'] !== '') {
$previous_endpoint = db_fetch_row_prepared('SELECT ipaddress, nextbackup, ' . implode(', ', plugin_routerconfigs_schedule_fields()) . '
FROM plugin_routerconfigs_devices
WHERE id = ?',
[$save['id']]);
}
} else {
$save['id'] = '';
}
if (isset_request_var('enabled')) {
$save['enabled'] = 'on';
} else {
$save['enabled'] = '';
}
$save['hostname'] = get_nfilter_request_var('hostname');
$save['ipaddress'] = get_nfilter_request_var('ipaddress');
$save['tftpserver'] = get_nfilter_request_var('tftpserver');
$save['directory'] = get_nfilter_request_var('directory');
$save['account'] = get_nfilter_request_var('account');
$save['devicetype'] = get_nfilter_request_var('devicetype');
$save['sched_type'] = get_nfilter_request_var('sched_type');
$save['recur_every'] = get_nfilter_request_var('recur_every');
$save['connecttype'] = get_nfilter_request_var('connecttype');
$save['timeout'] = get_nfilter_request_var('timeout');
$save['sleep'] = get_nfilter_request_var('sleep');
$save['elevated'] = get_nfilter_request_var('elevated');
if (!plugin_routerconfigs_schedule_valid_type($save['sched_type']) || !plugin_routerconfigs_schedule_valid_recur($save['recur_every'])) {
raise_message('rc_sched_err', __('The selected Schedule Type or Rerun Every is not valid.', 'routerconfigs'), MESSAGE_LEVEL_ERROR);
header('Location: router-devices.php?header=false&action=edit&id=' . (isset_request_var('id') ? get_request_var('id') : 0));
exit;
}
$sched_post = [];
foreach (['day_of_week', 'month', 'day_of_month', 'monthly_week', 'monthly_day'] as $sched_field) {
$sched_post[$sched_field] = isset_request_var($sched_field) ? get_nfilter_request_var($sched_field) : [];
}
$sched_error = plugin_routerconfigs_schedule_fields_valid($sched_post);
if ($sched_error === '') {
$save = plugin_routerconfigs_schedule_augment_save($save, $sched_post);
$sched_error = plugin_routerconfigs_schedule_validate($save);
}
if ($sched_error !== '') {
raise_message('rc_sched_err', $sched_error, MESSAGE_LEVEL_ERROR);
header('Location: router-devices.php?header=false&action=edit&id=' . (isset_request_var('id') ? get_request_var('id') : 0));
exit;
}
$save = plugin_routerconfigs_schedule_prepare_save(is_array($previous_endpoint) ? $previous_endpoint : [], $save, time());
$id = sql_save($save, 'plugin_routerconfigs_devices', 'id');
if ($id && is_array($previous_endpoint) &&
plugin_routerconfigs_connection_target_changed($previous_endpoint, $save)) {
plugin_routerconfigs_clear_ssh_hostkey($id, 'connection target changed');
}
if (is_error_message()) {
header('Location: router-devices.php?header=false&action=edit&id=' . (empty($id) ? get_request_var('id') : $id));
exit;
}
header('Location: router-devices.php?header=false');
exit;
}
/**
* Renders the add/edit form for a single router device, pre-populating
* its fields (except password, which is always blanked) and a display-
* only SSH host key fingerprint when editing an existing device.
* Invoked from this file's dispatcher when the request's 'action' is
* 'edit'.
*
* @return void Outputs the edit form HTML directly.
*
* @global array $rc_device_edit_fields The edit form's field
* definitions, filled in here with
* the device's current values.
*/
function edit_devices() {
global $rc_device_edit_fields;
// ================= input validation =================
get_filter_request_var('id');
// ====================================================
$account = [];
if (!isempty_request_var('id')) {
$account = db_fetch_row_prepared('SELECT * FROM plugin_routerconfigs_devices WHERE id = ?', [(int) get_request_var('id')]);
$account = is_array($account) ? $account : [];
if (!isset($account['id'])) {
header('Location: router-devices.php?header=false');
exit;
}
$account['password'] = '';
$account['ssh_hostkey_display'] = empty($account['ssh_fingerprint']) ?
'<em>' . __esc('Not recorded', 'routerconfigs') . '</em>' :
'<code>' . html_escape($account['ssh_hostkey_type'] . ' ' . $account['ssh_fingerprint']) . '</code>';
$header_label = __('Router: [edit: %s]', $account['hostname'], 'routerconfigs');
} else {
$account['ssh_hostkey_display'] = '<em>' . __esc('Not recorded', 'routerconfigs') . '</em>';
$header_label = __('Router: [new]', 'routerconfigs');
}
form_start('router-devices.php', 'chk');
html_start_box($header_label, '100%', false, 3, 'center', '');
draw_edit_form(
[
'config' => ['no_form_tag' => true, 'form_name' => 'chk'],
'fields' => inject_form_variables($rc_device_edit_fields, $account)
]
);
html_end_box();
form_save_button('router-devices.php');
?>
<script type='text/javascript' <?php print plugin_routerconfigs_csp_nonce(); ?>>
function rcToggleScheduleRows() {
var t = parseInt($('#sched_type').val(), 10);
var weekly = (t === <?php print SCHEDULE_WEEKLY; ?>);
var weekday = weekly && ($('#day_of_week').val() || []).length > 0;
// Selected weekdays run every week, so Rerun Every does not apply.
var recur = (t === <?php print SCHEDULE_DAILY; ?> || t === <?php print SCHEDULE_HOURLY; ?> || (weekly && !weekday));
var monthly = (t === <?php print SCHEDULE_MONTHLY; ?>);
var onday = (t === <?php print SCHEDULE_MONTHLY_ON_DAY; ?>);
$('#row_recur_every').toggle(recur);
$('#row_day_of_week').toggle(weekly);
$('#row_month').toggle(monthly || onday);
$('#row_day_of_month').toggle(monthly);
$('#row_monthly_week').toggle(onday);
$('#row_monthly_day').toggle(onday);
}
$(function() {
$('#sched_type, #day_of_week').change(rcToggleScheduleRows);
rcToggleScheduleRows();
});
</script>
<?php
}
/**
* Validates and stores the Devices list's filter/sort/pagination
* variables (device type, account, elevated flag, free-text search,
* sort column/direction) in the session. Called from show_devices()
* before rendering the list.
*
* @return void
*/
function devices_validate_vars() {
// ================= input validation and session storage =================
$filters = [
'rows' => [
'filter' => FILTER_VALIDATE_INT,
'pageset' => true,
'default' => '-1'
],
'page' => [
'filter' => FILTER_VALIDATE_INT,
'default' => '1'
],
'filter' => [
'filter' => FILTER_CALLBACK,
'pageset' => true,
'default' => '',
'options' => ['options' => 'sanitize_search_string']
],
'sort_column' => [
'filter' => FILTER_CALLBACK,
'default' => 'hostname',
'options' => ['options' => 'sanitize_search_string']
],
'sort_direction' => [
'filter' => FILTER_CALLBACK,
'default' => 'ASC',
'options' => ['options' => 'sanitize_search_string']
],
'devicetype' => [
'filter' => FILTER_VALIDATE_INT,
'pageset' => true,
'default' => '-1'
],
'elevated' => [
'filter' => FILTER_CALLBACK,
'default' => '',
'options' => ['options' => 'sanitize_search_string']
],
'account' => [
'filter' => FILTER_VALIDATE_INT,
'pageset' => true,
'default' => '-1'
],
];
validate_store_request_vars($filters, 'sess_rc_dev');
// ================= input validation =================
}
/**
* Adds a date => label entry to an accumulating array only if that date
* isn't already present, preserving the first label seen for a given
* date. Called from show_devices() while building the last-backup date
* summary column.
*
* @param array $date_array Reference, the accumulating date => label
* map.
* @param string $date The date key to add.
* @param string $text The label to associate with $date if not
* already present.
*
* @return void
*/
function addDateToArray(&$date_array, $date, $text) {
if (!array_key_exists($date, $date_array)) {
$date_array[$date] = $text;
}
}
/**
* Renders the main Devices list page: validates the request, draws the
* filter toolbar, and prints the paginated, sortable table of configured
* router devices with their connection/backup status. Invoked from this
* file's dispatcher for the default (no 'action') request.
*
* @return void Outputs the list page HTML directly.
*
* @global mixed $host Reserved/declared for parity with
* other functions in this file; not
* used directly here.
* @global mixed $username Reserved/declared for parity with
* other functions in this file; not
* used directly here.
* @global mixed $password Reserved/declared for parity with
* other functions in this file; not
* used directly here.
* @global mixed $command Reserved/declared for parity with
* other functions in this file; not
* used directly here.
* @global array $config Cacti global configuration array.
* @global array $rc_device_actions Map of bulk-action ids to their
* display labels, used to populate the
* actions dropdown.
* @global array $item_rows Rows-per-page options offered by
* Cacti core, used to populate the
* 'rows' select list.
*/
function show_devices() {
global $host, $username, $password, $command;
global $config, $rc_device_actions, $item_rows;
devices_validate_vars();
if (get_request_var('rows') == -1) {
$num_rows = read_config_option('num_rows_table');
} else {
$num_rows = get_request_var('rows');
}
if (isset_request_var('page')) {
$page = get_request_var('page');
} else {
$page = 1;
}
$sql_where = '';
$sql_params = [];
$sql_limit = 'LIMIT ' . $num_rows * ($page - 1) . ', ' . $num_rows;
$sql_order = get_order_string();
if (get_request_var('account') != '-1') {
$sql_where .= ($sql_where == '' ? 'WHERE' : 'AND') . ' account = ?';
$sql_params[] = get_request_var('account');
}
if (get_request_var('devicetype') != '-1') {
$sql_where .= ($sql_where == '' ? 'WHERE' : 'AND') . ' devicetype = ?';
$sql_params[] = get_request_var('devicetype');
}
if (get_request_var('filter') != '') {
$sql_where .= ($sql_where == '' ? 'WHERE' : 'AND') . ' (rc_d.id LIKE ? OR rc_d.ipaddress LIKE ? OR
rc_d.hostname LIKE ? OR rc_d.directory LIKE ? OR rc_d.account LIKE ? OR
rc_d.device LIKE ? OR rc_d.lastuser LIKE ?)';
$sql_params[] = '%' . get_request_var('filter') . '%';
$sql_params[] = '%' . get_request_var('filter') . '%';
$sql_params[] = '%' . get_request_var('filter') . '%';
$sql_params[] = '%' . get_request_var('filter') . '%';
$sql_params[] = '%' . get_request_var('filter') . '%';
$sql_params[] = '%' . get_request_var('filter') . '%';
$sql_params[] = '%' . get_request_var('filter') . '%';
}
$total_rows = db_fetch_cell_prepared("SELECT COUNT(*)
FROM plugin_routerconfigs_devices AS rc_d
$sql_where",
$sql_params);
$result = db_fetch_assoc_prepared("SELECT *
FROM (
SELECT
rc_d.id, rc_d.enabled, rc_d.ipaddress, rc_d.tftpserver, rc_d.hostname, rc_d.directory,
rc_d.account, rc_d.lastchange, rc_d.device,
rc_d.lastuser, rc_d.schedule, rc_d.sched_type, rc_d.recur_every, rc_d.lasterror,
rc_d.lastbackup, rc_d.nextbackup, rc_d.lastattempt,
rc_d.nextattempt, IFNULL(rc_dt.name,'') as devicetype,
rc_dt.id as devicetypeid,
IF(IFNULL(rc_d.connecttype,'')='',
IF(IFNULL(rc_dt.connecttype,'')='',
rc_sc.value,
rc_dt.connecttype
),
rc_d.connecttype
) AS connecttype,
IF(IFNULL(rc_d.sleep,'')='',
IF(IFNULL(rc_dt.sleep,'')='',
rc_ss.value,
rc_dt.sleep
),
rc_d.sleep
) AS sleep,
IF(IFNULL(rc_d.timeout,'')='',
IF(IFNULL(rc_dt.timeout,'')='',
rc_sc.value,
rc_dt.timeout
),
rc_d.timeout
) AS timeout,
debug
FROM plugin_routerconfigs_devices rc_d
LEFT JOIN plugin_routerconfigs_devicetypes rc_dt
ON rc_dt.id = rc_d.devicetype
LEFT JOIN plugin_routerconfigs_accounts rc_da
ON rc_da.id = rc_d.account
LEFT JOIN settings rc_ss
ON rc_ss.name = 'routerconfigs_sleep'
LEFT JOIN settings rc_st
ON rc_st.name = 'routerconfigs_timeout'
LEFT JOIN settings rc_sc
ON rc_sc.name = 'routerconfigs_connecttype'
$sql_where
) AS t
$sql_order
$sql_limit",
$sql_params);
?>
<script type='text/javascript' <?php print plugin_routerconfigs_csp_nonce(); ?>>
function applyFilter() {
var strURL = urlPath + 'plugins/routerconfigs/router-devices.php';
strURL += '?header=false'
strURL += '&devicetype=' + $('#devicetype').val();
strURL += '&account=' + $('#account').val();
strURL += '&rows=' + $('#rows').val();
strURL += '&filter=' + $('#filter').val();
loadPageNoHeader(strURL);
}
function clearFilter() {
var strURL = urlPath + 'plugins/routerconfigs/router-devices.php?clear=1&header=false';
loadPageNoHeader(strURL);
}
$(function() {
$('#rows, #devicetype, #account, #filter').change(function() {
applyFilter();
});
$('#refresh').click(function() {
applyFilter();
});
$('#clear').click(function() {
clearFilter();
});
$('#form_devices').submit(function(event) {
event.preventDefault();
applyFilter();
});
});
</script>
<?php
html_start_box(__('Router Device Management', 'routerconfigs'), '100%', false, 4, 'center', 'router-devices.php?action=edit');
?>
<tr class='even noprint'>
<td>
<form id='form_devices' action='router-devices.php'>
<table class='filterTable'>
<tr>
<td>
<?php print __('Device Type','routerconfigs'); ?>
</td>
<td>
<select id='devicetype'>
<option value='-1'<?php if (get_request_var('devicetype') == '-1') {?> selected<?php }?>><?php print __('Any','routerconfigs'); ?></option>
<?php
$devicetypes = db_fetch_assoc_prepared('SELECT id, name FROM plugin_routerconfigs_devicetypes ORDER BY name', []);
if (cacti_sizeof($devicetypes)) {
foreach ($devicetypes as $devicetype) {
print "<option value='" . $devicetype['id'] . "'";
if (get_request_var('devicetype') == $devicetype['id']) {
print ' selected';
} print '>' . html_escape($devicetype['name']) . "</option>\n";
}
}
?>
</select>
</td>
<td>
<?php print __('Account','routerconfigs'); ?>
</td>
<td>
<select id='account'>
<option value='-1'<?php if (get_request_var('account') == '-1') {?> selected<?php }?>><?php print __('Any','routerconfigs'); ?></option>
<?php
$accounts = db_fetch_assoc_prepared('SELECT id, name FROM plugin_routerconfigs_accounts ORDER BY name', []);
if (cacti_sizeof($accounts)) {
foreach ($accounts as $account) {
print "<option value='" . $account['id'] . "'";
if (get_request_var('account') == $account['id']) {
print ' selected';
} print '>' . html_escape($account['name']) . "</option>\n";
}
}
?>
</select>
</td>
<td>
<?php print __('Search','routerconfigs'); ?>
</td>
<td>
<input id='filter' type='text' size='25' value='<?php print html_escape_request_var('filter'); ?>'>
</td>
<td>
<select id='rows'>
<option value='-1'<?php print (get_request_var('rows') == '-1' ? ' selected>' : '>') . __('Default'); ?></option>
<?php
if (cacti_sizeof($item_rows)) {
foreach ($item_rows as $key => $value) {
print "<option value='" . $key . "'";
if (get_request_var('rows') == $key) {
print ' selected';
} print '>' . html_escape($value) . "</option>\n";
}
}
?>
</select>
</td>
<td>
<span>
<input type='button' id='refresh' value='<?php print __('Go','routerconfigs'); ?>' title='<?php print __esc('Set/Refresh Filters','routerconfigs'); ?>'>
<input type='button' id='clear' value='<?php print __('Clear','routerconfigs'); ?>' title='<?php print __esc('Clear Filters','routerconfigs'); ?>'>
</span>
</td>
</tr>
</table>
</form>
</td>
</tr>
<?php
html_end_box();
$display_text = [
'nosort_actions' => [
'display' => __('Actions', 'routerconfigs'),
],
'hostname' => [
'display' => __('Hostname', 'routerconfigs'),
'align' => 'left',
'sort' => 'ASC',
'tip' => __('Either an IP address, or hostname. If a hostname, it must be resolvable by either DNS, or from your hosts file.', 'routerconfigs')
],
'id' => [
'display' => __('ID','routerconfigs'),
'align' => 'right',
'sort' => 'ASC',
'tip' => __('The internal database ID for this Device. Useful when performing automation or debugging.', 'routerconfigs')
],
'enabled' => [