-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathfunctions.php
More file actions
5694 lines (4778 loc) · 182 KB
/
Copy pathfunctions.php
File metadata and controls
5694 lines (4778 loc) · 182 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/ |
+-------------------------------------------------------------------------+
*/
$syslog_query_builder = __DIR__ . '/lib/QueryBuilder.php';
if (file_exists($syslog_query_builder)) {
require_once $syslog_query_builder;
}
/**
* Allowlisted fields and operators shared by validation and the builder.
*
* @return array<string, string> Map of field names to display labels.
*/
function syslog_search_fields(): array {
return ['message' => 'Message', 'host' => 'Host', 'program' => 'Program',
'facility' => 'Facility', 'priority' => 'Priority', 'logtime' => 'Date',
'seq' => 'Sequence', 'host_id' => 'Host ID', 'program_id' => 'Program ID',
'facility_id' => 'Facility ID', 'priority_id' => 'Priority ID'];
}
/**
* Database-backed values used by query-builder dropdowns.
*
* @return array<string, array<int, array<int, string>>> Map of field names to choice arrays.
*/
function syslog_search_choices(): array {
global $syslogdb_default;
$choices = [];
foreach (['facility' => 'syslog_facilities', 'priority' => 'syslog_priorities', 'program' => 'syslog_programs'] as $field => $table) {
$choices[$field . '_id'] = [];
if ($field !== 'program') { $choices[$field] = []; }
foreach (syslog_db_fetch_assoc("SELECT {$field}_id AS id, $field AS name FROM `$syslogdb_default`.`$table` ORDER BY $field") as $record) {
$choices[$field . '_id'][] = [(string) $record['id'], $record['name'] . ' (' . $record['id'] . ')'];
if ($field !== 'program') { $choices[$field][] = [$record['name'], $record['name']]; }
}
}
return $choices;
}
/**
* Bounded suggestions; message/sequence suggestions sample recent records.
*
* @param string $field The field to get suggestions for.
* @param string $term The search term.
* @param string $tab The current tab.
* @param string $removal The removal flag.
*
* @return array<int, array{value: string, label: string}> Array of suggestion objects.
*/
function syslog_search_suggestions(string $field, string $term, string $tab, string $removal): array {
global $syslogdb_default;
if (!isset(syslog_search_fields()[$field]) || $field === 'logtime' || strlen($term) > 1024) {
return [];
}
$pattern = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $term) . '%';
$base = substr($field, -3) === '_id' ? substr($field, 0, -3) : $field;
$tables = ['host' => 'syslog_hosts', 'program' => 'syslog_programs', 'facility' => 'syslog_facilities', 'priority' => 'syslog_priorities'];
if (isset($tables[$base]) && !($base === 'host' && $tab === 'alerts')) {
$table = $tables[$base];
$records = syslog_db_fetch_assoc_prepared("SELECT $field AS value, $base AS label
FROM `$syslogdb_default`.`$table`
WHERE $base LIKE ? ESCAPE '!' OR CAST($field AS CHAR) LIKE ? ESCAPE '!'
ORDER BY $base LIMIT 30", [$pattern, $pattern]);
} else {
if (!in_array($field, ['message', 'seq', 'host'], true)) { return []; }
$column = $field === 'message' && $tab === 'alerts' ? 'logmsg' : $field;
$tables = $tab === 'alerts' ? ['syslog_logs'] : ($removal === '1' ? ['syslog', 'syslog_removed'] : [$removal === '-1' ? 'syslog' : 'syslog_removed']);
$queries = [];
foreach ($tables as $table) {
$queries[] = "SELECT $column AS value FROM (SELECT $column FROM `$syslogdb_default`.`$table` ORDER BY seq DESC LIMIT 1000) AS recent_$table";
}
$records = syslog_db_fetch_assoc_prepared('SELECT DISTINCT value, value AS label FROM (' . implode(' UNION ALL ', $queries) . ") AS suggestions WHERE value LIKE ? ESCAPE '!' ORDER BY value LIMIT 30", [$pattern]);
}
return array_map(function ($record) {
return ['value' => (string) $record['value'], 'label' => (string) $record['label']];
}, $records);
}
/**
* Get available search operators for a field.
*
* @param string $field The field name.
*
* @return array<int, string> Array of operator strings.
*/
function syslog_search_operators(string $field): array {
if ($field === 'logtime') { return ['=', '!=', '>', '>=', '<', '<=', 'last']; }
return $field === 'seq' || substr($field, -3) === '_id' || $field === 'logtime'
? ['=', '!=', '>', '>=', '<', '<='] : ['contains', '=', '!=', 'like'];
}
/**
* Parse literal message searches. Uppercase operators bind NOT, AND, then OR.
*
* @param string $input The search input string.
*
* @return array<int|string, mixed>|null The parsed search tree, or null if empty.
*
* @throws InvalidArgumentException When the search is too long, too complex, or malformed.
*/
function syslog_parse_logical_search(string $input): ?array {
if (strlen($input) > 8192) {
throw new InvalidArgumentException('Search is too long (maximum 8192 bytes).');
}
$tokens = [];
$length = strlen($input);
for ($i = 0; $i < $length;) {
if (ctype_space($input[$i])) {
$i++;
continue;
}
if (preg_match('/\G([a-z_]+)\s+(contains|like|last|regex|!=|>=|<=|=|>|<)\s+(?=")/', $input, $match, 0, $i)) {
if (!isset(syslog_search_fields()[$match[1]]) || !in_array($match[2], syslog_search_operators($match[1]), true)) {
throw new InvalidArgumentException('Invalid field or operator.');
}
$tokens[] = ['field', $match[1], $match[2]];
$i += strlen($match[0]);
continue;
}
if ($input[$i] == '(' || $input[$i] == ')') {
$tokens[] = [$input[$i++], ''];
} elseif ($input[$i] == '"') {
$value = '';
$closed = false;
for ($i++; $i < $length; $i++) {
if ($input[$i] == '"') {
$i++;
$closed = true;
break;
}
if ($input[$i] == '\\' && $i + 1 < $length && ($input[$i + 1] == '"' || $input[$i + 1] == '\\')) {
$i++;
}
$value .= $input[$i];
}
if (!$closed || $value === '') {
throw new InvalidArgumentException('Use a nonempty phrase with a closing double quote.');
}
$tokens[] = ['term', $value];
} elseif (preg_match('/\G(AND|OR|NOT)(?=\s|[()"]|$)/', $input, $match, 0, $i)) {
$tokens[] = [$match[1], ''];
$i += strlen($match[1]);
} else {
$start = $i++;
while ($i < $length && strpos('()"', $input[$i]) === false) {
if (ctype_space($input[$i - 1]) && preg_match('/\G(AND|OR|NOT)(?=\s|[()"]|$)/', $input, $match, 0, $i)) {
break;
}
$i++;
}
$tokens[] = ['term', trim(substr($input, $start, $i - $start))];
}
}
if (!$tokens) {
return null;
}
if (count($tokens) > 256) {
throw new InvalidArgumentException('Search is too complex (maximum 256 tokens).');
}
$position = 0;
$parse = function ($minimum = 0, $depth = 0) use (&$parse, &$position, $tokens) {
if ($depth > 32) {
throw new InvalidArgumentException('Search nesting is too deep (maximum 32 levels).');
}
/** @var array<int, string> $token A token: ['field', name, operator], ['term', value], ['NOT'|'AND'|'OR'|'('|')', '']. */
$token = $tokens[$position++] ?? ['', ''];
if ($token[0] == 'NOT') {
$node = ['NOT', $parse(3, $depth + 1)];
} elseif ($token[0] == '(') {
$node = $parse(0, $depth + 1);
if (($tokens[$position++][0] ?? '') != ')') {
throw new InvalidArgumentException('Expected a closing parenthesis.');
}
} elseif ($token[0] == 'field') {
$value = $tokens[$position++] ?? [];
if (($value[0] ?? '') !== 'term') {
throw new InvalidArgumentException('Expected a quoted field value.');
}
if (($token[1] === 'seq' || substr($token[1], -3) === '_id') && !ctype_digit($value[1])) {
throw new InvalidArgumentException('IDs must be nonnegative integers.');
}
if ($token[2] === 'last' && !in_array($value[1], ['3600', '21600', '86400', '604800', '1209600', '2592000', '3months', '6months'], true)) {
throw new InvalidArgumentException('Invalid date preset.');
}
if ($token[1] === 'logtime' && $token[2] !== 'last' && (!preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $value[1]) || strtotime($value[1]) === false)) {
throw new InvalidArgumentException('Use a date in YYYY-MM-DD HH:MM:SS format.');
}
$node = ['predicate', $token[1], $token[2], $value[1]];
} elseif ($token[0] == 'term') {
$node = $token;
} else {
throw new InvalidArgumentException('Expected a search term, NOT, or an opening parenthesis.');
}
while (isset($tokens[$position])) {
$operator = $tokens[$position][0];
$precedence = ['OR' => 1, 'AND' => 2][$operator] ?? 0;
if (!$precedence || $precedence < $minimum) {
break;
}
$position++;
$node = [$operator, $node, $parse($precedence + 1, $depth + 1)];
}
return $node;
};
$tree = $parse();
if ($position != count($tokens)) {
throw new InvalidArgumentException('Expected AND or OR between terms, or found an extra closing parenthesis.');
}
return $tree;
}
/**
* LOCATE treats wildcard and regex characters literally and uses column collation.
*
* @param array<int|string, mixed>|null $tree The parsed search tree.
* @param string $column The column name ('message' or 'logmsg').
*
* @return string The SQL WHERE clause fragment.
*
* @throws InvalidArgumentException When the tree or column is invalid.
*/
function syslog_logical_search_sql(?array $tree, string $column): string {
if (!in_array($column, ['message', 'logmsg'], true)) {
throw new InvalidArgumentException('Invalid message column.');
}
if ($tree === null) {
return '';
}
if ($tree[0] === 'predicate') {
global $syslogdb_default;
[, $field, $operator, $value] = $tree;
if (!isset(syslog_search_fields()[$field]) || !in_array($operator, syslog_search_operators($field), true)) {
throw new InvalidArgumentException('Invalid field or operator.');
}
if ($field === 'host_id' && $column === 'logmsg') {
throw new InvalidArgumentException('Host ID is only available for system logs.');
}
if ($operator === 'last') {
if (!in_array($value, ['3600', '21600', '86400', '604800', '1209600', '2592000', '3months', '6months'], true)) {
throw new InvalidArgumentException('Invalid date preset.');
}
$interval = ['3months' => '3 MONTH', '6months' => '6 MONTH'][$value] ?? ((int) $value . ' SECOND');
return '(syslog.logtime BETWEEN DATE_SUB(NOW(), INTERVAL ' . $interval . ') AND NOW())';
}
$target = $field === 'message' ? $column : 'syslog.' . $field;
if (in_array($field, ['host', 'program', 'facility', 'priority'], true)) {
if ($field === 'host' && $column === 'logmsg') {
$target = 'syslog.host';
} else {
$table = ['host' => 'syslog_hosts', 'program' => 'syslog_programs', 'facility' => 'syslog_facilities', 'priority' => 'syslog_priorities'][$field];
$target = "(SELECT search_lookup.$field FROM `$syslogdb_default`.`$table` AS search_lookup WHERE search_lookup.{$field}_id = syslog.{$field}_id)";
}
}
if ($operator === 'contains') {
return '(LOCATE(' . db_qstr($value) . ', ' . $target . ') > 0)';
}
$operator = ['like' => 'LIKE'][$operator] ?? $operator;
return '(' . $target . ' ' . $operator . ' ' . db_qstr($value) . ')';
}
if ($tree[0] == 'term') {
return '(LOCATE(' . db_qstr($tree[1]) . ', ' . $column . ') > 0)';
}
if ($tree[0] == 'NOT') {
return '(NOT ' . syslog_logical_search_sql($tree[1], $column) . ')';
}
return '(' . syslog_logical_search_sql($tree[1], $column) . ' ' . $tree[0] . ' ' . syslog_logical_search_sql($tree[2], $column) . ')';
}
/**
* Extract positive terms from a parsed search tree.
*
* @param array<int|string, mixed>|null $tree The parsed search tree.
* @param bool $negative Whether to extract negative terms.
*
* @return array<int, string> Array of search terms.
*/
function syslog_logical_positive_terms(?array $tree, bool $negative = false): array {
if ($tree === null) {
return [];
}
if ($tree[0] === 'predicate') {
return !$negative && $tree[1] === 'message' && in_array($tree[2], ['contains', '='], true) ? [$tree[3]] : [];
}
if ($tree[0] == 'term') {
return $negative ? [] : [$tree[1]];
}
if ($tree[0] == 'NOT') {
return syslog_logical_positive_terms($tree[1], !$negative);
}
return array_merge(syslog_logical_positive_terms($tree[1], $negative), syslog_logical_positive_terms($tree[2], $negative));
}
/**
* Remove the date clause the page entry logic appends to a search, so saved
* searches stay dynamic (dates are re-derived each time one is applied).
*
* @param string $search The search string.
* @param mixed $date1 The start date.
* @param mixed $date2 The end date.
*
* @return string The search string with auto dates removed.
*/
function syslog_strip_auto_dates(string $search, mixed $date1, mixed $date2): string {
$d1 = str_replace(['\\', '"'], ['\\\\', '\\"'], (string) $date1);
$d2 = str_replace(['\\', '"'], ['\\\\', '\\"'], (string) $date2);
$suffix = 'logtime >= "' . $d1 . '" AND logtime <= "' . $d2 . '"';
if (substr($search, -strlen($suffix)) === $suffix) {
$search = substr($search, 0, -strlen($suffix));
if (substr($search, -5) === ' AND ') {
$search = substr($search, 0, -5);
}
}
return $search;
}
/**
* Permission to make saved searches global and to manage other users' global searches.
*
* @return bool True if the user has admin permission.
*/
function syslog_saved_search_admin(): bool {
return api_plugin_user_realm_auth('syslog_saved_searches.php');
}
/**
* Permission to share saved searches with all syslog users.
*
* @return bool True if the user has share permission.
*/
function syslog_saved_search_share(): bool {
return syslog_saved_search_admin() || api_plugin_user_realm_auth('syslog_saved_searches_share.php');
}
/**
* Permission to manage all dashboards, including other users' shared dashboards.
*
* @return bool True if the user has dashboard admin permission.
*/
function syslog_dashboard_admin(): bool {
return api_plugin_user_realm_auth('syslog_alerts.php');
}
/**
* Permission to share dashboards with all syslog users.
*
* @return bool True if the user has dashboard share permission.
*/
function syslog_dashboard_share(): bool {
return syslog_dashboard_admin() || api_plugin_user_realm_auth('syslog_dashboards_share.php');
}
/**
* The whitelisted share table and item column per shareable item kind.
*
* @param string $item The item kind ('dashboard' or 'saved_search').
*
* @return array<int, string>|null [table, column], or null for an unknown kind.
*/
function syslog_share_table(string $item): ?array {
$tables = [
'dashboard' => ['syslog_dashboards_perm', 'dashboard_id'],
'saved_search' => ['syslog_saved_searches_perm', 'search_id']
];
return isset($tables[$item]) ? $tables[$item] : null;
}
/**
* Cacti group ids the session user is a member of, or the given user.
*
* @param int $user_id The user ID, or 0 for the current session user.
*
* @return array<int, int> Array of group IDs.
*/
function syslog_user_group_ids(int $user_id = 0): array {
if ($user_id === 0) {
$user_id = isset($_SESSION['sess_user_id']) ? (int) $_SESSION['sess_user_id'] : 0;
}
if ($user_id <= 0) {
return [];
}
$groups = db_fetch_assoc_prepared('SELECT group_id
FROM user_auth_group_members
WHERE user_id = ?',
[$user_id]);
if (!is_array($groups) || !cacti_sizeof($groups)) {
return [];
}
$ids = [];
foreach ($groups as $group) {
$ids[] = (int) $group['group_id'];
}
return $ids;
}
/**
* Ids of one shareable item kind granted to the current user or one of
* their groups, plus anything granted to everyone through an 'all' row.
* Returns [] outside a session or when nothing is granted.
*
* @param string $item The item kind.
*
* @return array<int, int> Array of item IDs granted to the user.
*/
function syslog_shared_item_ids(string $item): array {
global $syslogdb_default;
static $cache = [];
$user_id = isset($_SESSION['sess_user_id']) ? (int) $_SESSION['sess_user_id'] : 0;
if ($user_id <= 0) {
return [];
}
if (isset($cache[$item])) {
return $cache[$item];
}
$share_table = syslog_share_table($item);
if ($share_table === null) {
return [];
}
list($table, $column) = $share_table;
$group_ids = syslog_user_group_ids($user_id);
$sql = "SELECT $column AS id
FROM `$syslogdb_default`.`$table`
WHERE (type = 'user' AND item_id = ?) OR type = 'all'";
$params = [$user_id];
if (cacti_sizeof($group_ids)) {
$sql .= " OR (type = 'group' AND item_id IN (" . implode(',', array_fill(0, cacti_sizeof($group_ids), '?')) . '))';
foreach ($group_ids as $group_id) {
$params[] = $group_id;
}
}
$rows = syslog_db_fetch_assoc_prepared($sql, $params);
$ids = [];
if (cacti_sizeof($rows)) {
foreach ($rows as $row) {
if (isset($row['id']) && (int) $row['id'] > 0) {
$ids[] = (int) $row['id'];
}
}
}
$cache[$item] = $ids;
return $ids;
}
/**
* Current grants on one item, shaped for the drop_multi form fields.
*
* @param string $item The item kind.
* @param int $item_id The item ID.
*
* @return array{users: array<int, array{id: string|int}>, groups: array<int, array{id: string|int}>}
*/
function syslog_fetch_item_shares(string $item, int $item_id): array {
global $syslogdb_default;
$shares = ['users' => [], 'groups' => []];
$share_table = syslog_share_table($item);
if ($share_table === null || (int) $item_id <= 0) {
return $shares;
}
list($table, $column) = $share_table;
$rows = syslog_db_fetch_assoc_prepared("SELECT type, item_id
FROM `$syslogdb_default`.`$table`
WHERE $column = ?",
[(int) $item_id]);
if (cacti_sizeof($rows)) {
foreach ($rows as $row) {
if ($row['type'] === 'all') {
// The 'all' grant shows in both selects of the admin forms.
$shares['users'][] = ['id' => 'all'];
$shares['groups'][] = ['id' => 'all'];
} else {
$key = $row['type'] === 'group' ? 'groups' : 'users';
$shares[$key][] = ['id' => (int) $row['item_id']];
}
}
}
return $shares;
}
/**
* Normalize a posted multiselect of user or group ids to unique integers, allowing the 'all' sentinel.
*
* @param string $name The request variable name.
*
* @return array<int, string|int> Array of IDs with 'all' sentinel allowed.
*/
function syslog_parse_share_ids(string $name): array {
if (!isset_request_var($name)) {
return [];
}
$raw = get_nfilter_request_var($name);
if (!is_array($raw)) {
return [];
}
$ids = [];
foreach ($raw as $id) {
if ($id === 'all') {
$ids[] = 'all';
} elseif ((int) $id > 0) {
$ids[] = (int) $id;
}
}
return array_values(array_unique($ids));
}
/**
* Replace the user and group share rows of one item. Unknown ids are kept;
* they simply never match a real user or group. The 'all' sentinel grants
* the item to every signed-in user with a single row (item_id 0).
*
* @param string $item The item kind.
* @param int $item_id The item ID.
* @param array<int|string> $users Array of user IDs or 'all'.
* @param array<int|string> $groups Array of group IDs or 'all'.
*
* @return void
*/
function syslog_save_item_shares(string $item, int $item_id, array $users, array $groups): void {
global $syslogdb_default;
$share_table = syslog_share_table($item);
if ($share_table === null || (int) $item_id <= 0) {
return;
}
list($table, $column) = $share_table;
syslog_db_execute_prepared("DELETE FROM `$syslogdb_default`.`$table`
WHERE $column = ?",
[(int) $item_id]);
// Duplicates would collide with the composite primary key.
$users = array_unique(array_map('strval', $users));
$groups = array_unique(array_map('strval', $groups));
$grants = [];
if (in_array('all', $users, true) || in_array('all', $groups, true)) {
$grants[] = [(int) $item_id, 'all', 0];
}
foreach ($users as $user_id) {
if ((int) $user_id > 0) {
$grants[] = [(int) $item_id, 'user', (int) $user_id];
}
}
foreach ($groups as $group_id) {
if ((int) $group_id > 0) {
$grants[] = [(int) $item_id, 'group', (int) $group_id];
}
}
foreach ($grants as $grant) {
syslog_db_execute_prepared("INSERT INTO `$syslogdb_default`.`$table`
($column, type, item_id)
VALUES (?, ?, ?)",
$grant);
}
}
/**
* Format a message value with highlighted search terms.
*
* @param string $value The message value.
* @param string $filter The filter settings.
* @param string $href Optional link href.
*
* @return string The formatted HTML output.
*/
function syslog_message_filter_value(string $value, string $filter, string $href = ''): string {
if (get_request_var('search_mode') != 'logical') {
return filter_value($value, $filter, $href);
}
$terms = syslog_logical_positive_terms($GLOBALS['syslog_search_tree'] ?? null);
usort($terms, function ($a, $b) { return strlen($b) - strlen($a); });
$pattern = $terms ? '~(' . implode('|', array_map(function ($term) { return preg_quote($term, '~'); }, $terms)) . ')~iu' : '';
$parts = $pattern ? preg_split($pattern, $value, -1, PREG_SPLIT_DELIM_CAPTURE) : [$value];
if ($parts === false) {
$parts = [$value];
}
$output = '';
foreach ($parts as $index => $part) {
$escaped = htmlspecialchars($part, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$output .= $index % 2 ? '<span class="filteredValue">' . $escaped . '</span>' : $escaped;
}
return $href === '' ? $output : '<a class="linkEditMain" href="' . htmlspecialchars($href, ENT_QUOTES, 'UTF-8') . '">' . $output . '</a>';
}
/**
* Apply a bulk action to selected items.
*
* @param array<int, mixed>|false $selected_items Array of selected item IDs, or false.
* @param string $drp_action The selected action.
* @param array<int|string, string> $action_map Map of actions to function names.
* @param string $export_action Optional export action name.
* @param string $export_items Optional export items config.
*
* @return void
*/
function syslog_apply_selected_items_action($selected_items, string $drp_action, array $action_map, string $export_action = '', string $export_items = ''): void {
if ($selected_items != false) {
if (isset($action_map[$drp_action])) {
$action_function = $action_map[$drp_action];
if (function_exists($action_function)) {
foreach ($selected_items as $selected_item) {
$action_function($selected_item);
}
} else {
cacti_log("SYSLOG ERROR: Bulk action function '$action_function' not found.", false, 'SYSTEM');
}
} elseif ($export_action != '' && $drp_action == $export_action) {
$_SESSION['exporter'] = rawurlencode(serialize($selected_items));
}
}
}
/**
* Download in a separate browsing context so Cacti's page-unload spinner never starts.
*
* @param string $url The URL to load in the iframe.
*
* @return void
*/
function syslog_download_frame(string $url = ''): void {
print "<iframe id='syslog_download' name='syslog_download' hidden title='" . __esc('Syslog download', 'syslog') . "' src='" . html_escape($url === '' ? 'about:blank' : $url) . "'></iframe>";
}
/**
* Close a native bulk confirmation form, targeting exports at the download frame.
*
* @param bool $export Whether this is an export form.
*
* @return void
*/
function syslog_export_form_end(bool $export): void {
global $form_id;
form_end(false);
if (!$export) {
return;
}
syslog_download_frame();
?>
<script type='text/javascript'>
(function() {
var form = document.getElementById(<?php print syslog_json_safe($form_id); ?>);
if (form) form.target = 'syslog_download';
})();
</script>
<?php
}
/**
* Include syslog plugin JavaScript and CSS assets.
*
* @return void
*/
function syslog_include_js(): void {
global $config;
?>
<link rel='stylesheet' href='<?php print $config['url_path']; ?>plugins/syslog/css/search.css?v=<?php print filemtime(__DIR__ . '/css/search.css'); ?>'>
<link rel='stylesheet' href='<?php print $config['url_path']; ?>plugins/syslog/css/dashboard.css?v=<?php print filemtime(__DIR__ . '/css/dashboard.css'); ?>'>
<script type='text/javascript' src='<?php print $config['url_path']; ?>plugins/syslog/js/filter-builder.js?v=<?php print filemtime(__DIR__ . '/js/filter-builder.js'); ?>'></script>
<script type='text/javascript' src='<?php print $config['url_path']; ?>plugins/syslog/js/dashboard.js?v=<?php print filemtime(__DIR__ . '/js/dashboard.js'); ?>'></script>
<script type='text/javascript' src='<?php print $config['url_path']; ?>plugins/syslog/js/functions.js?v=<?php print filemtime(__DIR__ . '/js/functions.js'); ?>'></script>
<?php
}
/**
* __esc() is not enough inside a <script> block, because the browser does
* not HTML-decode there. The value has to arrive as a JSON literal.
*
* @param mixed $value
*
* @return string
*/
function syslog_json_safe($value) {
return json_encode($value, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_THROW_ON_ERROR);
}
/**
* Check if edits are allowed based on remote sync configuration.
*
* @return bool True if edits are allowed, false otherwise.
*/
function syslog_allow_edits(): bool {
global $config;
if (read_config_option('syslog_remote_enabled') == 'on' && read_config_option('syslog_remote_sync_rules') == 'on') {
if ($config['poller_id'] > 1) {
return false;
}
}
return true;
}
/**
* Save data with remote sync support.
*
* @param array<string, mixed> $data The data to save.
* @param string $table The table name.
* @param string $primary The primary key column name.
*
* @return void
*/
function syslog_sync_save(array $data, string $table, string $primary = ''): void {
global $config, $syslogdb_default;
if (read_config_option('syslog_remote_enabled') == 'on' && read_config_option('syslog_remote_sync_rules') == 'on') {
if ($config['poller_id'] == 1) {
$id = syslog_sql_save($data, $table, $primary);
if ($id > 0) {
raise_message(1);
} else {
raise_message(2);
}
$pollers = array_rekey(
db_fetch_assoc('SELECT poller_id
FROM pollers
WHERE disabled = ""
AND id > 1'),
'id', 'id'
);
if (cacti_sizeof($pollers)) {
foreach ($pollers as $poller_id) {
$rcnn_id = poller_connect_to_remote($poller_id);
if ($rcnn_id !== false) {
$id = sql_save($data, $table, $primary, true, $rcnn_id);
}
}
}
} else {
raise_message('syslog_denied', __('Save Failed. Remote Data Collectors in Sync Mode are not allowed to Save Rules. Save from the Main Cacti Server instead.', 'syslog'), MESSAGE_LEVEL_ERROR);
}
} else {
$id = syslog_sql_save($data, $table, $primary);
if ($id > 0) {
raise_message(1);
} else {
raise_message(2);
}
}
}
/**
* Send email alert with optional SMS support.
*
* @param string $to Recipient email address (may include sms@ addresses).
* @param array<int, string> $from Sender email and name as a list: [email, name].
* @param string $subject Email subject.
* @param string $message Email message body (HTML).
* @param string $smsmessage SMS message body.
*
* @return void
*/
function syslog_sendemail(string $to, array $from, string $subject, string $message, string $smsmessage = ''): void {
syslog_debug("Sending Alert email to '" . $to . "'");
$sms = '';
$nonsms = '';
// if there are SMS emails, process separately
if (substr_count($to, 'sms@')) {
$emails = explode(',', $to);
if (cacti_sizeof($emails)) {
foreach ($emails as $email) {
if (substr_count($email, 'sms@')) {
$sms .= ($sms != '' ? ', ' : '') . str_replace('sms@', '', trim($email));
} else {
$nonsms .= ($nonsms != '' ? ', ' : '') . trim($email);
}
}
}
} else {
$nonsms = $to;
}
if (strlen($sms) && $smsmessage != '') {
mailer($from, $sms, '', '', '', $subject, '', $smsmessage);
}
if (strlen($nonsms)) {
if (read_config_option('syslog_html') == 'on') {
mailer($from, $nonsms, '', '', '', $subject, $message, __('Please use an HTML Email Client', 'syslog'));
} else {
$message = strip_tags(str_replace('<br>', "\n", $message));
mailer($from, $nonsms, '', '', '', $subject, '', $message, '', '', false);
}
}
}
const SYSLOG_IMPORT_MAX_BYTES = 5 * 1024 * 1024;
const SYSLOG_IMPORT_VERSION = 1;
/**
* Get import payload from text input or uploaded file.
*
* @param string $redirect_url URL to redirect to on error.
*
* @return string The import payload.
*
* @throws void Exits on error.
*/
function syslog_get_import_xml_payload($redirect_url) {
$import_text = (string) get_nfilter_request_var('import_text');
if (strlen($import_text) > SYSLOG_IMPORT_MAX_BYTES) {
cacti_log('SYSLOG ERROR: Text import payload exceeds the maximum size', false, 'SYSTEM');
raise_message('syslog_import_size_error', __('Text import payload exceeds the maximum size', 'syslog'), MESSAGE_LEVEL_ERROR);
header('Location: ' . $redirect_url);
exit;
}
if (trim($import_text) !== '') {
// textbox input
return $import_text;
}
if (isset($_FILES['import_file']['tmp_name']) &&
$_FILES['import_file']['tmp_name'] !== 'none' &&
$_FILES['import_file']['tmp_name'] !== '') {
// file upload
$tmp_name = $_FILES['import_file']['tmp_name'];
if (!isset($_FILES['import_file']['error']) || $_FILES['import_file']['error'] !== UPLOAD_ERR_OK) {
raise_message('syslog_import_error', __('Unable to read the uploaded import file. Check the file and upload size limit.', 'syslog'), MESSAGE_LEVEL_ERROR);
header('Location: ' . $redirect_url);
exit;
}
if (!is_uploaded_file($tmp_name)) {
raise_message('syslog_import_error', __('Unable to read the uploaded import file. Check the file and upload size limit.', 'syslog'), MESSAGE_LEVEL_ERROR);
header('Location: ' . $redirect_url);
exit;
}
$import_data = syslog_read_import_file($tmp_name);
if ($import_data === false) {
cacti_log('SYSLOG ERROR: Uploaded import file is empty, unreadable, or exceeds the maximum size', false, 'SYSTEM');
raise_message('syslog_import_error', __('Unable to read the uploaded import file. Check the file and upload size limit.', 'syslog'), MESSAGE_LEVEL_ERROR);
header('Location: ' . $redirect_url);
exit;
}
return $import_data;
}
raise_message('syslog_import_error', __('Select an import file or paste its contents before importing.', 'syslog'), MESSAGE_LEVEL_ERROR);
header('Location: ' . $redirect_url);
exit;
}
/**
* Read import file contents safely.
*
* @param string $filename The file path to read.
*
* @return string|false The file contents, or false on failure.
*/
function syslog_read_import_file(string $filename): string|false {
$size = filesize($filename);
if ($size === false || $size <= 0 || $size > SYSLOG_IMPORT_MAX_BYTES) {
return false;
}
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
try {
return fread($handle, $size);
} finally {
fclose($handle);
}
}
/**
* syslog_rules_array2json - encode a list of rule rows as a JSON export document
*
* @param string $table Source rule table, used for uniqueness/version metadata
* @param array<int, array<string, mixed>> $rules Rule rows (the 'id' key is removed before export)
*
* @return string JSON document suitable for download
*/
function syslog_rules_array2json(string $table, array $rules): string {
$templates = [];
foreach ($rules as $rule) {
if (!is_array($rule)) {
continue;
}
unset($rule['id']);
if (!isset($rule['hash']) || $rule['hash'] === '') {
cacti_log("SYSLOG WARNING: Exported $table rule is missing a hash", false, 'SYSTEM');
}
$templates[] = $rule;
}
$encoded = json_encode([
'version' => SYSLOG_IMPORT_VERSION,
'generator' => 'syslog',
'table' => $table,
'templates' => $templates,
], JSON_PRETTY_PRINT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
// json_encode() only fails on malformed data, which cannot occur here;
// fall back to an empty string rather than returning false to callers.
return $encoded === false ? '' : $encoded;
}
/**
* syslog_parse_rule_import - parse a pasted or uploaded rule import payload
*
* Accepts JSON (preferred) or the legacy XML format. Returns an array of
* rule arrays keyed by an incremental template index, mirroring the shape
* previously returned by xml2array() for minimal downstream churn.
*
* @param string $payload Raw import payload.
* @param string $expected_table Destination object table.
*
* @return array<string, array<string, mixed>>|false Parsed templates, or false on failure.
*/
function syslog_parse_rule_import(string $payload, string $expected_table): array|false {
$trimmed = trim($payload);