Repository navigation
Expand file tree
/
Copy pathmactrack_utilities.php
More file actions
1141 lines (951 loc) · 43.1 KB
/
Copy pathmactrack_utilities.php
File metadata and controls
1141 lines (951 loc) · 43.1 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
/*
+-------------------------------------------------------------------------+
| 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('./plugins/mactrack/lib/mactrack_functions.php');
require_once('./plugins/mactrack/lib/mactrack_activity.php');
// set default action
set_default_action();
// add more memory for import
ini_set('memory_limit', '-1');
ini_set('max_execution_time', '300');
// Actions that change data run only on a POST, which Cacti checks for its
// CSRF token; a GET gets a form that posts the action back.
if (!mactrack_utilities_may_run(get_request_var('action'), $_SERVER['REQUEST_METHOD'] ?? '')) {
mactrack_utilities_confirm(get_request_var('action'));
exit;
}
// Actions that change or reconcile the history hold the partition lock, which a
// rebuild of the port and IP tables holds for its whole run, and are refused
// while one is running or unfinished.
$history_locked = false;
if (in_array(get_request_var('action'), [
'mactrack_utilities_truncate_ports_table',
'mactrack_utilities_rebuild_scan_dates',
'mactrack_utilities_purge_aggregated_data',
'mactrack_utilities_recreate_aggregated_data',
], true)) {
if (!mactrack_partition_history_begin()) {
top_header();
mactrack_utilities();
html_start_box(__('Mactrack Database Results', 'mactrack'), '100%', '', '3', 'center', '');
print '<td>' . html_escape(mactrack_partition_history_message()) . '</td>';
html_end_box();
bottom_footer();
exit;
}
$history_locked = true;
}
switch (get_request_var('action')) {
case 'mactrack_utilities_truncate_ports_table':
mactrack_utilities_ports_clear();
break;
case 'mactrack_utilities_perform_db_maint':
top_header();
require_once('./plugins/mactrack/lib/mactrack_functions.php');
mactrack_utilities();
mactrack_utilities_db_maint();
bottom_footer();
break;
case 'mactrack_utilities_rebuild_scan_dates':
top_header();
require_once('./plugins/mactrack/lib/mactrack_functions.php');
mactrack_utilities();
mactrack_utilities_rebuild_scan_dates();
bottom_footer();
break;
case 'mactrack_partition_status':
top_header();
mactrack_utilities();
mactrack_utilities_partition_status();
bottom_footer();
break;
case 'mactrack_utilities_optimize_ports':
mactrack_utilities_optimize_ports();
break;
case 'mactrack_utilities_convert_partitions':
mactrack_utilities_convert_partitions();
break;
case 'mactrack_utilities_purge_scanning_funcs':
top_header();
require_once('./plugins/mactrack/lib/mactrack_functions.php');
mactrack_utilities();
mactrack_utilities_purge_scanning_funcs();
bottom_footer();
break;
case 'mactrack_utilities_purge_aggregated_data':
mactrack_utilities_purge_aggregated_data();
break;
case 'mactrack_utilities_recreate_aggregated_data':
mactrack_utilities_recreate_aggregated_data();
break;
case 'mactrack_refresh_oui_database':
top_header();
require_once('./plugins/mactrack/lib/mactrack_functions.php');
import_oui_database('web');
bottom_footer();
break;
case 'mactrack_proc_status':
// ================= input validation =================
get_filter_request_var('refresh');
// ====================================================
load_current_session_value('refresh', 'sess_mt_refresh', '30');
$refresh['seconds'] = get_request_var('refresh');
$refresh['page'] = 'mactrack_utilities.php?action=mactrack_proc_status&header=false';
$refresh['logout'] = 'false';
set_page_refresh($refresh);
top_header();
mactrack_display_run_status();
bottom_footer();
break;
default:
top_header();
mactrack_utilities();
bottom_footer();
break;
}
if ($history_locked) {
mactrack_partition_history_end();
}
/* -----------------------
Utilities Functions
----------------------- */
/**
* Computes and displays the MacTrack device-scanning process status:
* whether a scan has ever completed, and the calculated time until the
* next scheduled collection run and database maintenance run, based on
* the configured collection timing and base/maintenance start times.
*
* @return void
*
* @global array $config Cacti global
* configuration array
* (declared but not used
* directly here).
* @global int $refresh_interval Reserved/declared for
* parity with other
* functions in this file;
* not used directly here.
* @global array $mactrack_poller_frequencies Reserved/declared for
* parity with other
* functions in this file;
* not used directly here.
*/
function mactrack_display_run_status(): void {
global $config, $refresh_interval, $mactrack_poller_frequencies;
$collection_timing = read_config_option('mt_collection_timing', true);
if ($collection_timing != 'disabled') {
$seconds_offset = $collection_timing * 60;
// find out if it's time to collect device information
$base_start_time = read_config_option('mt_base_time', true);
$database_maint_time = read_config_option('mt_maint_time', true);
$last_run_time = read_config_option('mt_last_run_time', true);
$last_db_maint_time = read_config_option('mt_last_db_maint_time', true);
$previous_base_start_time = read_config_option('mt_prev_base_time', true);
$previous_db_maint_time = read_config_option('mt_prev_db_maint_time', true);
// see if the user desires a new start time
if (!empty($previous_base_start_time)) {
if ($base_start_time != $previous_base_start_time) {
unset($last_run_time);
}
}
// see if the user desires a new db maintenance time
/*
if (!empty($previous_db_maint_time)) {
if ($database_maint_time <> $previous_db_maint_time) {
unset($last_db_maint_time);
}
}
*/
// determine the next start time
$current_time = strtotime('now');
if (empty($last_run_time)) {
$collection_never_completed = true;
if ($current_time > strtotime($base_start_time)) {
// if timer expired within a polling interval, then poll
if (($current_time - 300) < strtotime($base_start_time)) {
$next_run_time = strtotime(date('Y-m-d') . ' ' . $base_start_time);
} else {
$next_run_time = strtotime(date('Y-m-d') . ' ' . $base_start_time) + 3600 * 24;
}
} else {
$next_run_time = strtotime(date('Y-m-d') . ' ' . $base_start_time);
}
} else {
$collection_never_completed = false;
$next_run_time = $last_run_time + $seconds_offset;
}
// determine the next db maintenance time
/*
if (empty($last_db_maint_time)) {
if (strtotime($base_start_time) < $current_time) {
$next_db_maint_time = strtotime(date('Y-m-d') . ' ' . $database_maint_time) + 3600*24;
} else {
$next_db_maint_time = strtotime(date('Y-m-d') . ' ' . $database_maint_time);
}
} else {
$next_db_maint_time = $last_db_maint_time + 24*3600;
}
*/
$db_maint_time = strtotime($database_maint_time);
if ($last_db_maint_time < $db_maint_time) {
$next_db_maint_time = $db_maint_time;
} else {
$next_db_maint_time = strtotime('Tomorrow ' . $database_maint_time);
}
$time_till_next_run = $next_run_time - $current_time;
$time_till_next_db_maint = $next_db_maint_time - $current_time;
}
html_start_box(__('Mactrack Process Status', 'mactrack'), '100%', '', '1', 'center', '');
?>
<script type='text/javascript' <?php print plugin_mactrack_csp_nonce(); ?>>
function applyFilter() {
strURL = 'mactrack_utilities.php?action=mactrack_proc_status&header=false&refresh=' + $('#refresh').val();
loadPageNoHeader(strURL);
}
$(function() {
$('#refresh').on('change', function() {
applyFilter();
});
$('#refreshButton').on('click', function() {
applyFilter();
});
});
</script>
<tr class='even'>
<form name='form_mactrack_utilities_stats' method='post'>
<td>
<table class='filterTable'>
<tr>
<td>
<?php print __('Refresh', 'mactrack'); ?>
</td>
<td>
<select id='refresh'>
<?php
if (cacti_sizeof($refresh_interval)) {
foreach ($refresh_interval as $key => $interval) {
print '<option value="' . $key . '"';
if (get_request_var('refresh') == $key) {
print ' selected';
} print '>' . $interval . '</option>';
}
}
?>
</td>
<td>
<button type='button' id='refreshButton' class='ui-button ui-corner-all ui-widget'><?php print __esc('Refresh', 'mactrack'); ?></button>
</td>
</tr>
</table>
</td>
</form>
</tr>
<?php
html_end_box(true);
mactrack_display_activity();
html_start_box('', '100%', '', '1', 'center', '');
// get information on running processes
$running_processes = db_fetch_assoc('SELECT
mac_track_processes.process_id,
mac_track_devices.device_name,
mac_track_processes.device_id,
mac_track_processes.start_date
FROM mac_track_devices
INNER JOIN mac_track_processes
ON mac_track_devices.device_id = mac_track_processes.device_id
WHERE mac_track_processes.device_id != 0');
$resolver_running = db_fetch_cell('SELECT COUNT(*) FROM mac_track_processes WHERE device_id=0');
$total_processes = cacti_sizeof($running_processes);
$run_status = db_fetch_assoc("SELECT last_rundate,
COUNT(last_rundate) AS devices
FROM mac_track_devices
WHERE disabled = ''
GROUP BY last_rundate
ORDER BY last_rundate DESC");
$total_devices = db_fetch_cell('SELECT count(*) FROM mac_track_devices');
$disabled_devices = db_fetch_cell('SELECT count(*) FROM mac_track_devices');
html_header([__('Current Process Status', 'mactrack')], 2);
form_alternate_row();
print '<td>' . __('The Mactrack Poller is:', 'mactrack') . '</td><td>' . ($total_processes > 0 ? __('Running', 'mactrack') : ($collection_timing == 'disabled' ? __('Disabled', 'mactrack') : __('Idle', 'mactrack'))) . '</td>';
if ($total_processes > 0) {
form_alternate_row();
print '<td>' . __('Running Processes:', 'mactrack') . '</td><td>' . $total_processes . '</td>';
}
form_alternate_row();
print '<td width=200>' . __('Last Time Poller Started:', 'mactrack') . '</td><td>' . read_config_option('mt_scan_date', true) . '</td>';
form_alternate_row();
print '<td width=200>' . __('Poller Frequency:', 'mactrack') . '</td><td>' . ($collection_timing == 'disabled' ? __('N/A', 'mactrack') : $mactrack_poller_frequencies[$collection_timing]) . '</td>';
form_alternate_row();
print '<td width=200>' . __('Approx. Next Runtime:', 'mactrack') . '</td><td>' . (empty($next_run_time) ? __('N/A', 'mactrack') : date('Y-m-d H:i:s', (int) $next_run_time)) . '</td>';
html_header([__('Database Maintenance Information', 'mactrack')], 2);
form_alternate_row();
print '<td width=200>' . __('Last DB Maintenance Time:', 'mactrack') . '</td><td>' . (empty($last_db_maint_time) ? __('N/A', 'mactrack') : date('Y-m-d H:i:s', $last_db_maint_time)) . '</td>';
form_alternate_row();
print '<td width=200>' . __('Next DB Maintenance Time:', 'mactrack') . '</td><td>' . (empty($next_db_maint_time) ? __('N/A', 'mactrack') : date('Y-m-d H:i:s', $next_db_maint_time)) . '</td>';
html_header([__('Run Time Details', 'mactrack')], 2);
form_alternate_row();
print '<td width=200>' . __('Last Poller Runtime:', 'mactrack') . '</td><td>' . read_config_option('stats_mactrack', true) . '</td>';
form_alternate_row();
print '<td width=200>' . __('Last Poller Maintenance Runtime:', 'mactrack') . '</td><td>' . read_config_option('stats_mactrack_maint', true) . '</td>';
form_alternate_row();
print '<td width=200>' . __('Maximum Concurrent Processes:', 'mactrack') . '</td><td> ' . read_config_option('mt_processes', true) . __('processes', 'mactrack') . '</td>';
form_alternate_row();
print '<td width=200>' . __('Maximum Per Device Scan Time:', 'mactrack') . '</td><td> ' . read_config_option('mt_script_runtime', true) . __('minutes', 'mactrack') . '</td>';
html_header([__('DNS Configuration Information', 'mactrack')], 2);
form_alternate_row();
print '<td width=200>' . __('Reverse DNS Resolution is', 'mactrack') . '</td><td>' . (read_config_option('mt_reverse_dns', true) == 'on' ? __('Enabled', 'mactrack') : __('Disabled', 'mactrack')) . '</td>';
form_alternate_row();
print '<td width=200>' . __('Primary DNS Server:', 'mactrack') . '</td><td>' . read_config_option('mt_dns_primary', true) . '</td>';
form_alternate_row();
print '<td width=200>' . __('Secondary DNS Server:', 'mactrack') . '</td><td>' . read_config_option('mt_dns_secondary', true) . '</td>';
form_alternate_row();
print '<td width=200>' . __('DNS Resolution Timeout:', 'mactrack') . '</td><td> ' . read_config_option('mt_dns_timeout', true) . __('milliseconds', 'mactrack') . '</td>';
html_end_box(true);
if ($total_processes > 0) {
html_start_box(__('Running Process Summary', 'mactrack'), '100%', '', '3', 'center', '');
?>
<td><?php print($resolver_running ? __('The DNS Resolver is Running', 'mactrack') : __('The DNS Resolver is Not Running', 'mactrack')); ?></td>
<?php
html_header([__('Status', 'mactrack'), __('Devices', 'mactrack'), __('Date Started', 'mactrack')], 3);
$other_processes = 0;
$other_date = 0;
$completed_processes = 0;
$completed_date = '';
$running_processes = 0;
$running_date = '';
$waiting_processes = 0;
$waiting_date = '';
if (cacti_sizeof($run_status) == 1) {
$waiting_processes = $total_devices - $total_processes;
$waiting_date = $run_status[0]['last_rundate'];
$completed_processes = 0;
$completed_date = '';
$running_processes = $total_processes;
$running_date = read_config_option('mt_scan_date', true);
} else {
$i = 0;
foreach ($run_status as $key => $run) {
switch ($key) {
case 0:
$completed_processes = $run['devices'];
$completed_date = $run['last_rundate'];
break;
case 1:
$waiting_processes = $run['devices'] - $total_processes;
$waiting_date = $run['last_rundate'];
$running_processes = $total_processes;
$running_date = read_config_option('mt_scan_date', true);
break;
default:
$other_processes += $run['devices'];
$other_rundate = $run['last_rundate'];
}
}
}
form_alternate_row();
?>
<td><?php print __('Completed', 'mactrack'); ?></td>
<td><?php print $completed_processes; ?></td>
<td><?php print $completed_date; ?></td>
<?php
form_alternate_row();
?>
<td><?php print __('Running', 'mactrack'); ?></td>
<td><?php print $running_processes; ?></td>
<td><?php print $running_date; ?></td>
<?php
form_alternate_row();
?>
<td><?php print __('Waiting', 'mactrack'); ?></td>
<td><?php print $waiting_processes; ?></td>
<td><?php print $waiting_date; ?></td>
<?php
form_alternate_row();
if ($other_processes > 0) {
?>
<td><?php print __('Other', 'mactrack'); ?></td>
<td><?php print $other_processes; ?></td>
<td><?php print $other_date; ?></td>
<?php
}
html_end_box(true);
}
}
/**
* Prints what MacTrack is doing now, the step timings of the last
* maintenance run, and the size of its tables. Every figure comes from a
* recorded option or an information_schema estimate; no table is counted.
*
* @return void
*/
function mactrack_display_activity(): void {
$activity = mactrack_activity_state();
html_start_box(__('Current Activity', 'mactrack'), '100%', false, 3, 'center', '');
form_alternate_row();
print '<td width=200>' . __('State:', 'mactrack') . '</td><td>' . html_escape($activity['text']) . '</td>';
if ($activity['since']) {
form_alternate_row();
print '<td>' . __('Since:', 'mactrack') . '</td><td>' . html_escape(date('Y-m-d H:i:s', $activity['since'])) . '</td>';
}
if ($activity['detail'] !== '') {
form_alternate_row();
print '<td>' . __('Detail:', 'mactrack') . '</td><td>' . html_escape($activity['detail']) . '</td>';
}
if ($activity['deferred']) {
form_alternate_row();
print '<td>' . __('Last Skipped Poller Run:', 'mactrack') . '</td><td>' . html_escape($activity['deferred']['reason'] . ' (' . date('Y-m-d H:i:s', $activity['deferred']['time']) . ')') . '</td>';
}
html_end_box(true);
$steps = mactrack_maint_steps_last();
if (cacti_sizeof($steps)) {
html_start_box(__('Last Maintenance Steps', 'mactrack'), '100%', false, 3, 'center', '');
html_header([__('Step', 'mactrack'), __('Seconds', 'mactrack')]);
foreach ($steps as $step) {
form_alternate_row();
print '<td>' . html_escape(mactrack_activity_step_label((string) $step['step'])) . '</td><td>' . html_escape($step['seconds']) . '</td>';
form_end_row();
}
html_end_box(true);
}
$tables = mactrack_table_sizes();
$disk = mactrack_database_disk_free();
html_start_box(__('Table Sizes', 'mactrack'), '100%', false, 3, 'center', '');
html_header([__('Table', 'mactrack'), __('Rows (estimate)', 'mactrack'), __('Data', 'mactrack'), __('Index', 'mactrack'), __('Free', 'mactrack')]);
foreach ($tables as $table) {
form_alternate_row();
print '<td>' . html_escape($table['table_name']) . '</td>'
. '<td>' . html_escape(number_format((float) $table['table_rows'])) . '</td>'
. '<td>' . html_escape(mactrack_activity_bytes($table['data_length'])) . '</td>'
. '<td>' . html_escape(mactrack_activity_bytes($table['index_length'])) . '</td>'
. '<td>' . html_escape(mactrack_activity_bytes($table['data_free'])) . '</td>';
form_end_row();
}
form_alternate_row();
if ($disk['reason'] === 'remote') {
$free = __('Unknown: the database runs on another host', 'mactrack');
} elseif ($disk['bytes'] === null) {
$free = __('Unknown: the database data directory cannot be found from this host', 'mactrack');
} else {
$free = mactrack_activity_bytes($disk['bytes']);
}
print '<td colspan="5">' . __('Database Disk Free:', 'mactrack') . ' ' . html_escape($free) . '</td>';
form_end_row();
html_end_box(true);
}
/**
* Truncates all MacTrack port/MAC/IP result tables (ports, scan dates,
* IPs, IP ranges, VLANs, aggregated ports, dot1x) and resets the
* corresponding summary counters on every device and site record.
* Runs only on a POST (see mactrack_utilities_may_run()). Called from
* this script's main request-dispatch switch.
*
* @return void
*
* @global array $config Cacti global configuration array (declared but
* not used directly here).
*/
function mactrack_utilities_ports_clear(): void {
global $config;
$rows = db_fetch_cell('SELECT COUNT(*) FROM mac_track_ports');
db_execute('TRUNCATE TABLE mac_track_ports');
db_execute('TRUNCATE TABLE mac_track_scan_dates');
db_execute('TRUNCATE TABLE mac_track_ips');
db_execute('TRUNCATE TABLE mac_track_ip_ranges');
db_execute('TRUNCATE TABLE mac_track_vlans');
db_execute('TRUNCATE TABLE mac_track_aggregated_ports');
db_execute('TRUNCATE TABLE mac_track_dot1x');
db_execute('UPDATE mac_track_sites SET total_macs=0, total_ips=0, total_user_ports=0, total_oper_ports=0, total_trunk_ports=0');
db_execute('UPDATE mac_track_devices SET ips_total=0, ports_total=0, ports_active=0, ports_trunk=0, macs_active=0, vlans_total=0, last_runduration=0.0000');
$device_rows = db_fetch_assoc('SELECT device_id FROM mac_track_devices');
if (cacti_sizeof($device_rows)) {
foreach ($device_rows as $device_row) {
db_execute_prepared('UPDATE mac_track_devices SET ips_total=0 WHERE device_id = ?', [$device_row['device_id']]);
db_execute_prepared('UPDATE mac_track_devices SET ports_total=0 WHERE device_id = ?', [$device_row['device_id']]);
db_execute_prepared('UPDATE mac_track_devices SET ports_active=0 WHERE device_id = ?', [$device_row['device_id']]);
db_execute_prepared('UPDATE mac_track_devices SET ports_trunk=0 WHERE device_id = ?', [$device_row['device_id']]);
db_execute_prepared('UPDATE mac_track_devices SET macs_active=0 WHERE device_id = ?', [$device_row['device_id']]);
db_execute_prepared('UPDATE mac_track_devices SET vlans_total=0 WHERE device_id = ?', [$device_row['device_id']]);
db_execute_prepared('UPDATE mac_track_devices SET last_runduration=0.00000 WHERE device_id = ?', [$device_row['device_id']]);
}
}
$site_rows = db_fetch_assoc('SELECT site_id FROM mac_track_sites');
if (cacti_sizeof($site_rows)) {
foreach ($site_rows as $site_row) {
db_execute_prepared('UPDATE mac_track_sites SET total_devices=0 WHERE site_id = ?', [$site_row['site_id']]);
db_execute_prepared('UPDATE mac_track_sites SET total_macs=0 WHERE site_id = ?', [$site_row['site_id']]);
db_execute_prepared('UPDATE mac_track_sites SET total_ips=0 WHERE site_id = ?', [$site_row['site_id']]);
db_execute_prepared('UPDATE mac_track_sites SET total_user_ports=0 WHERE site_id = ?', [$site_row['site_id']]);
db_execute_prepared('UPDATE mac_track_sites SET total_oper_ports=0 WHERE site_id = ?', [$site_row['site_id']]);
db_execute_prepared('UPDATE mac_track_sites SET total_trunk_ports=0 WHERE site_id = ?', [$site_row['site_id']]);
}
}
top_header();
mactrack_utilities();
html_start_box(__('Mactrack Database Results', 'mactrack'), '100%', '', '3', 'center', '');
print '<td>' . __('The following number of records have been removed from the database: %s', $rows, 'mactrack') . '</td>';
html_end_box();
}
/**
* Truncates the mac_track_aggregated_ports table. Runs only on a POST
* (see mactrack_utilities_may_run()). Called from this script's main
* request-dispatch switch.
*
* @return void
*
* @global array $config Cacti global configuration array (declared but
* not used directly here).
*/
function mactrack_utilities_purge_aggregated_data(): void {
global $config;
$rows = db_fetch_cell('SELECT COUNT(*) FROM mac_track_aggregated_ports');
db_execute('TRUNCATE TABLE mac_track_aggregated_ports');
top_header();
mactrack_utilities();
html_start_box(__('Mactrack Database Results', 'mactrack'), '100%', '', '3', 'center', '');
print '<td>' . __('The following number of records have been removed from the aggergated table: %s', $rows, 'mactrack') . '</td>';
html_end_box();
}
/**
* Truncates and rebuilds the mac_track_aggregated_ports table by
* re-aggregating (grouping and counting) the raw mac_track_ports data.
* Runs only on a POST (see mactrack_utilities_may_run()). Called from
* this script's main request-dispatch switch.
*
* @return void
*
* @global array $config Cacti global configuration array (declared but
* not used directly here).
*/
function mactrack_utilities_recreate_aggregated_data(): void {
global $config;
$old_rows = db_fetch_cell('SELECT COUNT(*) FROM mac_track_aggregated_ports');
db_execute('TRUNCATE TABLE mac_track_aggregated_ports');
db_execute('INSERT INTO mac_track_aggregated_ports
(site_id, device_id, hostname, device_name,
vlan_id, vlan_name, mac_address, vendor_mac, ip_address, dns_hostname,
port_number, port_name, date_last, first_scan_date, count_rec, authorized)
SELECT site_id, device_id, hostname, device_name,
vlan_id, vlan_name, mac_address, vendor_mac, ip_address, dns_hostname,
port_number, port_name, max(scan_date), min(scan_date), count(*), authorized
FROM mac_track_ports
GROUP BY site_id,device_id, mac_address, port_number, ip_address, vlan_id, authorized');
$new_rows = db_fetch_cell('SELECT COUNT(*) FROM mac_track_aggregated_ports');
top_header();
mactrack_utilities();
html_start_box('Mactrack Database Results', '100%', '', '3', 'center', '');
print '<td>' . __('The following number of records have been removed from the aggergated table: %s. And %s records will be added.', $old_rows, $new_rows, 'mactrack') . '</td>';
html_end_box();
}
/**
* Runs the standard MacTrack database maintenance routine
* (perform_mactrack_db_maint()) and displays the number of rows
* removed from mac_track_ports as a result. Called from this script's
* main request-dispatch switch.
*
* @return void
*/
function mactrack_utilities_db_maint(): void {
$begin_rows = db_fetch_cell('SELECT COUNT(*) FROM mac_track_ports');
perform_mactrack_db_maint();
$end_rows = db_fetch_cell('SELECT COUNT(*) FROM mac_track_ports');
html_start_box('Mactrack Database Results', '100%', '', '3', 'center', '');
print '<td>' . __('The following number of records have been removed from the database: %s', $begin_rows - $end_rows, 'mactrack') . '</td>';
html_end_box();
}
/**
* Rebuilds the scan date list from the stored port results
* (mactrack_scan_dates_rebuild()) and displays how many dates it holds.
* Called from this script's main request-dispatch switch.
*
* @return void
*/
function mactrack_utilities_rebuild_scan_dates(): void {
html_start_box(__('Mactrack Scan Date Rebuild Results', 'mactrack'), '100%', '', '3', 'center', '');
// The scan lock keeps a scan from recording a date the rebuild has not
// read yet, which the rebuild would then delete as stale.
if (!mactrack_partition_scan_begin()) {
print '<td>' . html_escape(mactrack_utilities_busy_message()) . '</td>';
} else {
try {
$dates = mactrack_scan_dates_rebuild();
} finally {
mactrack_partition_scan_end();
}
if ($dates === false) {
print '<td>' . __('Scan date rebuild failed. Check the Cacti log and retry.', 'mactrack') . '</td>';
} else {
print '<td>' . __('Scan dates rebuilt: %d', $dates, 'mactrack') . '</td>';
}
}
html_end_box();
}
/**
* The message shown when a Utilities action cannot take the scan lock.
*
* @return string
*/
function mactrack_utilities_busy_message(): string {
return __('A scan or a port table conversion is running. Try again when it has finished.', 'mactrack');
}
/**
* Shows how mac_track_ports is partitioned: the layout, the partition
* count against the server's limit, the effective partition size and why,
* a pending exchange, and the outcome of the last maintenance run.
*
* @return void
*/
function mactrack_utilities_partition_status(): void {
$r = mactrack_partition_report();
$none = __('None', 'mactrack');
$sizes = [
'scan' => __('One per Scan', 'mactrack'),
'hour' => __('Hourly', 'mactrack'),
'day' => __('Daily', 'mactrack'),
'week' => __('Weekly', 'mactrack'),
];
$layouts = [
'none' => __('Not partitioned', 'mactrack'),
'legacy' => __('Daily partitions from an earlier MacTrack release. Conversion is needed.', 'mactrack'),
'range' => __('Partitioned by scan date', 'mactrack'),
'invalid' => __('Unrecognized partitions. MacTrack makes no partition changes.', 'mactrack'),
];
$i = 0;
$row = function (string $label, string $value) use (&$i): void {
form_alternate_row('line' . $i++);
print '<td>' . html_escape($label) . '</td><td>' . html_escape($value) . '</td>';
form_end_row();
};
html_start_box(__('Port Table Partitions', 'mactrack'), '100%', '', '3', 'center', '');
$row(__('Layout', 'mactrack'), trim($layouts[$r['layout']] . ' ' . $r['reason']));
if ($r['layout'] !== 'none') {
$row(__('Partitions', 'mactrack'), __('%d of at most %d', $r['partitions'], $r['cap'], 'mactrack'));
$row(__('Oldest Partition', 'mactrack'), $r['oldest'] ?? $none);
$row(__('Newest Partition', 'mactrack'), $r['newest'] ?? $none);
if ($r['covered_until'] !== null) {
$row(__('Partitions Cover Scans Before', 'mactrack'), date('Y-m-d H:i:s', $r['covered_until']));
}
}
$size = $r['layout'] === 'none' ? __('Disabled', 'mactrack') : $sizes[$r['granularity']];
if ($r['fell_back']) {
$size = __('%s, coarser than the setting because %d partitions would exceed the limit', $size, $r['projected'], 'mactrack');
}
$row(__('Port and IP Address Partition Size', 'mactrack'), $size);
$row(__('Pending Exchange', 'mactrack'), $r['pending'] !== '' ? $r['pending'] : $none);
$row(__('Load Path', 'mactrack'), __('PHP batches', 'mactrack'));
$row(__('Last Scan Note', 'mactrack'), $r['last_scan_reason'] !== '' ? $r['last_scan_reason'] : $none);
if ($r['converting'] !== null) {
$row(__('Rebuild', 'mactrack'), __('Running since %s', date('Y-m-d H:i:s', $r['converting']), 'mactrack'));
} elseif ($r['conversion'] !== null) {
$c = $r['conversion'];
$row(__('Last Rebuild', 'mactrack'), $c['ok']
? trim(__('%s: %d rows into %d partitions', date('Y-m-d H:i:s', (int) $c['time']), $c['rows'], $c['partitions'], 'mactrack') . ' ' . $c['reason'])
: __('%s: failed. %s', date('Y-m-d H:i:s', (int) $c['time']), $c['reason'], 'mactrack'));
}
$m = $r['maintenance'];
if ($m === null) {
$row(__('Last Maintenance', 'mactrack'), $none);
} else {
$row(__('Last Maintenance', 'mactrack'), trim(__('%s: %d partitions dropped, %d created', date('Y-m-d H:i:s', (int) $m['time']), count($m['dropped']), count($m['created']), 'mactrack') . ' ' . $m['reason']));
}
$ips = mactrack_partition_state('mac_track_ips')['layout'];
$row(__('IP Table Layout', 'mactrack'), trim($layouts[$ips['state']] . ' ' . $ips['reason']));
if ($ips['state'] === 'range') {
$row(__('IP Table Partitions', 'mactrack'), (string) count($ips['partitions']));
}
$dot1x = mactrack_partition_state('mac_track_dot1x')['layout'];
$row(__('802.1x Table Layout', 'mactrack'), trim($layouts[$dot1x['state']] . ' ' . $dot1x['reason']));
if ($dot1x['state'] === 'range') {
$row(__('802.1x Table Partitions', 'mactrack'), (string) count($dot1x['partitions']));
}
html_end_box();
}
/**
* Rebuilds and analyzes the hot port partition, or optimizes the whole
* table when it is unpartitioned. Runs only on a POST
* (see mactrack_utilities_may_run()).
*
* It holds the scan lock throughout, so it never runs during a scan or a
* conversion; a queued OPTIMIZE would also hold up a conversion's final
* rename until that gave up.
*
* @return void
*/
function mactrack_utilities_optimize_ports(): void {
$result = null;
if (mactrack_partition_scan_begin()) {
try {
$result = mactrack_partition_optimize();
} finally {
mactrack_partition_scan_end();
}
}
top_header();
mactrack_utilities();
html_start_box(__('Mactrack Database Results', 'mactrack'), '100%', '', '3', 'center', '');
if ($result === null) {
form_alternate_row();
print '<td>' . html_escape(mactrack_utilities_busy_message()) . '</td>';
form_end_row();
}
foreach ((array) $result as $line) {
form_alternate_row();
print '<td>' . html_escape(($line['Msg_type'] ?? '') . ': ' . ($line['Msg_text'] ?? '')) . '</td>';
form_end_row();
}
html_end_box();
bottom_footer();
}
/**
* Starts the partitioning rebuild of the port and IP tables in the
* background (cli/upgrade_partitioning.php), because it can take hours.
*
* Runs only on a POST (see mactrack_utilities_may_run()). The rebuild
* itself refuses to start when a scan or another rebuild holds the
* scan lock.
*
* @return void
*
* @global array $config Cacti global configuration array; used to build
* the script's path.
*/
function mactrack_utilities_convert_partitions(): void {
global $config;
$scheme = get_request_var('partition_scheme');
$busy = mactrack_partition_rebuild_state() === 'running';
if (!in_array($scheme, ['daily', 'weekly', 'disabled'], true)) {
$message = __('Select daily, weekly or disabled partitioning before starting the rebuild.', 'mactrack');
} elseif ($busy) {
$message = __('A rebuild is already running. The partition status page shows when it has finished.', 'mactrack');
} else {
// Only allowlisted schemes reach the CLI, and every argument is quoted.
$args = '-q ' . cacti_escapeshellarg($config['base_path'] . '/plugins/mactrack/cli/upgrade_partitioning.php')
. ' ' . cacti_escapeshellarg('--partition=' . $scheme);
exec_background(read_config_option('path_php_binary'), $args);
$message = __('The rebuild was requested in the background. Check Partition Status for its result; it will refuse to start if a scan or another rebuild is running.', 'mactrack');
}
top_header();
mactrack_utilities();
html_start_box(__('Mactrack Database Results', 'mactrack'), '100%', '', '3', 'center', '');
form_alternate_row();
print '<td>' . html_escape($message) . '</td>';
form_end_row();
html_end_box();
bottom_footer();
}
/**
* Purges and rebuilds the cached list of registered vendor scanning
* functions (mactrack_rebuild_scanning_funcs()). Called from this
* script's main request-dispatch switch.
*
* @return void
*
* @global array $config Cacti global configuration array (declared but
* not used directly here).
*/
function mactrack_utilities_purge_scanning_funcs(): void {
global $config;
mactrack_rebuild_scanning_funcs();
html_start_box('Mactrack Scanning Function Refresh Results', '100%', '', '3', 'center', '');
print '<td>' . __('Mactrack scanning functions have been purged. They will be recreated once you either edit a device or device type.', 'mactrack') . '</td>';
html_end_box();
}
/**
* Returns a form that posts a Utilities action. Cacti's output filter adds
* the CSRF token to every form with method="post".
*
* @param string $action Action to post.
* @param string $label Button label.
* @param bool $cancel Whether to put a Cancel link beside the button.
*
* @return string
*/
function mactrack_utilities_post_form(string $action, string $label, bool $cancel = false): string {
// The Cancel link sits inside the form so it and the submit button share a line.
return '<form method="post" action="mactrack_utilities.php">'
. '<input type="hidden" name="action" value="' . html_escape($action) . '">'
. ($action === 'mactrack_utilities_convert_partitions' ? mactrack_utilities_conversion_fields() : '')
. ($cancel ? '<a class="ui-button ui-corner-all ui-widget" href="mactrack_utilities.php">' . html_escape(__('Cancel', 'mactrack')) . '</a> ' : '')
. '<input type="submit" class="ui-button ui-corner-all ui-widget" value="' . html_escape($label) . '">'
. '</form>';
}
/**
* Returns the Utilities page entry for an action that changes data: a link
* to its confirmation form when Confirm Utilities Prompt is on, otherwise a
* button that posts the action at once.
*
* @param string $action Action from mactrack_utilities_post_actions().
* @param string $label Link or button text.
*
* @return string
*/
function mactrack_utilities_action_link(string $action, string $label): string {
if ($action === 'mactrack_utilities_convert_partitions' || read_config_option('mt_maint_confirm') == 'on') {
return "<a class='hyperLink' href='mactrack_utilities.php?action=" . html_escape($action) . "'>" . html_escape($label) . '</a>';
}
return mactrack_utilities_post_form($action, $label);
}
/**
* Shows the confirmation form for an action that changes data, reached by
* a GET. Continue posts the action back; nothing runs until then.
*
* @param string $action Action from mactrack_utilities_post_actions().
*
* @return void
*/
function mactrack_utilities_confirm(string $action): void {
$message = mactrack_utilities_post_actions()[$action];
top_header();
html_start_box(mactrack_utilities_post_titles()[$action], '60%', '', '3', 'center', '');
print '<tr><td class="textArea">' . html_escape($message) . '</td></tr>';
$class = $action === 'mactrack_utilities_convert_partitions' ? 'textArea' : 'right';
print '<tr><td class="' . $class . '">' . mactrack_utilities_post_form($action, __('Continue', 'mactrack'), true) . '</td></tr>';
html_end_box();
bottom_footer();
}
/**
* Renders the main MacTrack System Utilities page: displays the