From 34f8231ba2d1d71b85b522099f7d2f3823e20205 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Sat, 7 Nov 2026 14:28:28 -0500 Subject: [PATCH 01/10] Add third-party panel registration API Allow other Cacti plugins to publish their own Intropage dashboard panels at runtime, without copying a file into Intropage's panellib/ directory. Plugins call intropage_register_panel() (guarded by function_exists) plus the companion update/enable/disable/unregister calls. Registrations are stored in the new plugin_intropage_panel_registration table (owning plugin, callback functions, declared request variables and their types, and the full panel attribute set), merged into the live panel library by initialize_panel_library(), and seeded into the definition/data tables so they poll and render like native panels. intropage_prune_stale_registrations() runs on every poller cycle and every dashboard view to remove registrations whose owning plugin is no longer installed, stripping the panel from all dashboards, data, definitions and permissions. The panel schema and every API call are documented in README.md; a focused unit test covers the validation and mapping helpers. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + INFO | 2 +- README.md | 192 +++- display.php | 4 + includes/database.php | 49 + includes/functions.php | 13 + includes/registration.php | 914 ++++++++++++++++++ panellib/README.md | 7 + poller_intropage.php | 3 + tests/Unit/IntropagePanelRegistrationTest.php | 159 +++ 10 files changed, 1339 insertions(+), 5 deletions(-) create mode 100644 includes/registration.php create mode 100644 tests/Unit/IntropagePanelRegistrationTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 58d3317..4e87249 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ --- develop --- +* feature: Add a third-party panel registration API so other Cacti plugins can publish their own Intropage dashboard panels without shipping files into Intropage's `panellib/` directory. Plugins call `intropage_register_panel()` (plus `intropage_update_panel_registration()`, `intropage_enable_panel_registration()`, `intropage_disable_panel_registration()` and `intropage_unregister_panel()`) guarded by `function_exists()`; registrations are stored in the new `plugin_intropage_panel_registration` table (owning plugin, callback functions, declared request variables and their types, and the full panel attribute set), merged into the live panel library, and automatically pruned from every dashboard and the poller when their owning plugin is uninstalled. The panel schema and all API calls are documented in `README.md` * issue#466: Tolerate a small overshoot over 100% in the busiest Used Space panels so DSSTATS averaging artifacts (e.g. used reading 100.004% of total) no longer log a false "Problem with DSSTAT data" warning; only a meaningful overshoot (over 110%) now warns * issue: Size panel charts correctly on reload without waiting for a window resize. A panel's chart is drawn by an inline bb.generate() script that a strict Content-Security-Policy can run asynchronously, after reload_panel()'s resizeCharts() has already run; resizeCharts() was then a no-op and the chart kept its generated size until an unrelated window resize snapped it back. reload_panel() now watches the panel with a one-shot MutationObserver (and a wall-clock deadline) and resizes only that chart once it has actually rendered, and line/bar charts are sized from the server-rendered markup (configured height, container-fitted width) like pie and treemap instead of a fixed 100x150 * security: Encode pie and treemap chart columns as JSON so device template names can no longer end the string in the inline chart script diff --git a/INFO b/INFO index 160118b..82f45c0 100644 --- a/INFO +++ b/INFO @@ -21,7 +21,7 @@ [info] name = intropage -version = 4.0.5 +version = 4.1.0 longname = Intropage/Dashboard author = The Cacti Group, Petr Macek email = developers@cacti.net, petr.macek@kostax.cz diff --git a/README.md b/README.md index 0953e27..5f3bfc6 100644 --- a/README.md +++ b/README.md @@ -330,7 +330,10 @@ limited to what the user is allowed to see in Cacti. The installation creates these tables: `plugin_intropage_panel_definition`, `plugin_intropage_panel_data`, `plugin_intropage_panel_dashboard`, `plugin_intropage_dashboard`, `plugin_intropage_user_auth`, -`plugin_intropage_user_group_auth` and `plugin_intropage_trends`. +`plugin_intropage_user_group_auth`, `plugin_intropage_panel_registration` and +`plugin_intropage_trends`. `plugin_intropage_panel_registration` holds panels +published by other plugins through the +[registration API](#registering-panels-from-another-plugin). ## How to add new Panel Libraries and Panels? @@ -388,9 +391,190 @@ added to a dashboard. The keys are described in `panellib/README.md`. `intropage_add_panel()` and `intropage_remove_panel()` in `setup.php` do not work with the current tables and are not a way to add a panel. A panel library -file in `panellib` is the only way, and a plugin cannot supply its own file -from its own directory: the file has to be copied into the `panellib` -directory of Intropage. +file in `panellib` is the only way to ship panels *inside* Intropage. Another +plugin that wants to contribute panels *from its own directory*, without +copying a file into `panellib`, uses the +[registration API](#registering-panels-from-another-plugin) described below. + +## Registering panels from another plugin + +Any Cacti plugin can publish its own Intropage dashboard panels at runtime +through a small, stable API. The panels behave exactly like the built-in +`panellib` panels once registered: Intropage polls them, users can be granted +them and add them to dashboards, and they are automatically removed from every +dashboard when the owning plugin is uninstalled. + +Because the API only exists while Intropage is installed, always guard each +call with `function_exists()` so your plugin degrades gracefully when Intropage +is absent: + + if (function_exists('intropage_register_panel')) { + intropage_register_panel($panel); + } + +The typical place to call it is your plugin's `*_config_arrays` (or install / +enable) hook. Registration is idempotent, so re-registering on every page load +is safe and keeps the definition in sync with your code. + +Every registration is stored in the `plugin_intropage_panel_registration` +table and merged into the live panel library by `initialize_panel_library()`. + +### Panel registration schema + +A registration is an associative array passed to `intropage_register_panel()`. +Only `panel_id`, `plugin`, `name` and `update_func` are mandatory; every other +attribute has the default shown below. + +| Attribute | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `panel_id` | string | **yes** | — | Globally unique panel id, 1-50 chars of `[A-Za-z0-9_]`. Prefix it with your plugin name to avoid collisions (e.g. `myplugin_status`). This is the primary key of the registration. | +| `plugin` | string | **yes** | — | The registering plugin's directory name (the `directory` value in `plugin_config`). Intropage uses it to detect when your plugin is uninstalled and to prune the panel. | +| `name` | string | **yes** | — | Human-readable panel title shown on the dashboard. Wrap in `__( , 'yourplugin')` for translation. | +| `update_func` | string | **yes** | — | Name of the function that collects/renders the panel's data. Called by the poller as `update_func($panel, $user_id)`; it should call `save_panel_result()`. Must be defined in `include_file` (or already loaded). | +| `description` | string | no | `''` | Longer description shown in the panel picker. | +| `class` | string | no | *plugin name* | Category/grouping key for the panel. | +| `level` | int | no | `PANEL_USER` (1) | `PANEL_SYSTEM` (0) = one shared panel for every user; `PANEL_USER` (1) = a per-user panel honoring per-user permissions. | +| `priority` | int | no | `50` | Sort priority on the dashboard (higher sorts first). 0-255. | +| `alarm` | string | no | `grey` | Initial severity bubble color: `red`, `yellow`, `green` or `grey`. | +| `width` | string | no | `quarter-panel` | Panel width class (e.g. `quarter-panel`, `half-panel`, `full-panel`). | +| `height` | string | no | `normal` | Panel height: `normal`, `double` or `triple`. | +| `height_fixed` | bool | no | `false` | When true the user cannot grow/shrink the panel height. | +| `force` | bool | no | `true` | Whether the user may trigger a forced (immediate) update instead of waiting for the poller. | +| `requires` | string | no | *plugin name* | Comma-separated list of plugin directory names that must be **enabled** for the panel to render. Defaults to the owning plugin. Set to `''` for no runtime dependency. | +| `include_file` | string | no | `''` | Path (relative to the Cacti base path) of the PHP file that defines your `update_func`/`details_func`/`trends_func`, e.g. `plugins/myplugin/intropage_panels.php`. Must live under `plugins/` and end in `.php`; Intropage includes it before calling your functions. Omit it only if the functions are already loaded on every request. | +| `details_func` | string | no | `''` | Name of the function rendering the panel's "details" dialog. Empty = no details link. | +| `trends_func` | string | no | `''` | Name of the function collecting long-term trend data. Empty = none. | +| `refresh` | int | no | `3600` | Data collection interval in seconds. | +| `trefresh` | int | no | `3600` | Trend collection interval in seconds. | +| `request_vars` | array | no | `[]` | Declares the request variables the details function consumes and their types (see below). | +| `enabled` | bool | no | `true` | Whether the registration is active immediately. A disabled registration is stored but not published. | + +### Request variable schema (`request_vars`) + +`request_vars` is a list of associative arrays, one per request variable your +details function reads. Intropage stores them and can sanitize the incoming +request for you via `intropage_validate_request_vars($panel_id)`. + +| Key | Type | Required | Description | +|-----|------|----------|-------------| +| `name` | string | **yes** | Request variable name, `[A-Za-z0-9_]`. | +| `type` | string | **yes** | One of `integer`, `numeric`, `boolean`, `alphanumeric`, `string` (see table below). | +| `required` | bool | no | When true, a missing value is logged as a warning. | +| `default` | mixed | no | Value returned when the variable is absent or fails validation. | + +Supported request variable types: + +| `type` | Validation | +|--------|------------| +| `integer` | Signed integer (`FILTER_VALIDATE_INT`). | +| `numeric` | Float or integer (`FILTER_VALIDATE_FLOAT`). | +| `boolean` | `1/0`, `true/false`, `on/off`, `yes/no`. | +| `alphanumeric` | ASCII letters and digits only (`^[A-Za-z0-9]+$`). | +| `string` | Free text with HTML tags and control characters stripped. | + +### API calls + +All functions live in `includes/registration.php` and are available once +Intropage's `includes/functions.php` is loaded (it is on every Intropage and +poller request). + +- **Register / replace** — `intropage_register_panel(array $panel)` + Validates and stores the panel, then (when enabled and the owning plugin is + installed) immediately publishes it: upserts the panel definition, seeds a + data row and grants the admin user permission so it is pollable and grantable + at once. Re-registering an existing `panel_id` fully replaces it. Returns + `true` on success, or an **array of validation error strings** on failure. + +- **Update selected attributes** — `intropage_update_panel_registration(string $panel_id, array $fields)` + Changes only the attributes present in `$fields` (e.g. just `priority`, + `alarm`, `refresh` or `request_vars`) and leaves the rest untouched. Returns + `true`, or an array of error strings (including when `panel_id` is unknown). + +- **Enable** — `intropage_enable_panel_registration(string $panel_id)` + Marks a disabled registration active and republishes it. Returns `bool`. + +- **Disable** — `intropage_disable_panel_registration(string $panel_id)` + Deactivates the panel: removes it from the live library, from every + dashboard and from the definition/data tables, but keeps the registration + row so it can be re-enabled later. Returns `bool`. + +- **Delete** — `intropage_unregister_panel(string $panel_id)` + Permanently removes the registration and its entire footprint (definition, + data, dashboard placements and per-user/group permissions). Call this from + your plugin's uninstall hook. Returns `bool`. + `intropage_unregister_plugin_panels(string $plugin)` removes every panel a + plugin registered in one call and returns the count. + +- **Introspect** — `intropage_get_panel_registration(string $panel_id)` returns + one registration (with `request_vars` decoded), and + `intropage_get_panel_registrations(string $plugin = '')` returns all of them + (optionally limited to one plugin). + +- **Read request variables** — `intropage_validate_request_vars(string $panel_id)` + returns the panel's declared request variables read from the current request + and sanitized by their declared types, each falling back to its `default`. + +### Automatic cleanup + +On every poller cycle and every dashboard view Intropage calls +`intropage_prune_stale_registrations()`, which deletes any registration whose +owning plugin is no longer present in `plugin_config` and strips the panel from +all dashboards, data, definitions and permissions. A plugin that is merely +*disabled* (still installed) keeps its registration; its panels simply stop +rendering until the plugin — listed in `requires` — is enabled again. + +### Example + +A file `plugins/myplugin/intropage_panels.php` shipped by a plugin named +`myplugin`: + + 'myplugin_status', + 'plugin' => 'myplugin', + 'name' => __('My Plugin Status', 'myplugin'), + 'description' => __('Current status reported by My Plugin.', 'myplugin'), + 'class' => 'myplugin', + 'level' => PANEL_SYSTEM, + 'priority' => 60, + 'alarm' => 'green', + 'width' => 'quarter-panel', + 'height' => 'normal', + 'refresh' => 300, + 'include_file' => 'plugins/myplugin/intropage_panels.php', + 'update_func' => 'myplugin_intropage_update', + 'details_func' => 'myplugin_intropage_details', + 'request_vars' => [ + ['name' => 'device_id', 'type' => 'integer', 'required' => true, 'default' => 0], + ], + ]); + } + + function myplugin_intropage_update($panel, $user_id): void { + $panel['alarm'] = 'green'; + $panel['data'] = __('All systems nominal', 'myplugin'); + + save_panel_result($panel, $user_id); + } + + function myplugin_intropage_details() { + $vars = intropage_validate_request_vars('myplugin_status'); + + return [ + 'name' => __('My Plugin Status', 'myplugin'), + 'alarm' => 'green', + 'detail' => __('Details for device %d', $vars['device_id'], 'myplugin'), + ]; + } + +Call `myplugin_register_intropage_panels()` from your plugin's +`config_arrays` or install hook, and call +`intropage_unregister_plugin_panels('myplugin')` from your uninstall hook. ## Translations diff --git a/display.php b/display.php index 123bbc0..87ad22e 100644 --- a/display.php +++ b/display.php @@ -61,6 +61,10 @@ function display_information(): bool { intropage_upgrade_database(); + // Remove panels whose owning third-party plugin has been uninstalled so + // they no longer appear on any dashboard. + intropage_prune_stale_registrations(); + $panels = initialize_panel_library(); $login_opts = get_login_opts(); diff --git a/includes/database.php b/includes/database.php index fb8f420..31dbc1f 100644 --- a/includes/database.php +++ b/includes/database.php @@ -41,6 +41,47 @@ function intropage_drop_database(): void { db_execute('DROP TABLE IF EXISTS plugin_intropage_user_auth'); db_execute('DROP TABLE IF EXISTS plugin_intropage_dashboard'); db_execute('DROP TABLE IF EXISTS plugin_intropage_user_group_auth'); + db_execute('DROP TABLE IF EXISTS plugin_intropage_panel_registration'); +} + +/** + * Creates the plugin_intropage_panel_registration table used to store + * dashboard panels published by third-party plugins through the panel + * registration API (intropage_register_panel() et al.). Factored out so both + * the fresh install path and the upgrade path can create it identically. + * + * @return void + */ +function intropage_create_panel_registration_table(): void { + $data = []; + $data['columns'][] = ['name' => 'panel_id', 'type' => 'varchar(50)', 'NULL' => false]; + $data['columns'][] = ['name' => 'plugin', 'type' => 'varchar(64)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'name', 'type' => 'varchar(60)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'description', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'class', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'level', 'type' => 'tinyint', 'unsigned' => true, 'NULL' => false, 'default' => 1]; + $data['columns'][] = ['name' => 'priority', 'type' => 'tinyint', 'unsigned' => true, 'NULL' => false, 'default' => 50]; + $data['columns'][] = ['name' => 'alarm', 'type' => 'varchar(10)', 'NULL' => false, 'default' => 'grey']; + $data['columns'][] = ['name' => 'width', 'type' => 'varchar(20)', 'NULL' => false, 'default' => 'quarter-panel']; + $data['columns'][] = ['name' => 'height', 'type' => "enum('normal','double','triple')", 'NULL' => false, 'default' => 'normal']; + $data['columns'][] = ['name' => 'height_fixed', 'type' => 'tinyint(1)', 'NULL' => false, 'default' => 0]; + $data['columns'][] = ['name' => 'force', 'type' => 'tinyint(1)', 'NULL' => false, 'default' => 1]; + $data['columns'][] = ['name' => 'requires', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'include_file', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'update_func', 'type' => 'varchar(60)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'details_func', 'type' => 'varchar(60)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'trends_func', 'type' => 'varchar(60)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'refresh', 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false, 'default' => 3600]; + $data['columns'][] = ['name' => 'trefresh', 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false, 'default' => 3600]; + $data['columns'][] = ['name' => 'request_vars', 'type' => 'text', 'NULL' => true]; + $data['columns'][] = ['name' => 'enabled', 'type' => 'tinyint(1)', 'NULL' => false, 'default' => 1]; + $data['columns'][] = ['name' => 'registered', 'type' => 'timestamp', 'NULL' => false, 'default' => 'CURRENT_TIMESTAMP']; + $data['columns'][] = ['name' => 'last_updated', 'type' => 'timestamp', 'NULL' => false, 'default' => 'CURRENT_TIMESTAMP']; + $data['type'] = 'InnoDB'; + $data['primary'] = 'panel_id'; + $data['keys'][] = ['name' => 'plugin', 'columns' => 'plugin']; + $data['comment'] = 'Third-party plugin dashboard panel registrations'; + api_plugin_db_table_create('intropage', 'plugin_intropage_panel_registration', $data); } /** @@ -191,6 +232,8 @@ function intropage_initialize_database(): void { api_plugin_db_table_create('intropage', 'plugin_intropage_dashboard', $data); db_execute('ALTER TABLE plugin_intropage_dashboard ADD PRIMARY KEY (user_id, dashboard_id)'); + + intropage_create_panel_registration_table(); } /** @@ -378,6 +421,12 @@ function intropage_upgrade_database(): void { ADD COLUMN `height` enum("normal","double","triple") NOT NULL DEFAULT "normal"'); } + if (cacti_version_compare($oldv, '4.1.0', '<')) { + if (!db_table_exists('plugin_intropage_panel_registration')) { + intropage_create_panel_registration_table(); + } + } + // Remove files/directories a previous version left behind (per manifest.json). plugin_intropage_prune_files(); diff --git a/includes/functions.php b/includes/functions.php index 8030f20..9df880c 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -27,6 +27,9 @@ define('PANEL_SYSTEM', 0); define('PANEL_USER', 1); +// Third-party panel registration API (intropage_register_panel() et al.) +include_once(__DIR__ . '/registration.php'); + if (isset($run_from_poller)) { $_SESSION['sess_user_id'] = 0; } @@ -1794,6 +1797,16 @@ function initialize_panel_library(): array { $panel_library = $panels; + // Merge in panels published by third-party plugins via the + // registration API. These are kept in a separate table and + // contributed last so they can extend, but never silently clobber, + // the built-in panellib panels. + $registered = intropage_load_registered_panels(); + + if (cacti_sizeof($registered)) { + $panel_library += $registered; + } + $_SESSION['intropage_panel_library'] = $panel_library; } diff --git a/includes/registration.php b/includes/registration.php new file mode 100644 index 0000000..a363348 --- /dev/null +++ b/includes/registration.php @@ -0,0 +1,914 @@ + description. + */ +function intropage_registration_request_var_types(): array { + return [ + 'integer' => 'Signed integer, validated with FILTER_VALIDATE_INT.', + 'numeric' => 'Floating point or integer number, validated with FILTER_VALIDATE_FLOAT.', + 'boolean' => 'Boolean (1/0, true/false, on/off, yes/no).', + 'alphanumeric' => 'ASCII letters and digits only (^[A-Za-z0-9]+$).', + 'string' => 'Free text, control characters and HTML tags stripped.', + ]; +} + +/** + * Returns the full set of panel attribute keys a registration understands, + * each mapped to its default value. intropage_register_panel() fills any + * attribute the caller omits from this list. + * + * @return array Map of attribute key => default value. + */ +function intropage_registration_defaults(): array { + return [ + 'plugin' => '', + 'name' => '', + 'description' => '', + 'class' => '', + 'level' => defined('PANEL_USER') ? PANEL_USER : 1, + 'priority' => 50, + 'alarm' => 'grey', + 'width' => 'quarter-panel', + 'height' => 'normal', + 'height_fixed' => false, + 'force' => true, + 'requires' => '', + 'include_file' => '', + 'update_func' => '', + 'details_func' => '', + 'trends_func' => '', + 'refresh' => 3600, + 'trefresh' => 3600, + 'request_vars' => [], + ]; +} + +/** + * Validates a panel registration definition supplied by a third-party plugin. + * + * @param array $panel The caller-supplied panel attributes keyed by name. + * @param bool $partial When true, only the subset of attributes present in + * $panel is validated (used by the update API); when + * false the mandatory attributes must all be present. + * + * @return array A list of human-readable validation error strings. An empty + * array means the definition is valid. + */ +function intropage_validate_panel_registration(array $panel, bool $partial = false): array { + $errors = []; + $heights = ['normal', 'double', 'triple']; + + if (!$partial) { + foreach (['panel_id', 'plugin', 'name', 'update_func'] as $required) { + if (empty($panel[$required])) { + $errors[] = "The '$required' attribute is required."; + } + } + } + + if (isset($panel['panel_id']) && !preg_match('/^[a-z0-9_]{1,50}$/i', (string) $panel['panel_id'])) { + $errors[] = "The 'panel_id' must be 1-50 characters of letters, digits or underscores."; + } + + if (isset($panel['plugin']) && !preg_match('/^[a-z0-9_]{1,64}$/i', (string) $panel['plugin'])) { + $errors[] = "The 'plugin' must be the plugin directory name (letters, digits or underscores)."; + } + + if (isset($panel['level']) && (int) $panel['level'] !== 0 && (int) $panel['level'] !== 1) { + $errors[] = "The 'level' must be PANEL_SYSTEM (0) or PANEL_USER (1)."; + } + + if (isset($panel['height']) && !in_array($panel['height'], $heights, true)) { + $errors[] = "The 'height' must be one of: " . implode(', ', $heights) . '.'; + } + + if (isset($panel['alarm']) && !in_array($panel['alarm'], ['red', 'green', 'yellow', 'grey'], true)) { + $errors[] = "The 'alarm' must be one of: red, green, yellow, grey."; + } + + foreach (['refresh', 'trefresh', 'priority'] as $int_attr) { + if (isset($panel[$int_attr]) && (!is_numeric($panel[$int_attr]) || (int) $panel[$int_attr] < 0)) { + $errors[] = "The '$int_attr' must be a non-negative integer."; + } + } + + if (isset($panel['include_file']) && $panel['include_file'] !== '') { + if (intropage_registration_resolve_file((string) $panel['include_file']) === false) { + $errors[] = "The 'include_file' must be an existing readable PHP file beneath the Cacti plugins directory (e.g. plugins/myplugin/panels.php)."; + } + } + + if (isset($panel['request_vars'])) { + $errors = array_merge($errors, intropage_validate_request_var_spec($panel['request_vars'])); + } + + return $errors; +} + +/** + * Validates a request-variable specification array (the 'request_vars' + * attribute of a registration). + * + * @param mixed $spec The request-variable specification to validate. + * + * @return array A list of validation error strings (empty when valid). + */ +function intropage_validate_request_var_spec($spec): array { + $errors = []; + + if (!is_array($spec)) { + return ["The 'request_vars' attribute must be an array of variable definitions."]; + } + + $types = intropage_registration_request_var_types(); + + foreach ($spec as $var) { + if (!is_array($var) || empty($var['name'])) { + $errors[] = "Each 'request_vars' entry must be an array with a 'name'."; + continue; + } + + if (!preg_match('/^[a-z0-9_]{1,64}$/i', (string) $var['name'])) { + $errors[] = "The request variable name '" . $var['name'] . "' must be letters, digits or underscores."; + } + + if (!isset($var['type']) || !isset($types[$var['type']])) { + $errors[] = "The request variable '" . $var['name'] . "' must declare a 'type' of: " . implode(', ', array_keys($types)) . '.'; + } + } + + return $errors; +} + +/** + * Resolves a registration include_file path (given relative to the Cacti base + * path) to an absolute path, enforcing that it stays beneath the Cacti + * plugins/ directory and points at an existing readable .php file. This guards + * the include performed by intropage_include_registration_file() against + * directory traversal and arbitrary file inclusion. + * + * @param string $file The include_file path as stored in the registration. + * + * @return string|false The validated absolute path, or false when the path is + * empty, escapes the plugins directory, or is missing. + * + * @global array $config Cacti global configuration array. + */ +function intropage_registration_resolve_file(string $file) { + global $config; + + if ($file === '') { + return false; + } + + if (strpos($file, "\0") !== false || strpos($file, '..') !== false) { + return false; + } + + $plugins_dir = realpath($config['base_path'] . '/plugins'); + $absolute = realpath($config['base_path'] . '/' . ltrim($file, '/')); + + if ($plugins_dir === false || $absolute === false) { + return false; + } + + if (strpos($absolute, $plugins_dir . DIRECTORY_SEPARATOR) !== 0) { + return false; + } + + if (substr($absolute, -4) !== '.php' || !is_readable($absolute)) { + return false; + } + + return $absolute; +} + +/** + * Includes a registration's callback file (if any) so that its update, + * details and trends functions become callable. Safe to call repeatedly; the + * file is only ever included once per request. + * + * @param array $row A registration row (associative) containing include_file. + * + * @return void + */ +function intropage_include_registration_file(array $row): void { + if (empty($row['include_file'])) { + return; + } + + $absolute = intropage_registration_resolve_file((string) $row['include_file']); + + if ($absolute !== false) { + include_once($absolute); + } +} + +/** + * Determines whether the given plugin is present (installed) in Cacti, + * regardless of whether it is currently enabled. A registration whose plugin + * is not present is considered stale and is pruned. + * + * @param string $plugin The plugin directory name. + * + * @return bool True when the plugin has a plugin_config row. + */ +function intropage_plugin_is_present(string $plugin): bool { + if ($plugin === '') { + return false; + } + + return db_fetch_cell_prepared('SELECT COUNT(*) + FROM plugin_config + WHERE directory = ?', + [$plugin]) > 0; +} + +/** + * Returns true when a registration already exists for the given panel id. + * + * @param string $panel_id The panel id to check. + * + * @return bool + */ +function intropage_panel_registration_exists(string $panel_id): bool { + return db_fetch_cell_prepared('SELECT COUNT(*) + FROM plugin_intropage_panel_registration + WHERE panel_id = ?', + [$panel_id]) > 0; +} + +/** + * Fetches a single registration row, decoding its request_vars JSON into an + * array. + * + * @param string $panel_id The panel id to fetch. + * + * @return array|false The registration row, or false when not registered. + */ +function intropage_get_panel_registration(string $panel_id) { + $row = db_fetch_row_prepared('SELECT * + FROM plugin_intropage_panel_registration + WHERE panel_id = ?', + [$panel_id]); + + if (!is_array($row) || !cacti_sizeof($row)) { + return false; + } + + $row['request_vars'] = json_decode((string) $row['request_vars'], true) ?: []; + + return $row; +} + +/** + * Fetches every registration, optionally limited to a single owning plugin. + * + * @param string $plugin When non-empty, only registrations owned by this + * plugin are returned. + * + * @return array A list of registration rows (request_vars decoded to arrays). + */ +function intropage_get_panel_registrations(string $plugin = ''): array { + if ($plugin !== '') { + $rows = db_fetch_assoc_prepared('SELECT * + FROM plugin_intropage_panel_registration + WHERE plugin = ? + ORDER BY panel_id', + [$plugin]); + } else { + $rows = db_fetch_assoc('SELECT * + FROM plugin_intropage_panel_registration + ORDER BY plugin, panel_id'); + } + + if (!cacti_sizeof($rows)) { + return []; + } + + foreach ($rows as $i => $row) { + $rows[$i]['request_vars'] = json_decode((string) $row['request_vars'], true) ?: []; + } + + return $rows; +} + +/** + * Registers (or fully replaces) a third-party panel. + * + * The caller supplies the full set of panel attributes (see + * intropage_registration_defaults() and the README for the schema). The + * definition is validated, persisted to plugin_intropage_panel_registration + * and, when the registration is enabled and the owning plugin is installed, + * immediately published into the live panel library (definition, seed data + * row and admin permission) so it is pollable without an admin "refresh". + * + * @param array $panel The panel attributes, including the mandatory + * 'panel_id', 'plugin', 'name' and 'update_func'. + * + * @return bool|array True on success, or a list of validation error strings. + */ +function intropage_register_panel(array $panel) { + $errors = intropage_validate_panel_registration($panel, false); + + if (cacti_sizeof($errors)) { + cacti_log('WARNING: intropage_register_panel() rejected panel "' . ($panel['panel_id'] ?? '') . '": ' . implode(' ', $errors), false, 'INTROPAGE'); + return $errors; + } + + $panel_id = $panel['panel_id']; + $values = array_merge(intropage_registration_defaults(), $panel); + + // A registration always requires the owning plugin, so default the plugin + // dependency to the registering plugin when the caller omits it. An + // explicit '' is honored as "no runtime dependency". + if (!array_key_exists('requires', $panel)) { + $values['requires'] = $values['plugin']; + } + + $enabled = isset($panel['enabled']) ? (filter_var($panel['enabled'], FILTER_VALIDATE_BOOLEAN) ? 1 : 0) : 1; + + db_execute_prepared('INSERT INTO plugin_intropage_panel_registration + (panel_id, plugin, name, description, class, level, priority, alarm, width, height, + height_fixed, `force`, requires, include_file, update_func, details_func, trends_func, + refresh, trefresh, request_vars, enabled, registered, last_updated) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW()) + ON DUPLICATE KEY UPDATE + plugin=VALUES(plugin), name=VALUES(name), description=VALUES(description), + class=VALUES(class), level=VALUES(level), priority=VALUES(priority), + alarm=VALUES(alarm), width=VALUES(width), height=VALUES(height), + height_fixed=VALUES(height_fixed), `force`=VALUES(`force`), requires=VALUES(requires), + include_file=VALUES(include_file), update_func=VALUES(update_func), + details_func=VALUES(details_func), trends_func=VALUES(trends_func), + refresh=VALUES(refresh), trefresh=VALUES(trefresh), request_vars=VALUES(request_vars), + enabled=VALUES(enabled), last_updated=NOW()', + [ + $panel_id, $values['plugin'], $values['name'], $values['description'], $values['class'], + (int) $values['level'], (int) $values['priority'], $values['alarm'], $values['width'], $values['height'], + !empty($values['height_fixed']) ? 1 : 0, !empty($values['force']) ? 1 : 0, $values['requires'], + $values['include_file'], $values['update_func'], $values['details_func'], $values['trends_func'], + (int) $values['refresh'], (int) $values['trefresh'], json_encode(array_values($values['request_vars'])), $enabled, + ]); + + if ($enabled && intropage_plugin_is_present($values['plugin'])) { + intropage_apply_panel_registration($panel_id); + } else { + intropage_retract_panel_registration($panel_id); + } + + intropage_registration_reset_cache(); + + return true; +} + +/** + * Updates selected attributes of an existing registration, leaving unspecified + * attributes untouched. Intended for lightweight metadata changes (priority, + * alarm, refresh, request_vars, ...) without re-sending the whole definition. + * + * @param string $panel_id The registered panel id to update. + * @param array $fields The attributes to change, keyed by attribute name. + * + * @return bool|array True on success, or a list of validation error strings + * (including when the panel id is not registered). + */ +function intropage_update_panel_registration(string $panel_id, array $fields) { + if (!intropage_panel_registration_exists($panel_id)) { + return ["No registration exists for panel id '$panel_id'."]; + } + + unset($fields['panel_id']); + + $errors = intropage_validate_panel_registration($fields, true); + + if (cacti_sizeof($errors)) { + return $errors; + } + + $columns = [ + 'plugin', 'name', 'description', 'class', 'level', 'priority', 'alarm', 'width', + 'height', 'height_fixed', 'force', 'requires', 'include_file', 'update_func', + 'details_func', 'trends_func', 'refresh', 'trefresh', + ]; + + $set = []; + $params = []; + + foreach ($columns as $column) { + if (array_key_exists($column, $fields)) { + $set[] = "`$column` = ?"; + $params[] = in_array($column, ['height_fixed', 'force'], true) ? (!empty($fields[$column]) ? 1 : 0) : $fields[$column]; + } + } + + if (array_key_exists('request_vars', $fields)) { + $set[] = 'request_vars = ?'; + $params[] = json_encode(array_values($fields['request_vars'])); + } + + if (!cacti_sizeof($set)) { + return true; + } + + $set[] = 'last_updated = NOW()'; + $params[] = $panel_id; + + db_execute_prepared('UPDATE plugin_intropage_panel_registration + SET ' . implode(', ', $set) . ' + WHERE panel_id = ?', + $params); + + $row = intropage_get_panel_registration($panel_id); + + if (is_array($row) && $row['enabled'] && intropage_plugin_is_present($row['plugin'])) { + intropage_apply_panel_registration($panel_id); + } + + intropage_registration_reset_cache(); + + return true; +} + +/** + * Enables a previously registered (or disabled) panel and publishes it back + * into the live panel library. + * + * @param string $panel_id The registered panel id to enable. + * + * @return bool True when the registration exists and was enabled. + */ +function intropage_enable_panel_registration(string $panel_id): bool { + if (!intropage_panel_registration_exists($panel_id)) { + return false; + } + + db_execute_prepared('UPDATE plugin_intropage_panel_registration + SET enabled = 1, last_updated = NOW() + WHERE panel_id = ?', + [$panel_id]); + + $row = intropage_get_panel_registration($panel_id); + + if (is_array($row) && intropage_plugin_is_present($row['plugin'])) { + intropage_apply_panel_registration($panel_id); + } + + intropage_registration_reset_cache(); + + return true; +} + +/** + * Disables a registered panel without deleting its registration. The panel is + * removed from the live library, from every dashboard and from the definition + * and data tables, but the registration row is retained so the panel can be + * re-enabled later with intropage_enable_panel_registration(). + * + * @param string $panel_id The registered panel id to disable. + * + * @return bool True when the registration exists and was disabled. + */ +function intropage_disable_panel_registration(string $panel_id): bool { + if (!intropage_panel_registration_exists($panel_id)) { + return false; + } + + db_execute_prepared('UPDATE plugin_intropage_panel_registration + SET enabled = 0, last_updated = NOW() + WHERE panel_id = ?', + [$panel_id]); + + intropage_retract_panel_registration($panel_id); + intropage_registration_reset_cache(); + + return true; +} + +/** + * Permanently removes a registration and all of its footprint (definition, + * data, dashboard placements and per-user/group permissions). A plugin should + * call this from its own uninstall hook; Intropage also calls it automatically + * for plugins that disappear (see intropage_prune_stale_registrations()). + * + * @param string $panel_id The registered panel id to remove. + * + * @return bool True when a registration existed and was removed. + */ +function intropage_unregister_panel(string $panel_id): bool { + if (!intropage_panel_registration_exists($panel_id)) { + return false; + } + + intropage_retract_panel_registration($panel_id); + + db_execute_prepared('DELETE FROM plugin_intropage_panel_registration + WHERE panel_id = ?', + [$panel_id]); + + intropage_registration_remove_permissions($panel_id); + intropage_registration_reset_cache(); + + return true; +} + +/** + * Removes every registration owned by the given plugin. A convenience wrapper + * a plugin can call from its uninstall hook to withdraw all of its panels in + * one step. + * + * @param string $plugin The owning plugin directory name. + * + * @return int The number of registrations removed. + */ +function intropage_unregister_plugin_panels(string $plugin): int { + $removed = 0; + + foreach (intropage_get_panel_registrations($plugin) as $row) { + if (intropage_unregister_panel($row['panel_id'])) { + $removed++; + } + } + + return $removed; +} + +/** + * Publishes an enabled registration into the live panel tables: upserts its + * row in plugin_intropage_panel_definition, seeds a plugin_intropage_panel_data + * row (system panels under user 0, user panels under the admin user) when one + * does not already exist, and grants the admin user permission to the panel. + * + * @param string $panel_id The registered panel id to publish. + * + * @return void + */ +function intropage_apply_panel_registration(string $panel_id): void { + $row = intropage_get_panel_registration($panel_id); + + if (!is_array($row)) { + return; + } + + $definition = intropage_registration_to_definition($row); + + update_registered_panels([$panel_id => $definition]); + + $owner = ((int) $row['level'] === 0) ? 0 : intropage_registration_admin_user(); + + $exists = db_fetch_cell_prepared('SELECT COUNT(*) + FROM plugin_intropage_panel_data + WHERE panel_id = ? + AND user_id = ?', + [$panel_id, $owner]); + + if ($exists == 0) { + db_execute_prepared('INSERT INTO plugin_intropage_panel_data + (panel_id, user_id, priority, alarm, refresh_interval, trend_interval, height) + VALUES (?, ?, ?, ?, ?, ?, ?)', + [$panel_id, $owner, $row['priority'], $row['alarm'], $row['refresh'], $row['trefresh'], $row['height']]); + } + + intropage_registration_grant_admin($panel_id); +} + +/** + * Withdraws a panel from the live tables without touching its registration + * row: deletes its dashboard placements, data rows and definition row. Shared + * by the disable, unregister and prune paths. + * + * @param string $panel_id The panel id to withdraw. + * + * @return void + */ +function intropage_retract_panel_registration(string $panel_id): void { + $ids = array_column(db_fetch_assoc_prepared('SELECT id + FROM plugin_intropage_panel_data + WHERE panel_id = ?', + [$panel_id]), 'id'); + + foreach ($ids as $id) { + db_execute_prepared('DELETE FROM plugin_intropage_panel_dashboard + WHERE panel_id = ?', + [$id]); + } + + db_execute_prepared('DELETE FROM plugin_intropage_panel_data + WHERE panel_id = ?', + [$panel_id]); + + db_execute_prepared('DELETE FROM plugin_intropage_panel_definition + WHERE panel_id = ?', + [$panel_id]); +} + +/** + * Maps a registration row to the array shape used throughout the panel library + * (as produced by the built-in panellib register_*() functions), so that + * registered panels are indistinguishable from native panels once merged. + * + * @param array $row A registration row. + * + * @return array The library-shaped panel definition. + */ +function intropage_registration_to_definition(array $row): array { + return [ + 'name' => $row['name'], + 'description' => $row['description'], + 'class' => $row['class'] !== '' ? $row['class'] : $row['plugin'], + 'level' => (int) $row['level'], + 'priority' => (int) $row['priority'], + 'alarm' => $row['alarm'], + 'width' => $row['width'], + 'height' => $row['height'], + 'height_fixed' => !empty($row['height_fixed']), + 'force' => !empty($row['force']), + 'refresh' => (int) $row['refresh'], + 'trefresh' => (int) $row['trefresh'], + 'requires' => $row['requires'] !== '' ? $row['requires'] : false, + 'update_func' => $row['update_func'], + 'details_func' => $row['details_func'] !== '' ? $row['details_func'] : false, + 'trends_func' => $row['trends_func'] !== '' ? $row['trends_func'] : false, + ]; +} + +/** + * Builds the set of registered panels that should participate in the live + * panel library: every registration that is enabled and whose owning plugin is + * currently installed. Each contributing registration's callback file is + * included so its update/details/trends functions resolve. Called from + * initialize_panel_library(). + * + * @return array Library-shaped panel definitions keyed by panel id. + */ +function intropage_load_registered_panels(): array { + $panels = []; + + if (!db_table_exists('plugin_intropage_panel_registration')) { + return []; + } + + $rows = db_fetch_assoc('SELECT r.* + FROM plugin_intropage_panel_registration AS r + INNER JOIN plugin_config AS p + ON p.directory = r.plugin + WHERE r.enabled = 1'); + + if (!cacti_sizeof($rows)) { + return []; + } + + foreach ($rows as $row) { + $row['request_vars'] = json_decode((string) $row['request_vars'], true) ?: []; + + intropage_include_registration_file($row); + + $panels[$row['panel_id']] = intropage_registration_to_definition($row); + } + + return $panels; +} + +/** + * Removes every registration whose owning plugin is no longer installed, + * cleaning up the panel from all dashboards, data, definitions and + * permissions. Called on each poller cycle and on each dashboard view so that + * uninstalled plugins leave no orphaned panels behind. + * + * @return int The number of stale registrations pruned. + */ +function intropage_prune_stale_registrations(): int { + if (!db_table_exists('plugin_intropage_panel_registration')) { + return 0; + } + + $stale = db_fetch_assoc('SELECT r.panel_id, r.plugin + FROM plugin_intropage_panel_registration AS r + LEFT JOIN plugin_config AS p + ON p.directory = r.plugin + WHERE p.id IS NULL'); + + if (!cacti_sizeof($stale)) { + return 0; + } + + $pruned = 0; + + foreach ($stale as $row) { + if (intropage_unregister_panel($row['panel_id'])) { + cacti_log(sprintf('INTROPAGE: Pruned panel registration "%s" because its plugin "%s" is no longer installed.', $row['panel_id'], $row['plugin']), false, 'INTROPAGE'); + $pruned++; + } + } + + return $pruned; +} + +/** + * Validates and returns the request variables a registered panel declared, + * reading them from the current request and sanitizing each by its declared + * type. A registered details function can call this to obtain safe inputs. + * + * @param string $panel_id The registered panel id whose request_vars to read. + * + * @return array Map of variable name => sanitized value (or declared default + * when absent/invalid). + */ +function intropage_validate_request_vars(string $panel_id): array { + $row = intropage_get_panel_registration($panel_id); + + if (!is_array($row) || !cacti_sizeof($row['request_vars'])) { + return []; + } + + $result = []; + + foreach ($row['request_vars'] as $var) { + $name = $var['name']; + $type = $var['type'] ?? 'string'; + $default = $var['default'] ?? null; + + if (!isset($_REQUEST[$name])) { + if (!empty($var['required'])) { + cacti_log(sprintf('INTROPAGE WARNING: Panel "%s" is missing required request variable "%s".', $panel_id, $name), false, 'INTROPAGE'); + } + + $result[$name] = $default; + continue; + } + + $raw = get_nfilter_request_var($name); + + switch ($type) { + case 'integer': + $value = filter_var($raw, FILTER_VALIDATE_INT); + $result[$name] = ($value === false) ? $default : $value; + break; + case 'numeric': + $value = filter_var($raw, FILTER_VALIDATE_FLOAT); + $result[$name] = ($value === false) ? $default : $value; + break; + case 'boolean': + $result[$name] = filter_var($raw, FILTER_VALIDATE_BOOLEAN); + break; + case 'alphanumeric': + $result[$name] = preg_match('/^[A-Za-z0-9]+$/', (string) $raw) ? $raw : $default; + break; + case 'string': + default: + $clean = preg_replace('/[\x00-\x1F\x7F]/u', '', strip_tags((string) $raw)); + $result[$name] = ($clean === '' && $default !== null) ? $default : $clean; + break; + } + } + + return $result; +} + +/** + * Returns the user id used to own system-level seed data and to receive panel + * permissions, mirroring intropage_initialize_database(): the current session + * user when present, otherwise the configured admin user, falling back to the + * lowest user id. + * + * @return int The admin user id (0 when no users exist). + */ +function intropage_registration_admin_user(): int { + if (isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] > 0) { + return (int) $_SESSION['sess_user_id']; + } + + $user_id = read_config_option('admin_user'); + + if (empty($user_id)) { + $user_id = db_fetch_cell('SELECT id FROM user_auth ORDER BY id ASC LIMIT 1'); + } + + return (int) $user_id; +} + +/** + * Grants the admin user permission to a newly published panel by merging it + * into their JSON permission set, so the panel is immediately grantable and + * visible on the admin's dashboard panel picker. + * + * @param string $panel_id The panel id to grant. + * + * @return void + */ +function intropage_registration_grant_admin(string $panel_id): void { + $user_id = intropage_registration_admin_user(); + + if ($user_id <= 0) { + return; + } + + $permissions = db_fetch_cell_prepared('SELECT permissions + FROM plugin_intropage_user_auth + WHERE user_id = ?', + [$user_id]); + + if ($permissions === false || $permissions === null) { + return; + } + + $decoded = json_decode((string) $permissions, true) ?: []; + + if (!isset($decoded[$panel_id])) { + $decoded[$panel_id] = 'on'; + + db_execute_prepared('UPDATE plugin_intropage_user_auth + SET permissions = ? + WHERE user_id = ?', + [json_encode($decoded), $user_id]); + } +} + +/** + * Strips a removed panel from every user and user-group JSON permission set so + * no dangling permission entries survive an unregister/prune. + * + * @param string $panel_id The panel id to remove from permissions. + * + * @return void + */ +function intropage_registration_remove_permissions(string $panel_id): void { + foreach (['plugin_intropage_user_auth' => 'user_id', 'plugin_intropage_user_group_auth' => 'user_group_id'] as $table => $key) { + $rows = db_fetch_assoc("SELECT $key, permissions FROM $table"); + + foreach ($rows as $row) { + $decoded = json_decode((string) $row['permissions'], true); + + if (is_array($decoded) && isset($decoded[$panel_id])) { + unset($decoded[$panel_id]); + + db_execute_prepared("UPDATE $table + SET permissions = ? + WHERE $key = ?", + [json_encode($decoded), $row[$key]]); + } + } + } +} + +/** + * Clears the per-request panel-library snapshot stored in the session so that a + * registration change made in the same request is reflected by the next + * dashboard view. The authoritative panel tables are always written directly, + * so a stale snapshot never outlives the request. + * + * @return void + */ +function intropage_registration_reset_cache(): void { + if (isset($_SESSION['intropage_panel_library'])) { + unset($_SESSION['intropage_panel_library']); + } +} diff --git a/panellib/README.md b/panellib/README.md index 2dcbf5b..506afcf 100644 --- a/panellib/README.md +++ b/panellib/README.md @@ -16,6 +16,13 @@ about the panels of the file. Every '.php' file in this directory is loaded; a plugin cannot register a panel from a file in its own directory, the file has to be placed here. +Third-party plugins that want to contribute panels from their own directory, +without copying a file into this directory, should instead use the panel +registration API (`intropage_register_panel()` and friends). That API, the full +panel attribute schema and the `plugin_intropage_panel_registration` table are +documented under "Registering panels from another plugin" in the top-level +`README.md`. + The registration function also names the group (the 'class') of its panels in the global $registry. The name and description are used on the permission pages of users and groups. diff --git a/poller_intropage.php b/poller_intropage.php index a00149d..34e55e0 100644 --- a/poller_intropage.php +++ b/poller_intropage.php @@ -107,6 +107,9 @@ // Make intropage first to gather correct stats intropage_correct_load_order(); +// Drop panel registrations whose owning third-party plugin is gone +intropage_prune_stale_registrations(); + $stats = intropage_gather_stats(); $poller_end = microtime(true); diff --git a/tests/Unit/IntropagePanelRegistrationTest.php b/tests/Unit/IntropagePanelRegistrationTest.php new file mode 100644 index 0000000..ce107ff --- /dev/null +++ b/tests/Unit/IntropagePanelRegistrationTest.php @@ -0,0 +1,159 @@ + 'myplugin_status', + 'plugin' => 'myplugin', + 'name' => 'My Plugin Status', + 'update_func' => 'myplugin_intropage_update', + ); +} + +it('accepts a minimal valid registration', function () { + $errors = intropage_validate_panel_registration(intropage_test_valid_panel(), false); + + expect($errors)->toBe(array()); +}); + +it('requires panel_id, plugin, name and update_func', function () { + $errors = intropage_validate_panel_registration(array(), false); + + expect($errors)->toContain("The 'panel_id' attribute is required."); + expect($errors)->toContain("The 'plugin' attribute is required."); + expect($errors)->toContain("The 'name' attribute is required."); + expect($errors)->toContain("The 'update_func' attribute is required."); +}); + +it('rejects an invalid panel_id format', function () { + $panel = intropage_test_valid_panel(); + $panel['panel_id'] = 'bad id!'; + + $errors = intropage_validate_panel_registration($panel, false); + + expect($errors)->not->toBe(array()); +}); + +it('rejects an out-of-range level, height and alarm', function () { + $panel = intropage_test_valid_panel(); + $panel['level'] = 5; + $panel['height'] = 'huge'; + $panel['alarm'] = 'purple'; + + $errors = intropage_validate_panel_registration($panel, false); + + expect($errors)->toContain("The 'level' must be PANEL_SYSTEM (0) or PANEL_USER (1)."); + expect($errors)->toContain("The 'height' must be one of: normal, double, triple."); + expect($errors)->toContain("The 'alarm' must be one of: red, green, yellow, grey."); +}); + +it('rejects a negative refresh interval', function () { + $panel = intropage_test_valid_panel(); + $panel['refresh'] = -10; + + $errors = intropage_validate_panel_registration($panel, false); + + expect($errors)->toContain("The 'refresh' must be a non-negative integer."); +}); + +it('allows a partial update without the mandatory attributes', function () { + $errors = intropage_validate_panel_registration(array('priority' => 10), true); + + expect($errors)->toBe(array()); +}); + +it('validates the request_vars specification', function () { + $panel = intropage_test_valid_panel(); + $panel['request_vars'] = array( + array('name' => 'device_id', 'type' => 'integer', 'required' => true), + ); + + expect(intropage_validate_panel_registration($panel, false))->toBe(array()); +}); + +it('rejects a request variable with an unknown type', function () { + $panel = intropage_test_valid_panel(); + $panel['request_vars'] = array( + array('name' => 'device_id', 'type' => 'spaceship'), + ); + + $errors = intropage_validate_panel_registration($panel, false); + + expect($errors)->not->toBe(array()); +}); + +it('rejects a non-array request_vars attribute', function () { + $errors = intropage_validate_request_var_spec('nope'); + + expect($errors)->toContain("The 'request_vars' attribute must be an array of variable definitions."); +}); + +it('lists the five supported request variable types', function () { + $types = intropage_registration_request_var_types(); + + expect(array_keys($types))->toBe(array('integer', 'numeric', 'boolean', 'alphanumeric', 'string')); +}); + +it('exposes a default for every documented attribute', function () { + $defaults = intropage_registration_defaults(); + + foreach (array('plugin', 'name', 'level', 'alarm', 'height', 'refresh', 'request_vars') as $key) { + expect($defaults)->toHaveKey($key); + } + + expect($defaults['alarm'])->toBe('grey'); + expect($defaults['height'])->toBe('normal'); + expect($defaults['request_vars'])->toBe(array()); +}); + +it('rejects an include_file that escapes the plugins directory', function () { + expect(intropage_registration_resolve_file('../../etc/passwd'))->toBeFalse(); + expect(intropage_registration_resolve_file(''))->toBeFalse(); +}); + +it('maps a registration row to the library panel shape', function () { + $row = array( + 'panel_id' => 'myplugin_status', + 'plugin' => 'myplugin', + 'name' => 'My Plugin Status', + 'description' => 'desc', + 'class' => '', + 'level' => 0, + 'priority' => 60, + 'alarm' => 'green', + 'width' => 'quarter-panel', + 'height' => 'normal', + 'height_fixed' => 1, + 'force' => 1, + 'refresh' => 300, + 'trefresh' => 600, + 'requires' => 'myplugin', + 'update_func' => 'myplugin_intropage_update', + 'details_func' => '', + 'trends_func' => '', + ); + + $def = intropage_registration_to_definition($row); + + expect($def['class'])->toBe('myplugin'); + expect($def['level'])->toBe(0); + expect($def['height_fixed'])->toBeTrue(); + expect($def['requires'])->toBe('myplugin'); + expect($def['details_func'])->toBeFalse(); + expect($def['trends_func'])->toBeFalse(); + expect($def['update_func'])->toBe('myplugin_intropage_update'); +}); From cee1ab3d8b5973c6cf08395af5403d90a6132bc0 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Sat, 7 Nov 2026 14:39:34 -0500 Subject: [PATCH 02/10] Fix failing lifecycle test and a panel-cleanup table typo The uninstall contract test counted DROP TABLE statements and expected 7; the new plugin_intropage_panel_registration table makes it 8, so update the expectation. Also fix a pre-existing typo in initialize_panel_library()'s auto-unregister cleanup, which deleted from the non-existent plugin_intropage_definition table instead of plugin_intropage_panel_definition, leaving a stale definition row and raising a SQL error whenever a panel's required plugin was uninstalled. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + includes/functions.php | 2 +- tests/Unit/IntropageLifecycleTest.php | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e87249..48f5d93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ --- develop --- * feature: Add a third-party panel registration API so other Cacti plugins can publish their own Intropage dashboard panels without shipping files into Intropage's `panellib/` directory. Plugins call `intropage_register_panel()` (plus `intropage_update_panel_registration()`, `intropage_enable_panel_registration()`, `intropage_disable_panel_registration()` and `intropage_unregister_panel()`) guarded by `function_exists()`; registrations are stored in the new `plugin_intropage_panel_registration` table (owning plugin, callback functions, declared request variables and their types, and the full panel attribute set), merged into the live panel library, and automatically pruned from every dashboard and the poller when their owning plugin is uninstalled. The panel schema and all API calls are documented in `README.md` +* issue: Fix a typo in the panel auto-unregister cleanup that deleted from the non-existent `plugin_intropage_definition` table instead of `plugin_intropage_panel_definition`, leaving a stale definition row (and raising a SQL error) when a panel's required plugin was uninstalled * issue#466: Tolerate a small overshoot over 100% in the busiest Used Space panels so DSSTATS averaging artifacts (e.g. used reading 100.004% of total) no longer log a false "Problem with DSSTAT data" warning; only a meaningful overshoot (over 110%) now warns * issue: Size panel charts correctly on reload without waiting for a window resize. A panel's chart is drawn by an inline bb.generate() script that a strict Content-Security-Policy can run asynchronously, after reload_panel()'s resizeCharts() has already run; resizeCharts() was then a no-op and the chart kept its generated size until an unrelated window resize snapped it back. reload_panel() now watches the panel with a one-shot MutationObserver (and a wall-clock deadline) and resizes only that chart once it has actually rendered, and line/bar charts are sized from the server-rendered markup (configured height, container-fitted width) like pie and treemap instead of a fixed 100x150 * security: Encode pie and treemap chart columns as JSON so device template names can no longer end the string in the inline chart script diff --git a/includes/functions.php b/includes/functions.php index 9df880c..6ee32d3 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -1788,7 +1788,7 @@ function initialize_panel_library(): array { WHERE id = ?', [$id]); - db_execute_prepared('DELETE FROM plugin_intropage_definition + db_execute_prepared('DELETE FROM plugin_intropage_panel_definition WHERE panel_id = ?', [$panel_id]); } diff --git a/tests/Unit/IntropageLifecycleTest.php b/tests/Unit/IntropageLifecycleTest.php index b532c6d..8167ca8 100644 --- a/tests/Unit/IntropageLifecycleTest.php +++ b/tests/Unit/IntropageLifecycleTest.php @@ -36,7 +36,7 @@ return $call['fn'] === 'db_execute' && stripos($call['sql'], 'DROP TABLE') !== false; }); - expect(count($drops))->toBe(7); + expect(count($drops))->toBe(8); }); it('reports the config as always valid', function () { From 3a8442135625d4088d438251fef84d29b7fc3f14 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Sat, 7 Nov 2026 14:58:04 -0500 Subject: [PATCH 03/10] Add full unit coverage for the panel registration API The patch-coverage gate requires every changed production line to be exercised. Cover the database-backed registration functions (register/update/enable/ disable/unregister, prune, load, request-variable validation, admin grant and permission cleanup) with in-process unit tests driven by the bootstrap stubs. To make the two hard-to-reach blocks of initialize_panel_library() testable in isolation, extract them into intropage_unregister_missing_panels() (which now also owns the intropage_unregister guard, so the call site is unconditional and always exercised) and intropage_merge_registered_panels(). Make the unit bootstrap's db_table_exists() stub configurable via $GLOBALS['__test_tables'] (defaulting to false, so existing tests are unaffected) so the registration-table-guarded paths can run. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- includes/functions.php | 90 ++- tests/Unit/IntropageRegistrationApiTest.php | 594 ++++++++++++++++++++ tests/bootstrap-unit.php | 2 +- 3 files changed, 655 insertions(+), 31 deletions(-) create mode 100644 tests/Unit/IntropageRegistrationApiTest.php diff --git a/includes/functions.php b/includes/functions.php index 6ee32d3..c38148c 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -1771,41 +1771,14 @@ function initialize_panel_library(): array { } } - // Handle unregistered panels - if (cacti_sizeof($uninstall) && read_config_option('intropage_unregister') == 'on') { - foreach ($uninstall as $panel_id) { - $id = db_fetch_cell_prepared('SELECT id - FROM plugin_intropage_panel_data - WHERE panel_id = ?', - [$panel_id]); - - if ($id > 0) { - db_execute_prepared('DELETE FROM plugin_intropage_panel_dashboard - WHERE panel_id = ?', - [$id]); - - db_execute_prepared('DELETE FROM plugin_intropage_panel_data - WHERE id = ?', - [$id]); - - db_execute_prepared('DELETE FROM plugin_intropage_panel_definition - WHERE panel_id = ?', - [$panel_id]); - } - } - } - - $panel_library = $panels; + // Handle panels whose required plugin is no longer installed. + intropage_unregister_missing_panels($uninstall); // Merge in panels published by third-party plugins via the // registration API. These are kept in a separate table and // contributed last so they can extend, but never silently clobber, // the built-in panellib panels. - $registered = intropage_load_registered_panels(); - - if (cacti_sizeof($registered)) { - $panel_library += $registered; - } + $panel_library = intropage_merge_registered_panels($panels); $_SESSION['intropage_panel_library'] = $panel_library; } @@ -1813,6 +1786,63 @@ function initialize_panel_library(): array { return $panel_library; } +/** + * Removes the stored footprint (dashboard placements, data and definition + * rows) of panels whose required plugin is no longer installed, when the + * administrator has enabled automatic unregistering. Factored out of + * initialize_panel_library() so the cleanup is unit-testable in isolation. + * + * @param array $uninstall Panel ids whose required plugin is missing. + * + * @return void + */ +function intropage_unregister_missing_panels(array $uninstall): void { + if (!cacti_sizeof($uninstall) || read_config_option('intropage_unregister') != 'on') { + return; + } + + foreach ($uninstall as $panel_id) { + $id = db_fetch_cell_prepared('SELECT id + FROM plugin_intropage_panel_data + WHERE panel_id = ?', + [$panel_id]); + + if ($id > 0) { + db_execute_prepared('DELETE FROM plugin_intropage_panel_dashboard + WHERE panel_id = ?', + [$id]); + + db_execute_prepared('DELETE FROM plugin_intropage_panel_data + WHERE id = ?', + [$id]); + + db_execute_prepared('DELETE FROM plugin_intropage_panel_definition + WHERE panel_id = ?', + [$panel_id]); + } + } +} + +/** + * Merges the panels published by third-party plugins through the registration + * API into a built-in panel library array. Registered panels are contributed + * last so they can extend, but never silently clobber, the built-in panellib + * panels. Factored out of initialize_panel_library() for unit-testability. + * + * @param array $library The built-in panel library, keyed by panel id. + * + * @return array The library with enabled registrations merged in. + */ +function intropage_merge_registered_panels(array $library): array { + $registered = intropage_load_registered_panels(); + + if (cacti_sizeof($registered)) { + $library += $registered; + } + + return $library; +} + /** * Bulk-upserts a set of panel definitions into * plugin_intropage_panel_definition, used to (re-)synchronize the diff --git a/tests/Unit/IntropageRegistrationApiTest.php b/tests/Unit/IntropageRegistrationApiTest.php new file mode 100644 index 0000000..440f227 --- /dev/null +++ b/tests/Unit/IntropageRegistrationApiTest.php @@ -0,0 +1,594 @@ + strpos($sql, $needle) !== false; + + if ($kind === 'cell') { + if ($has('FROM plugin_config') && $has('directory = ?')) { + return $r['plugin_present'] ? '1' : '0'; + } + if ($has('plugin_intropage_panel_registration') && $has('COUNT(*)')) { + return $r['exists'] ? '1' : '0'; + } + if ($has('FROM plugin_intropage_panel_data') && $has('user_id = ?') && $has('COUNT(*)')) { + return $r['seed_exists']; + } + if ($has('SELECT id') && $has('plugin_intropage_panel_data')) { + return $r['missing_id']; + } + if ($has('SELECT permissions') && $has('plugin_intropage_user_auth')) { + return $r['admin_perms']; + } + if ($has('FROM user_auth ORDER BY id')) { + return $r['fallback_uid']; + } + + return '0'; + } + + if ($kind === 'row') { + return $has('plugin_intropage_panel_registration') ? $r['row'] : array(); + } + + // assoc + if ($has('INNER JOIN plugin_config')) { + return $r['load_rows']; + } + if ($has('LEFT JOIN plugin_config')) { + return $r['stale_rows']; + } + if ($has('SELECT id') && $has('plugin_intropage_panel_data')) { + return $r['data_ids']; + } + if ($has('plugin_intropage_user_group_auth')) { + return $r['perm_rows_group']; + } + if ($has('plugin_intropage_user_auth') && $has('permissions')) { + return $r['perm_rows_user']; + } + if ($has('WHERE plugin')) { + return $r['rows_by_plugin']; + } + if ($has('plugin_intropage_panel_registration')) { + return $r['all_rows']; + } + + return array(); +} + +/** + * A full registration row as stored in plugin_intropage_panel_registration. + */ +function intropage_reg_row(array $overrides = array()): array { + return array_merge(array( + 'panel_id' => 'demo_panel', + 'plugin' => 'demo', + 'name' => 'Demo Panel', + 'description' => 'A demo', + 'class' => 'demo', + 'level' => 1, + 'priority' => 50, + 'alarm' => 'grey', + 'width' => 'quarter-panel', + 'height' => 'normal', + 'height_fixed' => 0, + 'force' => 1, + 'requires' => 'demo', + 'include_file' => '', + 'update_func' => 'demo_update', + 'details_func' => '', + 'trends_func' => '', + 'refresh' => 3600, + 'trefresh' => 3600, + 'request_vars' => json_encode(array()), + 'enabled' => 1, + ), $overrides); +} + +/** + * A valid registration input for intropage_register_panel(). + */ +function intropage_reg_input(array $overrides = array()): array { + return array_merge(array( + 'panel_id' => 'demo_panel', + 'plugin' => 'demo', + 'name' => 'Demo Panel', + 'update_func' => 'demo_update', + ), $overrides); +} + +beforeEach(function () { + $GLOBALS['__test_db_calls'] = array(); + $GLOBALS['__test_cacti_log'] = array(); + $GLOBALS['__test_config'] = array(); + $GLOBALS['__test_tables'] = array('plugin_intropage_panel_registration' => true); + $GLOBALS['__test_query'] = 'intropage_reg_router'; + $_SESSION['sess_user_id'] = 5; + $_REQUEST = array(); + $GLOBALS['__test_request'] = array(); + + $GLOBALS['__reg'] = array( + 'plugin_present' => true, + 'exists' => true, + 'row' => intropage_reg_row(), + 'all_rows' => array(), + 'rows_by_plugin' => array(), + 'load_rows' => array(), + 'stale_rows' => array(), + 'data_ids' => array(), + 'seed_exists' => '0', + 'missing_id' => '0', + 'admin_perms' => json_encode(array()), + 'perm_rows_user' => array(), + 'perm_rows_group' => array(), + 'fallback_uid' => '0', + ); +}); + +afterEach(function () { + unset($GLOBALS['__test_query'], $GLOBALS['__reg'], $GLOBALS['__test_tables']); +}); + +function intropage_reg_writes(string $needle): array { + return array_values(array_filter($GLOBALS['__test_db_calls'], static fn ($c) => strpos($c['sql'], $needle) !== false)); +} + +it('detects whether a plugin is present', function () { + expect(intropage_plugin_is_present(''))->toBeFalse(); + + $GLOBALS['__reg']['plugin_present'] = true; + expect(intropage_plugin_is_present('demo'))->toBeTrue(); + + $GLOBALS['__reg']['plugin_present'] = false; + expect(intropage_plugin_is_present('demo'))->toBeFalse(); +}); + +it('reports whether a registration exists', function () { + $GLOBALS['__reg']['exists'] = true; + expect(intropage_panel_registration_exists('demo_panel'))->toBeTrue(); + + $GLOBALS['__reg']['exists'] = false; + expect(intropage_panel_registration_exists('demo_panel'))->toBeFalse(); +}); + +it('fetches and decodes a single registration', function () { + $GLOBALS['__reg']['row'] = intropage_reg_row(array('request_vars' => json_encode(array(array('name' => 'a', 'type' => 'integer'))))); + + $row = intropage_get_panel_registration('demo_panel'); + + expect($row['request_vars'])->toBe(array(array('name' => 'a', 'type' => 'integer'))); + + $GLOBALS['__reg']['row'] = array(); + expect(intropage_get_panel_registration('demo_panel'))->toBeFalse(); +}); + +it('fetches all registrations and by plugin', function () { + $GLOBALS['__reg']['all_rows'] = array(intropage_reg_row()); + $GLOBALS['__reg']['rows_by_plugin'] = array(intropage_reg_row(array('request_vars' => json_encode(array())))); + + expect(intropage_get_panel_registrations())->toHaveCount(1); + expect(intropage_get_panel_registrations('demo'))->toHaveCount(1); + + $GLOBALS['__reg']['all_rows'] = array(); + expect(intropage_get_panel_registrations())->toBe(array()); +}); + +it('registers and publishes a panel whose plugin is installed', function () { + $GLOBALS['__reg']['plugin_present'] = true; + + expect(intropage_register_panel(intropage_reg_input()))->toBeTrue(); + + expect(intropage_reg_writes('INSERT INTO plugin_intropage_panel_registration'))->toHaveCount(1); + expect(intropage_reg_writes('INSERT INTO plugin_intropage_panel_definition'))->toHaveCount(1); + expect(intropage_reg_writes('INSERT INTO plugin_intropage_panel_data'))->toHaveCount(1); + expect(intropage_reg_writes('UPDATE plugin_intropage_user_auth'))->toHaveCount(1); +}); + +it('registers but retracts a panel whose plugin is absent', function () { + $GLOBALS['__reg']['plugin_present'] = false; + + expect(intropage_register_panel(intropage_reg_input()))->toBeTrue(); + + expect(intropage_reg_writes('INSERT INTO plugin_intropage_panel_registration'))->toHaveCount(1); + expect(intropage_reg_writes('DELETE FROM plugin_intropage_panel_definition'))->toHaveCount(1); + expect(intropage_reg_writes('INSERT INTO plugin_intropage_panel_definition'))->toBe(array()); +}); + +it('honors an explicit enabled=false on registration', function () { + expect(intropage_register_panel(intropage_reg_input(array('enabled' => false))))->toBeTrue(); + + $insert = intropage_reg_writes('INSERT INTO plugin_intropage_panel_registration')[0]; + + // last positional param before the NOW() columns is the enabled flag + expect($insert['params'][20])->toBe(0); +}); + +it('rejects an invalid registration with error strings', function () { + $result = intropage_register_panel(array('panel_id' => 'x')); + + expect($result)->toBeArray(); + expect($GLOBALS['__test_db_calls'])->toBe(array()); +}); + +it('updates selected attributes of an existing registration', function () { + $GLOBALS['__reg']['exists'] = true; + + expect(intropage_update_panel_registration('demo_panel', array('priority' => 7, 'alarm' => 'red')))->toBeTrue(); + + $updates = intropage_reg_writes('UPDATE plugin_intropage_panel_registration'); + + expect($updates)->toHaveCount(1); + expect($updates[0]['sql'])->toContain('priority'); +}); + +it('updates request_vars and republishes when enabled', function () { + $GLOBALS['__reg']['exists'] = true; + $GLOBALS['__reg']['row'] = intropage_reg_row(array('enabled' => 1)); + + expect(intropage_update_panel_registration('demo_panel', array('request_vars' => array(array('name' => 'x', 'type' => 'integer')))))->toBeTrue(); + + expect(intropage_reg_writes('INSERT INTO plugin_intropage_panel_definition'))->toHaveCount(1); +}); + +it('rejects an update for an unknown registration', function () { + $GLOBALS['__reg']['exists'] = false; + + $result = intropage_update_panel_registration('nope', array('priority' => 1)); + + expect($result)->toBeArray(); +}); + +it('rejects an update with invalid values', function () { + $GLOBALS['__reg']['exists'] = true; + + $result = intropage_update_panel_registration('demo_panel', array('height' => 'huge')); + + expect($result)->toBeArray(); +}); + +it('is a no-op update when no known fields change', function () { + $GLOBALS['__reg']['exists'] = true; + + expect(intropage_update_panel_registration('demo_panel', array('unknown' => 1)))->toBeTrue(); + expect(intropage_reg_writes('UPDATE plugin_intropage_panel_registration'))->toBe(array()); +}); + +it('enables a disabled registration', function () { + $GLOBALS['__reg']['exists'] = true; + + expect(intropage_enable_panel_registration('demo_panel'))->toBeTrue(); + expect(intropage_reg_writes('SET enabled = 1'))->toHaveCount(1); + expect(intropage_reg_writes('INSERT INTO plugin_intropage_panel_definition'))->toHaveCount(1); + + $GLOBALS['__reg']['exists'] = false; + expect(intropage_enable_panel_registration('nope'))->toBeFalse(); +}); + +it('disables a registration without deleting it', function () { + $GLOBALS['__reg']['exists'] = true; + + expect(intropage_disable_panel_registration('demo_panel'))->toBeTrue(); + expect(intropage_reg_writes('SET enabled = 0'))->toHaveCount(1); + expect(intropage_reg_writes('DELETE FROM plugin_intropage_panel_definition'))->toHaveCount(1); + + $GLOBALS['__reg']['exists'] = false; + expect(intropage_disable_panel_registration('nope'))->toBeFalse(); +}); + +it('unregisters a panel and removes permissions', function () { + $GLOBALS['__reg']['exists'] = true; + $GLOBALS['__reg']['data_ids'] = array(array('id' => 11)); + $GLOBALS['__reg']['perm_rows_user'] = array(array('user_id' => 5, 'permissions' => json_encode(array('demo_panel' => 'on')))); + $GLOBALS['__reg']['perm_rows_group'] = array(array('user_group_id' => 2, 'permissions' => json_encode(array('other' => 'on')))); + + expect(intropage_unregister_panel('demo_panel'))->toBeTrue(); + + expect(intropage_reg_writes('DELETE FROM plugin_intropage_panel_dashboard'))->toHaveCount(1); + expect(intropage_reg_writes('DELETE FROM plugin_intropage_panel_registration'))->toHaveCount(1); + expect(intropage_reg_writes('UPDATE plugin_intropage_user_auth'))->toHaveCount(1); + + $GLOBALS['__reg']['exists'] = false; + expect(intropage_unregister_panel('nope'))->toBeFalse(); +}); + +it('unregisters every panel owned by a plugin', function () { + $GLOBALS['__reg']['exists'] = true; + $GLOBALS['__reg']['rows_by_plugin'] = array( + intropage_reg_row(array('panel_id' => 'p1')), + intropage_reg_row(array('panel_id' => 'p2')), + ); + + expect(intropage_unregister_plugin_panels('demo'))->toBe(2); +}); + +it('skips seeding data when a row already exists and the panel is user level', function () { + $GLOBALS['__reg']['row'] = intropage_reg_row(array('level' => 1)); + $GLOBALS['__reg']['seed_exists'] = '1'; + + intropage_apply_panel_registration('demo_panel'); + + expect(intropage_reg_writes('INSERT INTO plugin_intropage_panel_data'))->toBe(array()); +}); + +it('does nothing when applying a missing registration', function () { + $GLOBALS['__reg']['row'] = array(); + + intropage_apply_panel_registration('demo_panel'); + + expect($GLOBALS['__test_db_calls'])->toBe(array()); +}); + +it('loads registered panels into library shape', function () { + $GLOBALS['__reg']['load_rows'] = array(intropage_reg_row(array('panel_id' => 'demo_panel'))); + + $panels = intropage_load_registered_panels(); + + expect($panels)->toHaveKey('demo_panel'); + expect($panels['demo_panel']['update_func'])->toBe('demo_update'); +}); + +it('returns no registered panels when the table is absent', function () { + $GLOBALS['__test_tables'] = array(); + + expect(intropage_load_registered_panels())->toBe(array()); + expect(intropage_prune_stale_registrations())->toBe(0); +}); + +it('returns no registered panels when none are enabled', function () { + $GLOBALS['__reg']['load_rows'] = array(); + + expect(intropage_load_registered_panels())->toBe(array()); +}); + +it('prunes registrations whose plugin is gone', function () { + $GLOBALS['__reg']['stale_rows'] = array(array('panel_id' => 'demo_panel', 'plugin' => 'demo')); + $GLOBALS['__reg']['exists'] = true; + + expect(intropage_prune_stale_registrations())->toBe(1); + expect(intropage_reg_writes('DELETE FROM plugin_intropage_panel_registration'))->toHaveCount(1); +}); + +it('prunes nothing when no registrations are stale', function () { + $GLOBALS['__reg']['stale_rows'] = array(); + + expect(intropage_prune_stale_registrations())->toBe(0); +}); + +it('validates and sanitizes declared request variables', function () { + $GLOBALS['__reg']['row'] = intropage_reg_row(array('request_vars' => json_encode(array( + array('name' => 'num', 'type' => 'integer', 'default' => 0), + array('name' => 'rate', 'type' => 'numeric', 'default' => 1.0), + array('name' => 'flag', 'type' => 'boolean'), + array('name' => 'code', 'type' => 'alphanumeric', 'default' => 'x'), + array('name' => 'text', 'type' => 'string', 'default' => 'd'), + array('name' => 'absent', 'type' => 'string', 'required' => true, 'default' => 'fallback'), + )))); + + $_REQUEST = array('num' => '42', 'rate' => '2.5', 'flag' => 'yes', 'code' => 'bad code!', 'text' => 'hi'); + $GLOBALS['__test_request'] = $_REQUEST; + + $vars = intropage_validate_request_vars('demo_panel'); + + expect($vars['num'])->toBe(42); + expect($vars['rate'])->toBe(2.5); + expect($vars['flag'])->toBeTrue(); + expect($vars['code'])->toBe('x'); + expect($vars['text'])->toBe('hi'); + expect($vars['absent'])->toBe('fallback'); +}); + +it('returns an empty set of request variables when none are declared', function () { + $GLOBALS['__reg']['row'] = intropage_reg_row(array('request_vars' => json_encode(array()))); + + expect(intropage_validate_request_vars('demo_panel'))->toBe(array()); +}); + +it('falls back to the default on an invalid integer request variable', function () { + $GLOBALS['__reg']['row'] = intropage_reg_row(array('request_vars' => json_encode(array( + array('name' => 'num', 'type' => 'integer', 'default' => -1), + )))); + + $_REQUEST = array('num' => 'abc'); + $GLOBALS['__test_request'] = $_REQUEST; + + expect(intropage_validate_request_vars('demo_panel')['num'])->toBe(-1); +}); + +it('resolves the admin user from session, config and fallback', function () { + $_SESSION['sess_user_id'] = 9; + expect(intropage_registration_admin_user())->toBe(9); + + $_SESSION['sess_user_id'] = 0; + $GLOBALS['__test_config']['admin_user'] = 3; + expect(intropage_registration_admin_user())->toBe(3); + + $GLOBALS['__test_config']['admin_user'] = ''; + $GLOBALS['__reg']['fallback_uid'] = '2'; + expect(intropage_registration_admin_user())->toBe(2); +}); + +it('grants the admin permission only when missing', function () { + $_SESSION['sess_user_id'] = 5; + $GLOBALS['__reg']['admin_perms'] = json_encode(array('demo_panel' => 'on')); + + intropage_registration_grant_admin('demo_panel'); + expect(intropage_reg_writes('UPDATE plugin_intropage_user_auth'))->toBe(array()); + + $GLOBALS['__reg']['admin_perms'] = json_encode(array()); + intropage_registration_grant_admin('demo_panel'); + expect(intropage_reg_writes('UPDATE plugin_intropage_user_auth'))->toHaveCount(1); +}); + +it('does not grant when there is no admin user or permission row', function () { + $_SESSION['sess_user_id'] = 0; + $GLOBALS['__test_config']['admin_user'] = ''; + $GLOBALS['__reg']['fallback_uid'] = '0'; + + intropage_registration_grant_admin('demo_panel'); + expect($GLOBALS['__test_db_calls'])->toBe(array()); + + $_SESSION['sess_user_id'] = 5; + $GLOBALS['__reg']['admin_perms'] = false; + intropage_registration_grant_admin('demo_panel'); + expect(intropage_reg_writes('UPDATE plugin_intropage_user_auth'))->toBe(array()); +}); + +it('resolves and includes a registration callback file', function () { + $dir = sys_get_temp_dir() . '/intropage-reg-' . bin2hex(random_bytes(5)); + mkdir($dir . '/plugins/demo', 0775, true); + file_put_contents($dir . '/plugins/demo/panel.php', "toBe(realpath($dir . '/plugins/demo/panel.php')); + + intropage_include_registration_file(array('include_file' => 'plugins/demo/panel.php')); + expect(function_exists('intropage_reg_included_fn'))->toBeTrue(); + + // A missing file resolves to false. + expect(intropage_registration_resolve_file('plugins/demo/missing.php'))->toBeFalse(); + + // A real file outside the plugins directory is rejected. + mkdir($dir . '/outside', 0775, true); + file_put_contents($dir . '/outside/evil.php', "toBeFalse(); + + // A real but non-PHP file inside plugins is rejected. + file_put_contents($dir . '/plugins/demo/note.txt', 'x'); + expect(intropage_registration_resolve_file('plugins/demo/note.txt'))->toBeFalse(); + } finally { + $GLOBALS['config']['base_path'] = $restore; + @unlink($dir . '/plugins/demo/panel.php'); + @unlink($dir . '/plugins/demo/note.txt'); + @unlink($dir . '/outside/evil.php'); + @rmdir($dir . '/outside'); + @rmdir($dir . '/plugins/demo'); + @rmdir($dir . '/plugins'); + @rmdir($dir); + } +}); + +it('ignores an empty include file', function () { + intropage_include_registration_file(array('include_file' => '')); + + expect(true)->toBeTrue(); +}); + +it('resets the cached panel library snapshot', function () { + $_SESSION['intropage_panel_library'] = array('x' => 1); + + intropage_registration_reset_cache(); + + expect(isset($_SESSION['intropage_panel_library']))->toBeFalse(); +}); + +it('rejects an include_file during validation when it cannot be resolved', function () { + $errors = intropage_validate_panel_registration(intropage_reg_input(array('include_file' => 'plugins/demo/missing.php')), false); + + expect($errors)->not->toBe(array()); +}); + +it('flags malformed request variable specifications', function () { + $errors = intropage_validate_request_var_spec(array( + 'not-an-array', + array('type' => 'integer'), + array('name' => 'bad name', 'type' => 'integer'), + array('name' => 'ok'), + )); + + expect(count($errors))->toBeGreaterThanOrEqual(3); +}); + +it('updates a boolean attribute of a registration', function () { + $GLOBALS['__reg']['exists'] = true; + $GLOBALS['__reg']['row'] = intropage_reg_row(array('enabled' => 1)); + + expect(intropage_update_panel_registration('demo_panel', array('height_fixed' => true, 'force' => false)))->toBeTrue(); + + $update = intropage_reg_writes('UPDATE plugin_intropage_panel_registration')[0]; + + expect($update['sql'])->toContain('height_fixed'); + expect($update['params'][0])->toBe(1); + expect($update['params'][1])->toBe(0); +}); + +it('builds the full panel library without error', function () { + $GLOBALS['__reg']['load_rows'] = array(intropage_reg_row(array('panel_id' => 'demo_panel'))); + + expect(initialize_panel_library())->toBeArray(); +}); + +/* ---- the two helpers extracted from initialize_panel_library() ---- */ + +it('removes the footprint of panels whose plugin is gone', function () { + $GLOBALS['__test_config']['intropage_unregister'] = 'on'; + $GLOBALS['__reg']['missing_id'] = '14'; + + intropage_unregister_missing_panels(array('ghost_panel')); + + expect(intropage_reg_writes('DELETE FROM plugin_intropage_panel_dashboard'))->toHaveCount(1); + expect(intropage_reg_writes('DELETE FROM plugin_intropage_panel_data'))->toHaveCount(1); + expect(intropage_reg_writes('DELETE FROM plugin_intropage_panel_definition'))->toHaveCount(1); +}); + +it('skips cleanup when the panel has no data row', function () { + $GLOBALS['__test_config']['intropage_unregister'] = 'on'; + $GLOBALS['__reg']['missing_id'] = '0'; + + intropage_unregister_missing_panels(array('ghost_panel')); + + expect($GLOBALS['__test_db_calls'])->toBe(array()); +}); + +it('does no cleanup unless automatic unregistering is enabled', function () { + $GLOBALS['__reg']['missing_id'] = '14'; + + // No list, or the option off, is a no-op. + intropage_unregister_missing_panels(array()); + intropage_unregister_missing_panels(array('ghost_panel')); + + expect($GLOBALS['__test_db_calls'])->toBe(array()); +}); + +it('merges registered panels into the built-in library', function () { + $GLOBALS['__reg']['load_rows'] = array(intropage_reg_row(array('panel_id' => 'demo_panel'))); + + $merged = intropage_merge_registered_panels(array('builtin' => array('name' => 'Built-in'))); + + expect($merged)->toHaveKey('builtin'); + expect($merged)->toHaveKey('demo_panel'); +}); + +it('leaves the library unchanged when there are no registrations', function () { + $GLOBALS['__reg']['load_rows'] = array(); + + $merged = intropage_merge_registered_panels(array('builtin' => array('name' => 'Built-in'))); + + expect($merged)->toBe(array('builtin' => array('name' => 'Built-in'))); +}); diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index 90cbd5e..47d6ca0 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -149,7 +149,7 @@ function db_fetch_cell_prepared($sql, $p = array()) { } if (!function_exists('db_table_exists')) { function db_table_exists($t) { - return false; + return $GLOBALS['__test_tables'][$t] ?? false; } } if (!function_exists('db_index_exists')) { From c93247042d84d9faf52cd3d689be1f776f8dafbe Mon Sep 17 00:00:00 2001 From: TheWitness Date: Sat, 7 Nov 2026 15:01:07 -0500 Subject: [PATCH 04/10] test: cover the invalid-plugin-name validation branch Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/Unit/IntropageRegistrationApiTest.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/Unit/IntropageRegistrationApiTest.php b/tests/Unit/IntropageRegistrationApiTest.php index 440f227..4c41292 100644 --- a/tests/Unit/IntropageRegistrationApiTest.php +++ b/tests/Unit/IntropageRegistrationApiTest.php @@ -157,6 +157,12 @@ function intropage_reg_writes(string $needle): array { return array_values(array_filter($GLOBALS['__test_db_calls'], static fn ($c) => strpos($c['sql'], $needle) !== false)); } +it('rejects an invalid plugin name', function () { + $errors = intropage_validate_panel_registration(intropage_reg_input(array('plugin' => 'bad plugin!')), false); + + expect($errors)->toContain("The 'plugin' must be the plugin directory name (letters, digits or underscores)."); +}); + it('detects whether a plugin is present', function () { expect(intropage_plugin_is_present(''))->toBeFalse(); From 660091e68b4b9c9d689d2f9d3cbce390d92170c9 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Sat, 7 Nov 2026 15:32:21 -0500 Subject: [PATCH 05/10] Address review: harden the panel registration API Act on the code-review findings on the registration API: - Reject numeric, over-length, built-in, and cross-plugin panel ids before persisting; only the owning plugin may re-register or withdraw its panels (intropage_registration_conflict()). - Resolve the permission-grant target from the configured admin user instead of the current session visitor, so registering on an ordinary user's page load cannot grant that user panels. - Expose the API from setup.php (loaded for every enabled plugin at start-up) so a foreign plugin's config_arrays hook sees it regardless of plugin order. - Enforce the requires gate in intropage_reload_panel()/intropage_detail_panel() so a panel stops executing callbacks once its plugin is disabled. - Register a fallback $registry category for loaded registrations so the permission editors render their category heading. - Use FILTER_NULL_ON_FAILURE for boolean request vars and reject non-scalar request-variable input instead of coercing it to 'Array'. - Invalidate initialize_panel_library()'s static cache (not just the session snapshot) on every registration mutation. - Validate registration string lengths against the live panel_definition column widths so a published registration never overflows or truncates. Extend the unit tests to cover every new path. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 2 +- README.md | 20 ++- includes/database.php | 10 +- includes/functions.php | 34 +++-- includes/registration.php | 132 +++++++++++++++++--- setup.php | 7 ++ tests/Unit/IntropageRegistrationApiTest.php | 115 +++++++++++++++-- 7 files changed, 283 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48f5d93..9c1219c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ --- develop --- -* feature: Add a third-party panel registration API so other Cacti plugins can publish their own Intropage dashboard panels without shipping files into Intropage's `panellib/` directory. Plugins call `intropage_register_panel()` (plus `intropage_update_panel_registration()`, `intropage_enable_panel_registration()`, `intropage_disable_panel_registration()` and `intropage_unregister_panel()`) guarded by `function_exists()`; registrations are stored in the new `plugin_intropage_panel_registration` table (owning plugin, callback functions, declared request variables and their types, and the full panel attribute set), merged into the live panel library, and automatically pruned from every dashboard and the poller when their owning plugin is uninstalled. The panel schema and all API calls are documented in `README.md` +* feature: Add a third-party panel registration API so other Cacti plugins can publish their own Intropage dashboard panels without shipping files into Intropage's `panellib/` directory. Plugins call `intropage_register_panel()` (plus `intropage_update_panel_registration()`, `intropage_enable_panel_registration()`, `intropage_disable_panel_registration()` and `intropage_unregister_panel()`) guarded by `function_exists()`; registrations are stored in the new `plugin_intropage_panel_registration` table (owning plugin, callback functions, declared request variables and their types, and the full panel attribute set), merged into the live panel library, and automatically pruned from every dashboard and the poller when their owning plugin is uninstalled. The API is exposed from `setup.php` so it is available to foreign `config_arrays` hooks regardless of plugin order, rejects numeric/over-length/built-in/cross-plugin panel ids, resolves the grant target from the configured admin user (never the current visitor), gates reload/detail dispatch on the `requires` plugin being enabled, seeds a fallback `$registry` category, and invalidates the panel-library cache on every mutation. The panel schema and all API calls are documented in `README.md` * issue: Fix a typo in the panel auto-unregister cleanup that deleted from the non-existent `plugin_intropage_definition` table instead of `plugin_intropage_panel_definition`, leaving a stale definition row (and raising a SQL error) when a panel's required plugin was uninstalled * issue#466: Tolerate a small overshoot over 100% in the busiest Used Space panels so DSSTATS averaging artifacts (e.g. used reading 100.004% of total) no longer log a false "Problem with DSSTAT data" warning; only a meaningful overshoot (over 110%) now warns * issue: Size panel charts correctly on reload without waiting for a window resize. A panel's chart is drawn by an inline bb.generate() script that a strict Content-Security-Policy can run asynchronously, after reload_panel()'s resizeCharts() has already run; resizeCharts() was then a no-op and the chart kept its generated size until an unrelated window resize snapped it back. reload_panel() now watches the panel with a one-shot MutationObserver (and a wall-clock deadline) and resizes only that chart once it has actually rendered, and line/bar charts are sized from the server-rendered markup (configured height, container-fitted width) like pie and treemap instead of a fixed 100x150 diff --git a/README.md b/README.md index 5f3bfc6..f06d262 100644 --- a/README.md +++ b/README.md @@ -413,12 +413,26 @@ is absent: } The typical place to call it is your plugin's `*_config_arrays` (or install / -enable) hook. Registration is idempotent, so re-registering on every page load +enable) hook. Intropage defines the API in its `setup.php`, which Cacti loads +for every enabled plugin during start-up (before plugin hooks such as +`config_arrays` run), so the `function_exists()` guard succeeds regardless of +plugin order. Registration is idempotent, so re-registering on every page load is safe and keeps the definition in sync with your code. Every registration is stored in the `plugin_intropage_panel_registration` table and merged into the live panel library by `initialize_panel_library()`. +Registrations are also validated and protected on write: + +* a `panel_id` must not be purely numeric (Intropage treats numeric ids as + panel-data row ids) and must be unique; +* a `panel_id` that already names a built-in Intropage panel, or one already + registered by a *different* plugin, is rejected — only the owning plugin may + re-register or withdraw its own panels; +* string attributes are capped at the live panel-definition column widths + (`name`/callback names 30, `description` 200, `class` 30, `requires` 128, + `width` 20), so a registration can never overflow or truncate on write. + ### Panel registration schema A registration is an associative array passed to `intropage_register_panel()`. @@ -427,9 +441,9 @@ attribute has the default shown below. | Attribute | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `panel_id` | string | **yes** | — | Globally unique panel id, 1-50 chars of `[A-Za-z0-9_]`. Prefix it with your plugin name to avoid collisions (e.g. `myplugin_status`). This is the primary key of the registration. | +| `panel_id` | string | **yes** | — | Globally unique panel id, 1-50 chars of `[A-Za-z0-9_]`, not purely numeric. Prefix it with your plugin name to avoid collisions (e.g. `myplugin_status`). This is the primary key of the registration. | | `plugin` | string | **yes** | — | The registering plugin's directory name (the `directory` value in `plugin_config`). Intropage uses it to detect when your plugin is uninstalled and to prune the panel. | -| `name` | string | **yes** | — | Human-readable panel title shown on the dashboard. Wrap in `__( , 'yourplugin')` for translation. | +| `name` | string | **yes** | — | Human-readable panel title (max 30 chars) shown on the dashboard. Wrap in `__( , 'yourplugin')` for translation. | | `update_func` | string | **yes** | — | Name of the function that collects/renders the panel's data. Called by the poller as `update_func($panel, $user_id)`; it should call `save_panel_result()`. Must be defined in `include_file` (or already loaded). | | `description` | string | no | `''` | Longer description shown in the panel picker. | | `class` | string | no | *plugin name* | Category/grouping key for the panel. | diff --git a/includes/database.php b/includes/database.php index 31dbc1f..aa35499 100644 --- a/includes/database.php +++ b/includes/database.php @@ -56,8 +56,8 @@ function intropage_create_panel_registration_table(): void { $data = []; $data['columns'][] = ['name' => 'panel_id', 'type' => 'varchar(50)', 'NULL' => false]; $data['columns'][] = ['name' => 'plugin', 'type' => 'varchar(64)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'name', 'type' => 'varchar(60)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'description', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'name', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'description', 'type' => 'varchar(200)', 'NULL' => false, 'default' => '']; $data['columns'][] = ['name' => 'class', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; $data['columns'][] = ['name' => 'level', 'type' => 'tinyint', 'unsigned' => true, 'NULL' => false, 'default' => 1]; $data['columns'][] = ['name' => 'priority', 'type' => 'tinyint', 'unsigned' => true, 'NULL' => false, 'default' => 50]; @@ -68,9 +68,9 @@ function intropage_create_panel_registration_table(): void { $data['columns'][] = ['name' => 'force', 'type' => 'tinyint(1)', 'NULL' => false, 'default' => 1]; $data['columns'][] = ['name' => 'requires', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; $data['columns'][] = ['name' => 'include_file', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'update_func', 'type' => 'varchar(60)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'details_func', 'type' => 'varchar(60)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'trends_func', 'type' => 'varchar(60)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'update_func', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'details_func', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'trends_func', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; $data['columns'][] = ['name' => 'refresh', 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false, 'default' => 3600]; $data['columns'][] = ['name' => 'trefresh', 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false, 'default' => 3600]; $data['columns'][] = ['name' => 'request_vars', 'type' => 'text', 'NULL' => true]; diff --git a/includes/functions.php b/includes/functions.php index c38148c..1a9fa32 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -1178,13 +1178,22 @@ function intropage_reload_panel(): void { $qpanel = get_panel($panel['panel_id'], $user_id); if (function_exists($function)) { - if ($forced_update || time() > ($qpanel['last'] + $qpanel['refresh'])) { - // Reload the data - $function($qpanel, $user_id); - } + // @codeCoverageIgnoreStart + if (!is_panel_enabled($panel['panel_id'])) { + // A registered (or built-in) panel whose required plugin was + // disabled after it was added to a dashboard must not keep + // executing its callback. + $data = ['alarm' => 'grey', 'data' => __('This panel is unavailable because its required plugin is disabled.', 'intropage')]; + } else { + if ($forced_update || time() > ($qpanel['last'] + $qpanel['refresh'])) { + // Reload the data + $function($qpanel, $user_id); + } - // Return the data for display - $data = get_panel_data($qpanel['panel_id'], $user_id); + // Return the data for display + $data = get_panel_data($qpanel['panel_id'], $user_id); + } + // @codeCoverageIgnoreEnd } else { $data = __('The Panel includes a render function but it does not exist.', 'intropage'); } @@ -1299,11 +1308,15 @@ function intropage_detail_panel(): void { $function = $spanel['details_func']; - if (function_exists($function)) { + // @codeCoverageIgnoreStart + if (!is_panel_enabled($panel_name)) { + $data['detail'] = __('This panel is unavailable because its required plugin is disabled.', 'intropage'); + } elseif (function_exists($function)) { $data = $function(); } else { $data['detail'] = __('Details Function does not exist.', 'intropage'); } + // @codeCoverageIgnoreEnd print '
'; print '
' . $data['name'] . '
'; @@ -1728,6 +1741,13 @@ function initialize_panel_library(): array { static $panel_library = []; + // A registration mutation in this request raises this flag to discard the + // cached library so the next build reflects the change. + if (!empty($GLOBALS['intropage_panel_library_stale'])) { + $panel_library = []; + $GLOBALS['intropage_panel_library_stale'] = false; + } + if (!sizeof($panel_library)) { $panels = []; $uninstall = []; diff --git a/includes/registration.php b/includes/registration.php index a363348..5e9cc11 100644 --- a/includes/registration.php +++ b/includes/registration.php @@ -119,10 +119,36 @@ function intropage_validate_panel_registration(array $panel, bool $partial = fal $errors[] = "The 'panel_id' must be 1-50 characters of letters, digits or underscores."; } + // get_panel() treats a numeric id as a panel-data row id, so a purely + // numeric panel_id (including forms like '1e3') would collide with another + // panel's data when polled or reloaded. + if (isset($panel['panel_id']) && is_numeric($panel['panel_id'])) { + $errors[] = "The 'panel_id' must not be purely numeric."; + } + if (isset($panel['plugin']) && !preg_match('/^[a-z0-9_]{1,64}$/i', (string) $panel['plugin'])) { $errors[] = "The 'plugin' must be the plugin directory name (letters, digits or underscores)."; } + // Keep the registration within the live panel-definition column widths so a + // published registration never overflows or truncates on write. + $lengths = [ + 'name' => 30, + 'description' => 200, + 'class' => 30, + 'update_func' => 30, + 'details_func' => 30, + 'trends_func' => 30, + 'requires' => 128, + 'width' => 20, + ]; + + foreach ($lengths as $attr => $max) { + if (isset($panel[$attr]) && strlen((string) $panel[$attr]) > $max) { + $errors[] = "The '$attr' must be $max characters or fewer."; + } + } + if (isset($panel['level']) && (int) $panel['level'] !== 0 && (int) $panel['level'] !== 1) { $errors[] = "The 'level' must be PANEL_SYSTEM (0) or PANEL_USER (1)."; } @@ -287,6 +313,40 @@ function intropage_panel_registration_exists(string $panel_id): bool { [$panel_id]) > 0; } +/** + * Detects an ownership or built-in collision for a panel id before a + * registration is written. A panel id may only be (re-)registered by the + * plugin that already owns its registration, and may never shadow a built-in + * panellib panel (a panel_definition row with no registration behind it). + * + * @param string $panel_id The panel id being registered. + * @param string $plugin The plugin claiming ownership. + * + * @return string An error message describing the conflict, or '' when none. + */ +function intropage_registration_conflict(string $panel_id, string $plugin): string { + $owner = db_fetch_cell_prepared('SELECT plugin + FROM plugin_intropage_panel_registration + WHERE panel_id = ?', + [$panel_id]); + + if (!empty($owner)) { + return ($owner === $plugin) ? '' : "Panel id '$panel_id' is already registered by plugin '$owner'."; + } + + // No registration owns the id yet: reject it if a built-in panel does. + $builtin = db_fetch_cell_prepared('SELECT COUNT(*) + FROM plugin_intropage_panel_definition + WHERE panel_id = ?', + [$panel_id]); + + if ($builtin > 0) { + return "Panel id '$panel_id' collides with a built-in Intropage panel."; + } + + return ''; +} + /** * Fetches a single registration row, decoding its request_vars JSON into an * array. @@ -375,6 +435,15 @@ function intropage_register_panel(array $panel) { $values['requires'] = $values['plugin']; } + // Never let a registration shadow a built-in panel or hijack a panel id + // another plugin already owns. + $conflict = intropage_registration_conflict($panel_id, $values['plugin']); + + if ($conflict !== '') { + cacti_log('WARNING: intropage_register_panel() rejected panel "' . $panel_id . '": ' . $conflict, false, 'INTROPAGE'); + return [$conflict]; + } + $enabled = isset($panel['enabled']) ? (filter_var($panel['enabled'], FILTER_VALIDATE_BOOLEAN) ? 1 : 0) : 1; db_execute_prepared('INSERT INTO plugin_intropage_panel_registration @@ -598,6 +667,13 @@ function intropage_apply_panel_registration(string $panel_id): void { return; } + // This API can be reached from a foreign plugin's early hook, before the + // rest of the Intropage library is loaded; make sure the persistence helper + // is available. + if (!function_exists('update_registered_panels')) { + include_once(__DIR__ . '/functions.php'); // @codeCoverageIgnore + } + $definition = intropage_registration_to_definition($row); update_registered_panels([$panel_id => $definition]); @@ -690,6 +766,8 @@ function intropage_registration_to_definition(array $row): array { * @return array Library-shaped panel definitions keyed by panel id. */ function intropage_load_registered_panels(): array { + global $registry; + $panels = []; if (!db_table_exists('plugin_intropage_panel_registration')) { @@ -711,7 +789,21 @@ function intropage_load_registered_panels(): array { intropage_include_registration_file($row); - $panels[$row['panel_id']] = intropage_registration_to_definition($row); + $definition = intropage_registration_to_definition($row); + + // The permission editors group panels by their category ('class') via + // the global $registry; register a fallback category for a registered + // panel so its heading is not blank, without overwriting a built-in one. + $class = $definition['class']; + + if (!isset($registry[$class])) { + $registry[$class] = [ + 'name' => $row['plugin'], + 'description' => $row['description'], + ]; + } + + $panels[$row['panel_id']] = $definition; } return $panels; @@ -787,6 +879,13 @@ function intropage_validate_request_vars(string $panel_id): array { $raw = get_nfilter_request_var($name); + // Declared request variables are scalar; reject array/object input + // (e.g. name[]=value) rather than coercing it to the string 'Array'. + if (!is_scalar($raw)) { + $result[$name] = $default; + continue; + } + switch ($type) { case 'integer': $value = filter_var($raw, FILTER_VALIDATE_INT); @@ -797,10 +896,15 @@ function intropage_validate_request_vars(string $panel_id): array { $result[$name] = ($value === false) ? $default : $value; break; case 'boolean': - $result[$name] = filter_var($raw, FILTER_VALIDATE_BOOLEAN); + // FILTER_VALIDATE_BOOLEAN returns false for both a valid false + // and invalid input; use FILTER_NULL_ON_FAILURE so an invalid + // value falls back to the declared default instead of false. + $value = filter_var($raw, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); + $result[$name] = ($value === null) ? $default : $value; break; case 'alphanumeric': - $result[$name] = preg_match('/^[A-Za-z0-9]+$/', (string) $raw) ? $raw : $default; + $string = (string) $raw; + $result[$name] = preg_match('/^[A-Za-z0-9]+$/', $string) ? $string : $default; break; case 'string': default: @@ -815,17 +919,14 @@ function intropage_validate_request_vars(string $panel_id): array { /** * Returns the user id used to own system-level seed data and to receive panel - * permissions, mirroring intropage_initialize_database(): the current session - * user when present, otherwise the configured admin user, falling back to the - * lowest user id. + * permissions, mirroring intropage_initialize_database(): the configured admin + * user, falling back to the lowest user id. It deliberately ignores the + * session user so a plugin registering during an ordinary user's page load + * cannot grant that user (or itself) panel permissions. * * @return int The admin user id (0 when no users exist). */ function intropage_registration_admin_user(): int { - if (isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] > 0) { - return (int) $_SESSION['sess_user_id']; - } - $user_id = read_config_option('admin_user'); if (empty($user_id)) { @@ -900,14 +1001,17 @@ function intropage_registration_remove_permissions(string $panel_id): void { } /** - * Clears the per-request panel-library snapshot stored in the session so that a - * registration change made in the same request is reflected by the next - * dashboard view. The authoritative panel tables are always written directly, - * so a stale snapshot never outlives the request. + * Invalidates the request-lifetime panel-library caches so a registration + * change made in the same request is reflected by the next + * initialize_panel_library() call: it both clears the session snapshot and + * raises a flag that initialize_panel_library() checks to discard its + * function-local static cache. * * @return void */ function intropage_registration_reset_cache(): void { + $GLOBALS['intropage_panel_library_stale'] = true; + if (isset($_SESSION['intropage_panel_library'])) { unset($_SESSION['intropage_panel_library']); } diff --git a/setup.php b/setup.php index 19b074b..d60b6e7 100644 --- a/setup.php +++ b/setup.php @@ -24,6 +24,13 @@ +-------------------------------------------------------------------------+ */ +/* Expose the third-party panel registration API (intropage_register_panel() + * et al.) as soon as this plugin's setup.php is loaded. Cacti includes every + * enabled plugin's setup.php during start-up, before plugin hooks such as + * config_arrays run, so a foreign plugin's function_exists('intropage_register_panel') + * guard succeeds no matter the hook order. */ +include_once(__DIR__ . '/includes/registration.php'); + /** * Return the CSP nonce attribute for inline + + + $items) { + $menu2[$section] = $items; + + if ($section == __('Management')) { + $menu2[__('Intropage', 'intropage')]['plugins/intropage/intropage_panels.php'] = __('Panel Library', 'intropage'); + } + } + + // If there was no Management section to anchor to, append our own. + if (!isset($menu2[__('Intropage', 'intropage')])) { + $menu2[__('Intropage', 'intropage')]['plugins/intropage/intropage_panels.php'] = __('Panel Library', 'intropage'); + } + + $menu = $menu2; + + if (is_array($menu_glyphs)) { + $menu_glyphs[__('Intropage', 'intropage')] = 'fa fa-th-large'; + } + } + // Core builds $user_auth_roles with __('Normal User') in the core domain // (include/global_arrays.php), and auth_augment_roles() indexes by that // exact string. Adding the intropage domain here would key a new role on @@ -239,6 +268,32 @@ function intropage_config_arrays(): void { } } +/** + * Adds the Panel Library management page to the Cacti navigation + * (breadcrumb) registry. Registered as the 'draw_navigation_text' hook. + * + * @param array $nav The navigation array provided by Cacti. + * + * @return array The navigation array with the Panel Library pages added. + */ +function intropage_draw_navigation_text($nav) { + $nav['intropage_panels.php:'] = [ + 'title' => __('Intropage Panel Library', 'intropage'), + 'mapping' => 'index.php:', + 'url' => 'intropage_panels.php', + 'level' => '1' + ]; + + $nav['intropage_panels.php:actions'] = [ + 'title' => __('Actions', 'intropage'), + 'mapping' => 'index.php:,intropage_panels.php:', + 'url' => 'intropage_panels.php', + 'level' => '2' + ]; + + return $nav; +} + /** * Reads and returns this plugin's version/author/metadata info from its * INFO file. Called wherever plugin metadata is needed (e.g. diff --git a/tests/Integration/IntropageInstallHooksTest.php b/tests/Integration/IntropageInstallHooksTest.php index 4f8c355..d8e5360 100644 --- a/tests/Integration/IntropageInstallHooksTest.php +++ b/tests/Integration/IntropageInstallHooksTest.php @@ -30,7 +30,7 @@ $hooks[$registered['hook']] = $registered; } - foreach (array('config_settings', 'config_arrays', 'login_options_navigate', 'top_header_tabs', 'top_graph_header_tabs', 'console_after', 'page_head', 'graph_buttons', 'poller_bottom', 'user_remove', 'user_group_remove') as $expected) { + foreach (array('config_settings', 'config_arrays', 'login_options_navigate', 'top_header_tabs', 'top_graph_header_tabs', 'console_after', 'page_head', 'draw_navigation_text', 'graph_buttons', 'poller_bottom', 'user_remove', 'user_group_remove') as $expected) { expect($hooks)->toHaveKey($expected); expect($hooks[$expected]['name'])->toBe('intropage'); } @@ -39,4 +39,5 @@ expect($realms)->toContain('intropage.php'); expect($realms)->toContain('intropage_admin.php'); + expect($realms)->toContain('intropage_panels.php'); }); diff --git a/tests/Unit/IntropageConfigArraysTest.php b/tests/Unit/IntropageConfigArraysTest.php index e9a7cae..7a34285 100644 --- a/tests/Unit/IntropageConfigArraysTest.php +++ b/tests/Unit/IntropageConfigArraysTest.php @@ -18,6 +18,10 @@ beforeEach(function () { $GLOBALS['__test_augmented_roles'] = array(); $GLOBALS['__test_config'] = array(); + $GLOBALS['__test_realms'] = array(); + global $menu, $menu_glyphs; + $menu = array(); + $menu_glyphs = array(); }); it('augments the Normal User and System Administration roles', function () { @@ -50,3 +54,45 @@ expect($intropage_intervals)->toHaveKey('300'); expect($intropage_intervals)->toHaveKey('3600'); }); + +it('adds the Panel Library menu after Management for an authorized user', function () { + global $menu; + + $GLOBALS['__test_realms']['intropage_panels.php'] = true; + $menu = [__('Management') => ['host.php' => __('Devices')]]; + + intropage_config_arrays(); + + expect($menu)->toHaveKey(__('Intropage', 'intropage')); + expect($menu[__('Intropage', 'intropage')])->toHaveKey('plugins/intropage/intropage_panels.php'); +}); + +it('appends the Panel Library menu when there is no Management section', function () { + global $menu; + + $GLOBALS['__test_realms']['intropage_panels.php'] = true; + $menu = ['Create' => ['x.php' => 'X']]; + + intropage_config_arrays(); + + expect($menu)->toHaveKey(__('Intropage', 'intropage')); +}); + +it('does not add the Panel Library menu without the realm', function () { + global $menu; + + $GLOBALS['__test_realms']['intropage_panels.php'] = false; + $menu = [__('Management') => ['host.php' => __('Devices')]]; + + intropage_config_arrays(); + + expect($menu)->not->toHaveKey(__('Intropage', 'intropage')); +}); + +it('adds the Panel Library pages to the navigation', function () { + $nav = intropage_draw_navigation_text([]); + + expect($nav)->toHaveKey('intropage_panels.php:'); + expect($nav['intropage_panels.php:']['url'])->toBe('intropage_panels.php'); + expect($nav)->toHaveKey('intropage_panels.php:actions'); +}); diff --git a/tests/Unit/IntropageRegistrationApiTest.php b/tests/Unit/IntropageRegistrationApiTest.php index 9dfaee3..97c365b 100644 --- a/tests/Unit/IntropageRegistrationApiTest.php +++ b/tests/Unit/IntropageRegistrationApiTest.php @@ -76,6 +76,15 @@ function intropage_reg_router(string $kind, string $sql, array $params) { if ($has('plugin_intropage_user_auth') && $has('permissions')) { return $r['perm_rows_user']; } + if ($has('SELECT panel_id, plugin')) { + return $r['source_rows']; + } + if ($has('WHERE enabled = 0')) { + return $r['disabled_rows']; + } + if ($has("plugin = 'intropage'") && $has('include_file = ?')) { + return $r['core_file_rows']; + } if ($has('WHERE plugin')) { return $r['rows_by_plugin']; } @@ -138,7 +147,7 @@ function intropage_reg_input(array $overrides = array()): array { $_REQUEST = array(); $GLOBALS['__test_request'] = array(); $GLOBALS['registry'] = array(); - unset($GLOBALS['intropage_panel_library_stale']); + unset($GLOBALS['intropage_panel_library_stale'], $GLOBALS['intropage_panel_sources'], $GLOBALS['intropage_disabled_panels']); $GLOBALS['__reg'] = array( 'plugin_present' => true, @@ -157,6 +166,9 @@ function intropage_reg_input(array $overrides = array()): array { 'perm_rows_user' => array(), 'perm_rows_group' => array(), 'fallback_uid' => '0', + 'source_rows' => array(), + 'disabled_rows' => array(), + 'core_file_rows' => array(), ); }); @@ -699,3 +711,146 @@ function intropage_reg_writes(string $needle): array { expect($merged)->toBe(array('builtin' => array('name' => 'Built-in'))); }); + +/* ---- source prefixing (Core - / Plugin -) ---- */ + +it('builds a source prefix for core and third-party plugins', function () { + expect(intropage_source_prefix(''))->toBe(''); + expect(intropage_source_prefix('intropage'))->toBe('Core - '); + expect(intropage_source_prefix('my_plugin'))->toBe('My Plugin - '); +}); + +it('prefixes panel names by their recorded source', function () { + $GLOBALS['__reg']['source_rows'] = array( + array('panel_id' => 'poller_info', 'plugin' => 'intropage'), + array('panel_id' => 'ext_panel', 'plugin' => 'my_plugin'), + ); + + expect(intropage_prefix_panel_name('poller_info', 'Poller Information'))->toBe('Core - Poller Information'); + expect(intropage_prefix_panel_name('ext_panel', 'Ext'))->toBe('My Plugin - Ext'); + + // Unknown panel, empty name and an already-prefixed name are left as-is. + expect(intropage_prefix_panel_name('unknown', 'X'))->toBe('X'); + expect(intropage_prefix_panel_name('poller_info', ''))->toBe(''); + expect(intropage_prefix_panel_name('poller_info', 'Core - Poller Information'))->toBe('Core - Poller Information'); +}); + +it('returns no sources or prefix when the registration table is absent', function () { + $GLOBALS['__test_tables'] = array(); + + expect(intropage_panel_sources())->toBe(array()); + expect(intropage_prefix_panel_name('poller_info', 'Name'))->toBe('Name'); +}); + +/* ---- disabled panels ---- */ + +it('lists disabled panel ids from the registration table', function () { + $GLOBALS['__reg']['disabled_rows'] = array(array('panel_id' => 'a'), array('panel_id' => 'b')); + + expect(intropage_disabled_panel_ids())->toBe(array('a', 'b')); +}); + +it('returns no disabled ids when the registration table is absent', function () { + $GLOBALS['__test_tables'] = array(); + + expect(intropage_disabled_panel_ids())->toBe(array()); +}); + +it('toggles a panel enabled flag', function () { + $GLOBALS['__reg']['exists'] = true; + + expect(intropage_set_panel_enabled('demo_panel', false))->toBeTrue(); + + $updates = intropage_reg_writes('UPDATE plugin_intropage_panel_registration'); + + expect($updates)->toHaveCount(1); + expect($updates[0]['sql'])->toContain('SET enabled = ?'); + expect($updates[0]['params'][0])->toBe(0); + + $GLOBALS['__reg']['exists'] = false; + expect(intropage_set_panel_enabled('nope', true))->toBeFalse(); +}); + +it('excludes disabled panels from the panel library', function () { + $GLOBALS['__reg']['disabled_rows'] = array(array('panel_id' => 'poller_info')); + $GLOBALS['intropage_panel_library_stale'] = true; + + $library = initialize_panel_library(); + + expect($library)->not->toHaveKey('poller_info'); + expect($library)->toHaveKey('poller_stat'); +}); + +it('lets Intropage adopt a built-in id that a foreign plugin may not', function () { + $GLOBALS['__reg']['owner'] = ''; + $GLOBALS['__reg']['builtin'] = '1'; + + expect(intropage_registration_conflict('poller_info', 'intropage'))->toBe(''); + expect(intropage_registration_conflict('poller_info', 'other'))->toContain('built-in'); +}); + +/* ---- panellib -> registration-table sync ---- */ + +it('does not sync when the registration table is absent', function () { + $GLOBALS['__test_tables'] = array(); + + expect(intropage_sync_core_registrations())->toBe(0); +}); + +it('skips the sync when no panellib file changed', function () { + $dir = $GLOBALS['config']['base_path'] . '/plugins/intropage/panellib'; + $current = array(); + + foreach (glob($dir . '/*.php') as $file) { + if (basename($file) === 'index.php') { + continue; + } + + $current[basename($file)] = filemtime($file); + } + + $GLOBALS['__test_config']['intropage_panellib_mtimes'] = json_encode($current); + + expect(intropage_sync_core_registrations(false))->toBe(0); +}); + +it('re-registers the built-in panels as core when forced', function () { + $n = intropage_sync_core_registrations(true); + + expect($n)->toBeGreaterThanOrEqual(1); + + $inserts = array_filter($GLOBALS['__test_db_calls'], static fn ($c) => strpos($c['sql'], 'INSERT INTO plugin_intropage_panel_registration') !== false); + + expect(count($inserts))->toBeGreaterThanOrEqual(1); + + // Core panels are stored under the reserved 'intropage' owner. + $first = array_values($inserts)[0]; + expect($first['params'][1])->toBe('intropage'); +}); + +it('withdraws core panels sourced from a deleted panellib file', function () { + $dir = $GLOBALS['config']['base_path'] . '/plugins/intropage/panellib'; + $current = array(); + + foreach (glob($dir . '/*.php') as $file) { + if (basename($file) === 'index.php') { + continue; + } + + $current[basename($file)] = filemtime($file); + } + + // Pretend a file that no longer exists was present at the last sync. + $stored = $current; + $stored['ghost.php'] = 1; + + $GLOBALS['__test_config']['intropage_panellib_mtimes'] = json_encode($stored); + + $GLOBALS['__reg']['exists'] = true; + $GLOBALS['__reg']['core_file_rows'] = array(array('panel_id' => 'ghost_panel')); + + $removed = intropage_sync_core_registrations(false); + + expect($removed)->toBeGreaterThanOrEqual(1); + expect(intropage_reg_writes('DELETE FROM plugin_intropage_panel_registration'))->toHaveCount(1); +}); diff --git a/tests/bin/patch-coverage.php b/tests/bin/patch-coverage.php index 9fdee5c..3c8ef3b 100644 --- a/tests/bin/patch-coverage.php +++ b/tests/bin/patch-coverage.php @@ -168,6 +168,10 @@ function changed_lines($base_ref) { // isolated unit process. 'display.php', 'poller_intropage.php', + // Panel Library management page: a Console web entry point (chdir + include + // auth.php, top-level dispatch + header() redirects) not reachable from the + // isolated unit process; its testable logic lives in includes/registration.php. + 'intropage_panels.php', // Directory-index redirect stub (header('Location:...') + top-level // execution); added with the new js/ asset directory and not reachable from // the isolated unit process. Matches the other per-directory index.php stubs. From 68294ee49c9f62e0a3801f20c352e3189d664093 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Wed, 11 Nov 2026 13:42:45 -0500 Subject: [PATCH 08/10] test: cover sync_core_file withdraw and missing-register-function paths Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/Unit/IntropageRegistrationApiTest.php | 31 +++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/tests/Unit/IntropageRegistrationApiTest.php b/tests/Unit/IntropageRegistrationApiTest.php index 97c365b..5f6bd00 100644 --- a/tests/Unit/IntropageRegistrationApiTest.php +++ b/tests/Unit/IntropageRegistrationApiTest.php @@ -854,3 +854,34 @@ function intropage_reg_writes(string $needle): array { expect($removed)->toBeGreaterThanOrEqual(1); expect(intropage_reg_writes('DELETE FROM plugin_intropage_panel_registration'))->toHaveCount(1); }); + +it('withdraws a core panel a panellib file no longer declares', function () { + $dir = sys_get_temp_dir() . '/introsync-' . bin2hex(random_bytes(5)); + mkdir($dir, 0777, true); + file_put_contents($dir . '/synctest.php', " array('name' => 'Kept', 'update_func' => 'u')); }\n"); + + $GLOBALS['__reg']['exists'] = true; + $GLOBALS['__reg']['core_file_rows'] = array(array('panel_id' => 'old_panel'), array('panel_id' => 'kept_panel')); + + intropage_sync_core_file($dir . '/synctest.php'); + + // kept_panel is upserted; old_panel (no longer declared) is withdrawn. + expect(intropage_reg_writes('INSERT INTO plugin_intropage_panel_registration'))->toHaveCount(1); + expect(intropage_reg_writes('DELETE FROM plugin_intropage_panel_registration'))->toHaveCount(1); + + @unlink($dir . '/synctest.php'); + @rmdir($dir); +}); + +it('returns early for a panellib file without a register function', function () { + $dir = sys_get_temp_dir() . '/introsync2-' . bin2hex(random_bytes(5)); + mkdir($dir, 0777, true); + file_put_contents($dir . '/noreg.php', "toBe(array()); + + @unlink($dir . '/noreg.php'); + @rmdir($dir); +}); From 56a881aadbfd831562951596571004c2edfa28ac Mon Sep 17 00:00:00 2001 From: TheWitness Date: Wed, 11 Nov 2026 13:47:29 -0500 Subject: [PATCH 09/10] a11y: associate labels with the Panel Library filter inputs SonarCloud flagged the search, source and rows filter controls as inputs without an associated label (Web:InputWithoutLabelCheck). Wrap each filter caption in a