-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsetup.php
More file actions
728 lines (639 loc) · 27 KB
/
Copy pathsetup.php
File metadata and controls
728 lines (639 loc) · 27 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
<?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/ |
+-------------------------------------------------------------------------+
*/
/**
* Return the CSP nonce attribute for inline <script> tags, safely across
* Cacti versions. Newer Cacti releases enforce a Content-Security-Policy that
* requires a per-request nonce on parser-inserted scripts; older releases lack
* the CactiSecureHeaders class, so this returns an empty string there.
*
* @return string The nonce attribute when supported, otherwise empty string.
*/
function plugin_cycle_csp_nonce(): string {
if (class_exists('CactiSecureHeaders')) {
return CactiSecureHeaders::getNonceAttribute();
}
return '';
}
/**
* Installs the Cycle plugin: registers its Cacti hooks (top_header_tabs,
* top_graph_header_tabs, config_arrays, draw_navigation_text,
* config_settings, api_graph_save, page_head), and registers its realm
* covering cycle.php and cycle_ajax.php (this plugin does not require
* any dedicated database tables). Invoked by Cacti's plugin architecture
* when an administrator installs this plugin from Console > Plugin
* Management, and re-invoked from cycle_check_upgrade() to refresh hook
* registrations after an upgrade.
*
* @return void
*/
function plugin_cycle_install(): void {
api_plugin_register_hook('cycle', 'top_header_tabs', 'cycle_show_tab', 'setup.php');
api_plugin_register_hook('cycle', 'top_graph_header_tabs', 'cycle_show_tab', 'setup.php');
api_plugin_register_hook('cycle', 'config_arrays', 'cycle_config_arrays', 'setup.php');
api_plugin_register_hook('cycle', 'draw_navigation_text', 'cycle_draw_navigation_text', 'setup.php');
api_plugin_register_hook('cycle', 'config_settings', 'cycle_config_settings', 'setup.php');
api_plugin_register_hook('cycle', 'api_graph_save', 'cycle_api_graph_save', 'setup.php');
api_plugin_register_hook('cycle', 'page_head', 'cycle_page_head', 'setup.php');
api_plugin_register_realm('cycle', 'cycle.php,cycle_ajax.php', __('Plugin -> Cycle Graphs', 'cycle'), 1);
cycle_setup_table_new();
}
/**
* Uninstalls the Cycle plugin; currently a no-op placeholder (this
* plugin does not create any tables or settings that require explicit
* cleanup beyond what Cacti's plugin architecture handles automatically).
* Invoked by Cacti's plugin architecture when an administrator
* uninstalls this plugin from Console > Plugin Management.
*
* @return void
*/
function plugin_cycle_uninstall(): void {
// Do any extra Uninstall stuff here
}
/**
* Verifies the plugin's configuration by triggering its upgrade check.
* Invoked by Cacti's plugin architecture on relevant page loads.
*
* @return bool Always returns true.
*/
function plugin_cycle_check_config(): bool {
// Here we will check to ensure everything is configured
cycle_check_upgrade();
return true;
}
/**
* Performs any schema/data migrations needed when upgrading to a newer
* version of this plugin, by delegating to cycle_check_upgrade(). Invoked
* by Cacti's plugin architecture when an installed plugin's version
* increases.
*
* @return bool Always returns false.
*/
function plugin_cycle_upgrade(): bool {
// Here we will upgrade to the newest version
cycle_check_upgrade();
return false;
}
/**
* Detects whether the installed plugin_config version differs from this
* plugin's INFO file version and, if so, re-registers hooks/database
* schema (for enabled/active installs), migrates a legacy realm's user
* permissions to the new realm id (for upgrades from pre-1.0), removes a
* stale legacy 'config_form' hook, and updates the stored plugin_config
* record. Only runs on index.php/plugins.php/cycle.php. Called from
* cycle_config_settings() on every relevant page load.
*
* @return void
*
* @global array $config Reserved/declared for parity with other
* functions in this file; not used directly here
* (the page guard uses $_SERVER['PHP_SELF']
* instead).
*/
function cycle_check_upgrade(): void {
global $config;
$files = ['index.php', 'plugins.php', 'cycle.php'];
if (isset($_SERVER['PHP_SELF']) && !in_array(basename($_SERVER['PHP_SELF']), $files, true)) {
return;
}
$info = plugin_cycle_version();
if (!isset($info['version'], $info['longname'], $info['author'], $info['homepage'])) {
cacti_log('ERROR: Cycle plugin INFO file is missing required fields, skipping upgrade check', false, 'CYCLE');
return;
}
$current = $info['version'];
$old = db_fetch_row("SELECT * FROM plugin_config WHERE directory='cycle'");
if (cacti_sizeof($old) && $current != $old['version']) {
// if the plugin is installed and/or active
if ($old['status'] == 1 || $old['status'] == 4) {
// re-register the hooks
plugin_cycle_install();
// perform a database upgrade
cycle_database_upgrade();
}
if ($old['version'] < '1.0') {
api_plugin_register_realm('cycle', 'cycle.php,cycle_ajax.php', 'Plugin -> Cycle Graphs', 1);
// get the realm id's and change from old to new
$user = db_fetch_cell("SELECT id FROM plugin_realms WHERE file='cycle.php'") + 100;
$users = db_fetch_assoc('SELECT user_id FROM user_auth_realm WHERE realm_id=42');
if (cacti_sizeof($users)) {
foreach ($users as $u) {
db_execute('INSERT INTO user_auth_realm
(realm_id, user_id) VALUES (' . $user . ', ' . $u['user_id'] . ')
ON DUPLICATE KEY UPDATE realm_id=VALUES(realm_id)');
db_execute('DELETE FROM user_auth_realm
WHERE user_id=' . $u['user_id'] . '
AND realm_id=' . $user);
}
}
}
// update the plugin information
$id = db_fetch_cell("SELECT id FROM plugin_config WHERE directory='cycle'");
// remove legacy hook
db_execute('DELETE FROM plugin_hooks WHERE name="cycle" AND hook="config_form"');
db_execute_prepared('UPDATE plugin_config
SET name = ?, author = ?, webpage = ?, version = ?
WHERE id = ?',
[$info['longname'], $info['author'], $info['homepage'], $info['version'], $id]);
// Remove files tombstoned in manifest.json plus the dev-only tests/ tree.
cycle_prune_files();
}
}
/**
* Applies database schema migrations for this plugin; currently a no-op
* placeholder (this plugin's schema has not required migrations since
* its initial release). Called from cycle_check_upgrade() when an
* enabled/active install's version has changed.
*
* @return void
*/
function cycle_database_upgrade(): void {
}
/**
* Verifies that this plugin's PHP/Cacti dependencies are met; currently
* always reports success. Invoked by Cacti's plugin architecture before
* enabling the plugin.
*
* @return bool Always returns true.
*
* @global array $plugins Reserved/declared for parity with other
* dependency-check functions; not used directly
* here.
* @global array $config Reserved/declared for parity with other
* dependency-check functions; not used directly
* here.
*/
function cycle_check_dependencies(): bool {
global $plugins, $config;
return true;
}
/**
* Creates this plugin's database tables; currently a no-op placeholder
* (this plugin does not require any dedicated database tables, relying
* instead on Cacti core's settings tables for its configuration). Called
* from plugin_cycle_install() during plugin installation.
*
* @return void
*/
function cycle_setup_table_new(): void {
}
/**
* Reads this plugin's INFO file and returns its [info] section. Used by
* Cacti's plugin architecture via the api_plugin_version hook, and
* internally by cycle_check_upgrade() to detect/report the plugin's
* version.
*
* @return array The parsed [info] section of the plugin's INFO file (keys
* such as name, version, author, homepage, longname).
*
* @global array $config Cacti global configuration array; used to locate
* the plugin's base path.
*/
function plugin_cycle_version(): array {
global $config;
$info = parse_ini_file($config['base_path'] . '/plugins/cycle/INFO', true);
$info = is_array($info) ? $info : [];
return isset($info['info']) && is_array($info['info']) ? $info['info'] : [];
}
/**
* Hook implementation for Cacti's 'page_head' filter. Intended to include
* this plugin's page-level assets; currently a no-op (the function body
* is empty). Called by Cacti core via api_plugin_hook('page_head', ...)
* while rendering the page <head> section.
*
* @return void
*/
function cycle_page_head(): void {
}
/**
* Hook implementation for Cacti's 'config_settings' filter. Registers the
* "Cycle" Settings/Graph-settings tab and its fields (delay interval,
* default timespan, columns, graphs-per-page, height, width, legend, and
* rotation type/list/tree options), for both the global Settings page
* and per-user preferences. Also triggers this plugin's own upgrade
* check. Called by Cacti core via api_plugin_hook('config_settings', ...)
* while building the Settings page, restricted to settings.php/
* auth_profile.php unless $force is set.
*
* @param bool $force Whether to register the settings regardless of the
* current page (used when called directly from
* validate_request_vars() rather than via the hook);
* defaults to false.
*
* @return void
*
* @global array $tabs Cacti's registered Settings page
* tabs, extended here with the
* 'cycle' tab.
* @global array $settings Cacti's registered Settings page
* fields, extended here with this
* plugin's global settings.
* @global array $tabs_graphs Cacti's registered per-graph
* settings tabs, extended here with
* the 'cycle' tab.
* @global array $settings_user Cacti's registered per-user
* settings fields, extended here
* with this plugin's user-level
* settings.
* @global array $page_refresh_interval Options for the cycle rotation
* refresh delay, used to populate
* the Delay Interval field.
* @global array $graph_timespans Cacti's predefined graph timespan
* options, used to populate the
* Graph Timespan field.
* @global array $cycle_width Options for graph width, used to
* populate the Graph Width field.
* @global array $cycle_height Options for graph height, used to
* populate the Graph Height field.
* @global array $cycle_cols Options for graph columns, used to
* populate the Column Count field.
* @global array $cycle_graphs Options for graphs-per-page, used
* to populate the Number of Graphs
* per Page field.
*/
function cycle_config_settings($force = false): void {
global $tabs, $settings, $tabs_graphs, $settings_user, $page_refresh_interval, $graph_timespans;
global $cycle_width, $cycle_height, $cycle_cols, $cycle_graphs;
// check for an upgrade
plugin_cycle_check_config();
if ($force === false && isset($_SERVER['PHP_SELF']) &&
basename($_SERVER['PHP_SELF']) != 'settings.php' &&
basename($_SERVER['PHP_SELF']) != 'auth_profile.php') {
return;
}
$tabs['cycle'] = __('Cycle', 'cycle');
$tabs_graphs['cycle'] = __('Cycle', 'cycle');
$treeList = array_rekey(get_allowed_trees(), 'id', 'name');
$tempHeader = ['cycle_header' => [
'friendly_name' => __('Cycle Graphs', 'cycle'),
'method' => 'spacer',
]];
$temp = [
'cycle_delay' => [
'friendly_name' => __('Delay Interval', 'cycle'),
'description' => __('This is the time in seconds before the next graph is displayed.', 'cycle'),
'method' => 'drop_array',
'default' => 60,
'array' => $page_refresh_interval
],
'cycle_timespan' => [
'friendly_name' => __('Graph Timespan', 'cycle'),
'description' => __('This is the default timespan that will be displayed on the page.', 'cycle'),
'method' => 'drop_array',
'default' => 5,
'array' => $graph_timespans
],
'cycle_columns' => [
'friendly_name' => __('Column Count', 'cycle'),
'description' => __('In Tree Mode this is the number of columns that will be used.', 'cycle'),
'method' => 'drop_array',
'default' => 2,
'array' => $cycle_cols
],
'cycle_graphs' => [
'friendly_name' => __('Number of Graphs per Page', 'cycle'),
'description' => __('Select the number of graphs to display per page', 'cycle'),
'method' => 'drop_array',
'default' => '4',
'array' => $cycle_graphs,
],
'cycle_height' => [
'friendly_name' => __('Graph Height', 'cycle'),
'description' => __('This sets the graph height for the displayed graphs.', 'cycle'),
'method' => 'drop_array',
'default' => '100',
'array' => $cycle_height
],
'cycle_width' => [
'friendly_name' => __('Graph Width', 'cycle'),
'description' => __('This sets the graph width for the displayed graphs.', 'cycle'),
'method' => 'drop_array',
'default' => '400',
'array' => $cycle_width
],
'cycle_legend' => [
'friendly_name' => __('Display Legend', 'cycle'),
'description' => __('Check this to display legend.', 'cycle'),
'method' => 'checkbox',
'default' => ''
],
'cycle_cheader' => [
'friendly_name' => __('Predefined Rotations', 'cycle'),
'method' => 'spacer',
],
'cycle_custom_graphs_type' => [
'friendly_name' => __('Rotation Type', 'cycle'),
'description' => __('Select which method to use for custom graph rotation. If you select \'Specific List\', you must define a list of Graph ID\'s', 'cycle'),
'method' => 'drop_array',
'default' => '1',
'array' => [0 => __('Legacy (All)', 'cycle'), 1 => __('Specific List', 'cycle'), 2 => __('Tree Mode', 'cycle')],
],
'cycle_custom_graphs_list' => [
'friendly_name' => __('Custom Graph List', 'cycle'),
'description' => __('This must be a comma delimited list of Graph ID\'s to cycle through. For example \'1,2,3,4\'', 'cycle'),
'method' => 'textbox',
'max_length' => 255,
],
'cycle_custom_graphs_tree' => [
'friendly_name' => __('Default Tree', 'cycle'),
'description' => __('Select the graph tree to cycle if Tree Mode is selected', 'cycle'),
'method' => 'drop_array',
'default' => 'None',
'array' => $treeList,
]
];
if (isset($settings['cycle'])) {
$settings['cycle'] = array_merge($settings['cycle'], $tempHeader, $temp);
} else {
$settings['cycle'] = array_merge($tempHeader, $temp);
}
if (isset($settings_user['cycle'])) {
$settings_user['cycle'] = array_merge($settings_user['cycle'], $temp);
} else {
$settings_user['cycle'] = $temp;
}
}
/**
* Hook implementation for Cacti's 'top_header_tabs'/'top_graph_header_tabs'
* filters. Prints a clickable tab icon linking to cycle.php, using a
* different icon when cycle.php is the currently displayed page. Called
* by Cacti core via api_plugin_hook('top_header_tabs'/
* 'top_graph_header_tabs', ...) while rendering the page header tabs, for
* users with access to cycle.php.
*
* @return void Outputs HTML directly.
*
* @global array $config Cacti global configuration array; used to build
* the tab's image/link URLs.
*/
function cycle_show_tab(): void {
global $config;
if (api_user_realm_auth('cycle.php')) {
if (substr_count($_SERVER['REQUEST_URI'], 'cycle.php')) {
print '<a href="' . $config['url_path'] . 'plugins/cycle/cycle.php"><img src="' . $config['url_path'] . 'plugins/cycle/images/tab_cycle_down.gif" alt="' . __('Cycle') . '"></a>';
} else {
print '<a href="' . $config['url_path'] . 'plugins/cycle/cycle.php"><img src="' . $config['url_path'] . 'plugins/cycle/images/tab_cycle.gif" alt="' . __('Cycle') . '"></a>';
}
}
}
/**
* Hook implementation for Cacti's 'config_arrays' filter. Populates the
* shared $cycle_graphs, $cycle_cols, $cycle_height, and $cycle_width
* lookup arrays used throughout this plugin's filter/settings UI (as
* graphs-per-page, column-count, and pixel-size options). Called by
* Cacti core via api_plugin_hook('config_arrays', ...) while building the
* navigation menu.
*
* @return bool Always returns true.
*
* @global array $cycle_graphs Populated here with the graphs-per-page
* options.
* @global array $cycle_cols Populated here with the column-count
* options.
* @global array $cycle_width Populated here with the graph-width pixel
* options.
* @global array $cycle_height Populated here with the graph-height pixel
* options.
*/
function cycle_config_arrays(): bool {
global $cycle_graphs, $cycle_cols, $cycle_width, $cycle_height;
$cycle_graphs = [
1 => __('%d Graph', 1, 'cycle'),
2 => __('%d Graphs', 2, 'cycle'),
4 => __('%d Graphs', 4, 'cycle'),
6 => __('%d Graphs', 6, 'cycle'),
8 => __('%d Graphs', 8, 'cycle'),
10 => __('%d Graphs', 10, 'cycle')
];
$cycle_cols = [
1 => __('%d Column', 1, 'cycle'),
2 => __('%d Columns', 2, 'cycle'),
3 => __('%d Columns', 3, 'cycle'),
4 => __('%d Columns', 4, 'cycle'),
5 => __('%d Columns', 5, 'cycle')
];
$cycle_height = [
75 => __('%d Pixels', 75, 'cycle'),
100 => __('%d Pixels', 100, 'cycle'),
125 => __('%d Pixels', 125, 'cycle'),
150 => __('%d Pixels', 150, 'cycle'),
175 => __('%d Pixels', 175, 'cycle'),
200 => __('%d Pixels', 200, 'cycle'),
250 => __('%d Pixels', 250, 'cycle'),
300 => __('%d Pixels', 300, 'cycle'),
350 => __('%d Pixels', 350, 'cycle'),
400 => __('%d Pixels', 400, 'cycle'),
500 => __('%d Pixels', 500, 'cycle')
];
$cycle_width = [
100 => __('%d Pixels', 100, 'cycle'),
125 => __('%d Pixels', 125, 'cycle'),
150 => __('%d Pixels', 150, 'cycle'),
175 => __('%d Pixels', 175, 'cycle'),
200 => __('%d Pixels', 200, 'cycle'),
250 => __('%d Pixels', 250, 'cycle'),
300 => __('%d Pixels', 300, 'cycle'),
350 => __('%d Pixels', 350, 'cycle'),
400 => __('%d Pixels', 400, 'cycle'),
500 => __('%d Pixels', 500, 'cycle'),
550 => __('%d Pixels', 550, 'cycle'),
600 => __('%d Pixels', 600, 'cycle'),
650 => __('%d Pixels', 650, 'cycle'),
700 => __('%d Pixels', 700, 'cycle'),
800 => __('%d Pixels', 800, 'cycle'),
900 => __('%d Pixels', 900, 'cycle'),
1000 => __('%d Pixels', 1000, 'cycle'),
1100 => __('%d Pixels', 1100, 'cycle'),
1200 => __('%d Pixels', 1200, 'cycle'),
1300 => __('%d Pixels', 1300, 'cycle'),
1400 => __('%d Pixels', 1400, 'cycle'),
1500 => __('%d Pixels', 1500, 'cycle')
];
return true;
}
/**
* Hook implementation for Cacti's 'draw_navigation_text' filter. Adds
* breadcrumb entries for cycle.php's default, view, graphs, and save
* actions. Called by Cacti core via
* api_plugin_hook('draw_navigation_text', ...) while rendering the page
* breadcrumb trail.
*
* @param array $nav The existing breadcrumb map contributed by Cacti
* core and other plugins.
*
* @return array The $nav array with this plugin's breadcrumb entries
* added.
*/
function cycle_draw_navigation_text($nav) {
$nav['cycle.php:'] = ['title' => __('Cycling', 'cycle'), 'mapping' => '', 'url' => 'cycle.php', 'level' => '1'];
$nav['cycle.php:view'] = ['title' => __('Cycling', 'cycle'), 'mapping' => '', 'url' => 'cycle.php', 'level' => '1'];
$nav['cycle.php:graphs'] = ['title' => __('Cycling', 'cycle'), 'mapping' => '', 'url' => 'cycle.php', 'level' => '1'];
$nav['cycle.php:save'] = ['title' => __('Cycling', 'cycle'), 'mapping' => '', 'url' => 'cycle.php', 'level' => '1'];
return $nav;
}
/**
* Hook implementation for Cacti's 'api_graph_save' filter. Intended to
* react to graphs being created/updated; currently a no-op (the function
* body is empty). Called by Cacti core via
* api_plugin_hook('api_graph_save', ...) after a graph is saved.
*
* @param array $save The graph values that were saved.
*
* @return void
*/
function cycle_api_graph_save($save): void {
}
/**
* Removes files and directories that a previous version of this plugin
* shipped but that have since moved or been deleted, using the tombstone
* and whitelist lists in manifest.json. Whitelisted (user-data) paths and
* any VCS metadata (.git*) are never touched; the dev-only tests/ tree is
* removed. Any path that resolves outside the plugin directory (a tampered
* manifest.json) is refused, and any file/directory that cannot be removed
* (e.g. read-only) is reported to the Cacti log. Any top-level entry that is
* neither expected nor a tombstone nor whitelisted is logged to the Cacti
* log and left in place. Called on a plugin version change.
*
* @return void
*
* @global array $config Cacti global configuration array; used to resolve
* the plugin directory.
*/
function cycle_prune_files(): void {
global $config;
$plugin_dir = $config['base_path'] . '/plugins/cycle';
$manifest_path = $plugin_dir . '/manifest.json';
if (!is_readable($manifest_path)) {
return;
}
$manifest = json_decode((string) file_get_contents($manifest_path), true);
if (!is_array($manifest)) {
cacti_log('WARNING: cycle manifest.json could not be parsed; skipping file prune', false, 'CYCLE');
return;
}
$tombstones = isset($manifest['tombstones']) && is_array($manifest['tombstones']) ? $manifest['tombstones'] : [];
$expected = isset($manifest['expected']) && is_array($manifest['expected']) ? $manifest['expected'] : [];
$whitelist = isset($manifest['whitelist']) && is_array($manifest['whitelist']) ? $manifest['whitelist'] : [];
$protected = function (string $rel) use ($whitelist): bool {
if (strncmp($rel, '.git', 4) === 0 || strncmp($rel, '.md', 3) === 0) {
return true;
}
foreach ($whitelist as $entry) {
$entry = trim((string) $entry, '/');
if ($entry !== '' && ($rel === $entry
|| strncmp($rel, $entry . '/', strlen($entry) + 1) === 0
|| strncmp($entry, $rel . '/', strlen($rel) + 1) === 0)) {
return true;
}
}
return false;
};
// Security: resolve the plugin directory so a tampered manifest.json
// cannot steer the prune outside of it.
$plugin_real = realpath($plugin_dir);
// Remove tombstoned (moved/deleted) paths plus the dev-only tests/
// tree and the phpunit.xml test configuration.
$remove = $tombstones;
$remove[] = 'tests/';
$remove[] = 'phpunit.xml';
foreach ($remove as $rel) {
$rel = trim((string) $rel, '/');
if ($rel === '' || $protected($rel)) {
continue;
}
// A tombstone must never contain '.'/'..' segments; a tampered manifest
// could use them to escape the plugin directory or target its root.
$segments = explode('/', $rel);
if (in_array('.', $segments, true) || in_array('..', $segments, true)) {
cacti_log(sprintf('WARNING: cycle prune refused to remove %s: path contains a traversal segment (tampered manifest.json?)', $rel), false, 'CYCLE');
continue;
}
$path = $plugin_dir . '/' . $rel;
if (!is_link($path) && !file_exists($path)) {
continue;
}
// Refuse any path that, after resolving symlinks and ../ segments,
// escapes the plugin directory (protects user data from a tampered
// manifest.json).
$anchor = is_link($path) ? dirname($path) : $path;
$real = realpath($anchor);
if ($real === false || ($real !== $plugin_real && strncmp($real, $plugin_real . DIRECTORY_SEPARATOR, strlen((string) $plugin_real) + 1) !== 0)) {
cacti_log(sprintf('WARNING: cycle prune refused to remove %s: path resolves outside the plugin directory (tampered manifest.json?)', $rel), false, 'CYCLE');
continue;
}
if (is_dir($path) && !is_link($path)) {
$removed = cycle_rmtree($path);
} else {
$removed = @unlink($path);
}
if (!$removed) {
cacti_log(sprintf('WARNING: cycle upgrade could not remove %s (check file/directory permissions)', $rel), false, 'CYCLE');
}
}
// Surface any top-level entry the manifest does not account for.
$known = [];
foreach (array_merge($expected, $tombstones) as $entry) {
$top = explode('/', trim((string) $entry, '/'))[0];
if ($top !== '') {
$known[$top] = true;
}
}
$entries = scandir($plugin_dir);
foreach (($entries !== false ? $entries : []) as $entry) {
if ($entry === '.' || $entry === '..' || $entry === 'tests' || $entry === 'phpunit.xml' || $protected($entry) || isset($known[$entry])) {
continue;
}
cacti_log(sprintf('WARNING: cycle upgrade found a file/directory not described in manifest.json: %s (left in place)', $entry), false, 'CYCLE');
}
}
/**
* Recursively deletes a directory and its contents. Symlinks are removed
* without being followed. Helper for cycle_prune_files().
*
* @param string $dir Absolute path to the directory to remove.
*
* @return bool True if the directory and everything under it was removed;
* false if any entry could not be deleted.
*/
function cycle_rmtree(string $dir): bool {
$entries = scandir($dir);
$ok = true;
foreach (($entries !== false ? $entries : []) as $entry) {
if ($entry === '.' || $entry === '..') {
continue;
}
$path = $dir . '/' . $entry;
if (is_dir($path) && !is_link($path)) {
if (!cycle_rmtree($path)) {
$ok = false;
}
} elseif (!@unlink($path)) {
$ok = false;
}
}
if (!@rmdir($dir)) {
$ok = false;
}
return $ok;
}
?>