diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 877b36e..5c51701 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -4,7 +4,7 @@ When generating code for this repository: -1. **Version Compatibility**: This is a Cacti plugin (`intropage`, "Intropage/Dashboard", version 4.0.5) targeting Cacti 1.2.17+ +1. **Version Compatibility**: This is a Cacti plugin (`intropage`, "Intropage/Dashboard", version 4.0.5) targeting Cacti 1.2.29+ 2. **Context Files**: Prioritize patterns and standards defined in this file (`.github/copilot-instructions.md`) 3. **Codebase Patterns**: When context files don't provide specific guidance, scan the codebase for established patterns 4. **Architectural Consistency**: Maintain plugin-based architecture extending Cacti core diff --git a/CHANGELOG.md b/CHANGELOG.md index 9af3c98..83330ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ --- develop --- +* dev: Raise the minimum supported Cacti version (the `compat` value in `INFO`) from 1.2.17 to 1.2.29 +* 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` +* feature: Add a Panel Library management page (Console > Intropage Panels) that lists every registered panel in a filterable table with a source-plugin dropdown and Enable/Disable bulk actions, backed by the poller keeping the registration table in sync with the `panellib/` directory on file change +* dev: Sync the built-in `panellib/` panels into the `plugin_intropage_panel_registration` table from the poller whenever a panel file's mtime changes, so the panel library is read from the table instead of being rebuilt from disk on every request +* dev: Prefix panel titles by their source in the UI (`Core -` for Intropage's own panels, `Plugin Name -` in title case for panels registered by other plugins) +* 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#471: Do not return a phantom empty row when tailing newline-terminated log files; return no rows for empty files * dev: Relocate the shared dashboard card chrome to the standard `js/cards.js` + `css/cards.css` plugin asset paths (from `includes/cards/`) and move the plugin's `intropage.js` to `js/intropage.js`, so all JavaScript lives under `js/`, every plugin that adopts the card interface uses an identical file layout, and the bundle can be promoted to Cacti core unchanged * dev: Load the shared card chrome from Cacti core on 1.2.32+ (`include/js/cards.js` + `include/css/cards.css`) and only bundle the plugin's own copy on older cores diff --git a/INFO b/INFO index 160118b..a915b3c 100644 --- a/INFO +++ b/INFO @@ -21,10 +21,10 @@ [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 homepage = https://github.com/cacti/plugin_intropage -compat = 1.2.17 +compat = 1.2.29 capabilities = online_view:1, online_mgmt:1, offline_view:0, offline_mgmt:0, remote_collect:0 diff --git a/README.md b/README.md index 0953e27..66b0505 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ screenshots and tests. ## Requirements -- Cacti 1.2.17 or later (the `compat` value in the `INFO` file). The plugin is +- Cacti 1.2.29 or later (the `compat` value in the `INFO` file). The plugin is tested in CI against the 1.2.x branch of Cacti, and it installs, enables and runs its poller script on the Cacti development branch (1.3). - PHP 8.0 or later for the plugin code. The Cacti release you run decides @@ -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,237 @@ 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. 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()`. +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_]`, 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 (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. | +| `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. + +### The registration table is the single panel catalog + +The `plugin_intropage_panel_registration` table holds **every** panel — the +built-in `panellib/` panels as well as third-party ones. Built-in panels are +owned by the reserved `intropage` plugin name and are kept in sync +automatically: on each poller cycle `intropage_sync_core_registrations()` +compares every `panellib/*.php` file's modification time against the last sync +and, when a file has changed (or is new or removed), re-runs that file's +`register_()` function and upserts its panels into the table. This +means the panel catalog is read from the table instead of being rebuilt from +disk on every web request; editing a panellib file is picked up on the next +poller run without any manual "Reload Panel Definitions". + +### Panel source prefixes + +Panel titles are prefixed by their source wherever they are shown (dashboard +cards and the detail dialog): Intropage's own panels are prefixed `Core - `, +and panels registered by another plugin are prefixed with the plugin's name in +title case, e.g. `Mactrack - `. The prefix is derived from the owning plugin +recorded in the registration table. + +### Panel Library management page + +**Console > Intropage > Panel Library** (`intropage_panels.php`, guarded by the +*Intropage Panel Library* realm) lists every registered panel in a filterable, +sortable table with a free-text search, a **Source** dropdown (filter by the +providing plugin, with Intropage shown as *Core*) and **Enable**/**Disable** +bulk actions. Disabling a panel is non-destructive: it is hidden from +dashboards and skipped by the poller, but its stored data and dashboard +placements are retained, so re-enabling restores it unchanged. The columns are +Panel Name, Source, Category, Level (System/User), Requires, Refresh, Update +Function and Status. + +### 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 d4812b3..4181825 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(); @@ -534,7 +538,15 @@ function display_information(): bool { } // end of admin panel + $disabled_panels = intropage_disabled_panel_ids(); + foreach ($panels as $xkey => $xvalue) { + // Skip panels an administrator has disabled on the Panel Library + // management page; their data is retained but they are not rendered. + if (in_array($xvalue['panel_id'], $disabled_panels, true)) { + continue; + } + intropage_create_panel($xvalue['id'], $dashboard_id); } diff --git a/includes/database.php b/includes/database.php index fb8f420..b16c226 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(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]; + $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(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]; + $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,13 @@ 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(); + + // Seed the registration catalog with the built-in panellib panels so the + // Panel Library management page and source prefixes work before the first + // poller cycle runs. + intropage_sync_core_registrations(true); } /** @@ -292,7 +340,7 @@ function intropage_upgrade_database(): void { case 'permissions': break; default: - // db_is_safe_identifier() postdates the 1.2.17 baseline in INFO. + // db_is_safe_identifier() postdates the 1.2.29 baseline in INFO. $safe = function_exists('db_is_safe_identifier') ? db_is_safe_identifier($c['Field']) : preg_match('/^[A-Za-z0-9_]+$/', (string) $c['Field']) === 1; @@ -378,6 +426,20 @@ 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(); + } + + // Populate the catalog with the built-in panellib panels on upgrade. + intropage_sync_core_registrations(true); + + // Register the new Panel Library management page's realm and its + // navigation hook on existing installs. + api_plugin_register_realm('intropage', 'intropage_panels.php', 'Intropage Panel Library', 1); + api_plugin_register_hook('intropage', 'draw_navigation_text', 'intropage_draw_navigation_text', 'setup.php', true); + } + // 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 0c16c23..9947dd2 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; } @@ -1175,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'); } @@ -1296,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'] . '
'; @@ -1415,6 +1431,11 @@ function get_panel($panel_id, int $user_id = 0): array { $definition['height'] = 'normal'; } + // Prefix the title with its source ("Core -" / "Plugin -") so every place + // that renders the definition name (dashboard cards, detail dialog) shows + // where the panel came from. + $definition['name'] = intropage_prefix_panel_name((string) $panel_id, (string) $definition['name']); + if (is_array($panel) && cacti_sizeof($panel)) { $last_update = $panel['ts']; $refresh_interval = $panel['refresh_interval']; @@ -1725,6 +1746,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 = []; @@ -1744,6 +1772,10 @@ function initialize_panel_library(): array { // Check to see if the panel should be activated foreach ($base_panels as $panel_id => $p) { + // Tag built-in panels with the reserved 'intropage' + // owner so their titles are prefixed "Core -". + $base_panels[$panel_id]['plugin'] = 'intropage'; + if (isset($p['requires']) && $p['requires'] !== false) { $plugins = explode(',', $p['requires']); @@ -1768,38 +1800,85 @@ 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]); + // Handle panels whose required plugin is no longer installed. + intropage_unregister_missing_panels($uninstall); - if ($id > 0) { - db_execute_prepared('DELETE FROM plugin_intropage_panel_dashboard - WHERE panel_id = ?', - [$id]); + // 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. + $panel_library = intropage_merge_registered_panels($panels); - db_execute_prepared('DELETE FROM plugin_intropage_panel_data - WHERE id = ?', - [$id]); - - db_execute_prepared('DELETE FROM plugin_intropage_definition - WHERE panel_id = ?', - [$panel_id]); - } - } + // Drop panels an administrator has disabled on the Panel Library + // management page (core or third-party), so they are hidden from + // dashboards, the panel picker and the poller without deleting data. + foreach (intropage_disabled_panel_ids() as $disabled_id) { + unset($panel_library[$disabled_id]); } - $panel_library = $panels; - $_SESSION['intropage_panel_library'] = $panel_library; } 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/includes/registration.php b/includes/registration.php new file mode 100644 index 0000000..4277916 --- /dev/null +++ b/includes/registration.php @@ -0,0 +1,1352 @@ + 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."; + } + + // 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)."; + } + + 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; +} + +/** + * 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. Intropage's own built-in panels + * are owned by the reserved `intropage` plugin name, so a foreign plugin may + * never shadow a built-in panellib panel, while Intropage itself is allowed to + * (re-)register its built-ins through the core sync. + * + * @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'."; + } + + // Intropage owns its built-ins; only a foreign plugin is blocked from + // shadowing a built-in panellib panel that has no registration row yet. + if ($plugin === 'intropage') { + return ''; + } + + $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. + * + * @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']; + } + + // 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 + (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; + } + + // 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]); + + $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'], + 'plugin' => $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 { + global $registry; + + $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); + + $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; +} + +/** + * 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); + + // 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); + $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': + // 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': + $string = (string) $raw; + $result[$name] = preg_match('/^[A-Za-z0-9]+$/', $string) ? $string : $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 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 { + $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]]); + } + } + } +} + +/** + * 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; + + unset($GLOBALS['intropage_panel_sources'], $GLOBALS['intropage_disabled_panels']); + + if (isset($_SESSION['intropage_panel_library'])) { + unset($_SESSION['intropage_panel_library']); + } +} + +/** + * Returns the display prefix for a panel's source plugin: "Core - " for + * Intropage's own built-in panels (the reserved `intropage` plugin name), and + * the title-cased plugin name followed by " - " for panels registered by any + * other plugin. + * + * @param string $plugin The owning plugin directory name. + * + * @return string The display prefix (including the trailing " - "), or '' when + * no plugin is known. + */ +function intropage_source_prefix(string $plugin): string { + if ($plugin === '') { + return ''; + } + + if ($plugin === 'intropage') { + return __('Core', 'intropage') . ' - '; + } + + return ucwords(str_replace(['_', '-'], ' ', $plugin)) . ' - '; +} + +/** + * Builds (and request-caches) a map of panel id to owning plugin from the + * registration table, used to prefix panel titles by their source. + * + * @return array Map of panel_id => plugin directory name. + */ +function intropage_panel_sources(): array { + if (!isset($GLOBALS['intropage_panel_sources'])) { + $map = []; + + if (db_table_exists('plugin_intropage_panel_registration')) { + foreach (db_fetch_assoc('SELECT panel_id, plugin FROM plugin_intropage_panel_registration') as $row) { + $map[$row['panel_id']] = $row['plugin']; + } + } + + $GLOBALS['intropage_panel_sources'] = $map; + } + + return $GLOBALS['intropage_panel_sources']; +} + +/** + * Prefixes a panel's title with its source ("Core - " / "Plugin - ") based on + * the owning plugin recorded in the registration table. Panels without a + * registration row (e.g. the favourite-graph pseudo-panel) and empty names are + * returned unchanged, and an already-prefixed name is not prefixed twice. + * + * @param string $panel_id The panel id whose source to resolve. + * @param string $name The panel's base title. + * + * @return string The prefixed title. + */ +function intropage_prefix_panel_name(string $panel_id, string $name): string { + if ($name === '') { + return $name; + } + + $sources = intropage_panel_sources(); + + if (!isset($sources[$panel_id])) { + return $name; + } + + $prefix = intropage_source_prefix($sources[$panel_id]); + + if ($prefix !== '' && strpos($name, $prefix) === 0) { + return $name; + } + + return $prefix . $name; +} + +/** + * Returns (and request-caches) the set of panel ids an administrator has + * disabled in the registration table. Disabled panels are excluded from the + * live panel library and from dashboards without deleting their stored data. + * + * @return array A list of disabled panel ids. + */ +function intropage_disabled_panel_ids(): array { + if (!isset($GLOBALS['intropage_disabled_panels'])) { + $ids = []; + + if (db_table_exists('plugin_intropage_panel_registration')) { + $ids = array_column(db_fetch_assoc('SELECT panel_id + FROM plugin_intropage_panel_registration + WHERE enabled = 0'), 'panel_id'); + } + + $GLOBALS['intropage_disabled_panels'] = $ids; + } + + return $GLOBALS['intropage_disabled_panels']; +} + +/** + * Enables or disables a panel registration (core or third-party) by setting + * its `enabled` flag, and invalidates the panel-library caches. Disabling is + * non-destructive: the panel is hidden from dashboards and skipped by the + * poller, but its stored data and dashboard placements are retained so it + * reappears unchanged when re-enabled. Called from the Panel Library + * management page's bulk Enable/Disable actions. + * + * @param string $panel_id The registered panel id to toggle. + * @param bool $enabled True to enable, false to disable. + * + * @return bool True when a registration row was updated. + */ +function intropage_set_panel_enabled(string $panel_id, bool $enabled): bool { + if (!intropage_panel_registration_exists($panel_id)) { + return false; + } + + db_execute_prepared('UPDATE plugin_intropage_panel_registration + SET enabled = ?, last_updated = NOW() + WHERE panel_id = ?', + [$enabled ? 1 : 0, $panel_id]); + + intropage_registration_reset_cache(); + + return true; +} + +/** + * Synchronizes the built-in panellib panels into the registration table so the + * table is the single catalog of every panel (core and third-party). It stats + * each panellib/*.php file and, when any file's mtime has changed since the + * last sync (or when forced), re-runs that file's register_() + * function and upserts its panels as Intropage-owned ("intropage") core + * registrations; panels removed from a file, and panels from deleted files, + * are withdrawn. The per-file mtimes are stored in the + * `intropage_panellib_mtimes` setting. Intended to be called from the poller + * (every cycle, cheap when nothing changed) and at install/upgrade time. + * + * @param bool $force When true, re-register every file regardless of mtime. + * + * @return int The number of panellib files (re-)synchronized. + * + * @global array $config Cacti global configuration array; used to locate the + * panellib directory. + * @global array $registry Populated by each panellib file's register function. + */ +function intropage_sync_core_registrations(bool $force = false): int { + global $config, $registry; + + if (!db_table_exists('plugin_intropage_panel_registration')) { + return 0; + } + + $dir = $config['base_path'] . '/plugins/intropage/panellib'; + $files = glob($dir . '/*.php') ?: []; + + $current = []; + + foreach ($files as $file) { + if (basename($file) === 'index.php') { + continue; + } + + $mtime = @filemtime($file); + + if ($mtime !== false) { + $current[basename($file)] = $mtime; + } + } + + $stored = json_decode((string) read_config_option('intropage_panellib_mtimes'), true); + + if (!is_array($stored)) { + $stored = []; + } + + if (!$force && $current == $stored) { + return 0; + } + + $synced = 0; + + // Re-register every file whose mtime changed or that is new. + foreach ($current as $basename => $mtime) { + if (!$force && isset($stored[$basename]) && $stored[$basename] == $mtime) { + continue; + } + + intropage_sync_core_file($dir . '/' . $basename); + $synced++; + } + + // Withdraw core panels that came from files which no longer exist. + foreach ($stored as $basename => $mtime) { + if (!isset($current[$basename])) { + $relative = 'plugins/intropage/panellib/' . $basename; + + foreach (db_fetch_assoc_prepared("SELECT panel_id + FROM plugin_intropage_panel_registration + WHERE plugin = 'intropage' AND include_file = ?", + [$relative]) as $row) { + intropage_unregister_panel($row['panel_id']); + } + + $synced++; + } + } + + set_config_option('intropage_panellib_mtimes', json_encode($current)); + + intropage_registration_reset_cache(); + + return $synced; +} + +/** + * Re-registers every panel a single panellib file declares as Intropage-owned + * core registrations, and withdraws any core panel previously sourced from the + * same file that the file no longer declares. Helper for + * intropage_sync_core_registrations(). + * + * @param string $file Absolute path of the panellib file to synchronize. + * + * @return void + * + * @global array $registry Populated by the file's register function. + */ +function intropage_sync_core_file(string $file): void { + global $registry; + + $basename = str_replace('.php', '', basename($file)); + $relative = 'plugins/intropage/panellib/' . basename($file); + + include_once($file); + + $function = 'register_' . $basename; + + if (!function_exists($function)) { + return; + } + + $panels = call_user_func($function); + $defined = []; + + if (is_array($panels)) { + foreach ($panels as $panel_id => $def) { + $defined[] = $panel_id; + intropage_upsert_core_panel((string) $panel_id, $def, $relative); + } + } + + // Withdraw core panels this file used to declare but no longer does. + $existing = db_fetch_assoc_prepared("SELECT panel_id + FROM plugin_intropage_panel_registration + WHERE plugin = 'intropage' AND include_file = ?", + [$relative]); + + foreach ($existing as $row) { + if (!in_array($row['panel_id'], $defined, true)) { + intropage_unregister_panel($row['panel_id']); + } + } +} + +/** + * Upserts a single built-in panellib panel into the registration table as an + * Intropage-owned ("intropage") core registration. The panel's `enabled` flag + * is preserved across syncs (only defaulted to enabled on first insert), so an + * administrator's Disable survives a panellib file change. Helper for + * intropage_sync_core_file(). + * + * @param string $panel_id The built-in panel id. + * @param array $def The panel definition returned by the file's + * register_() function. + * @param string $file The panellib file path (relative to the Cacti base), + * recorded as the registration's include_file. + * + * @return void + */ +function intropage_upsert_core_panel(string $panel_id, array $def, string $file): void { + $level = $def['level'] ?? (defined('PANEL_USER') ? PANEL_USER : 1); + + $requires = $def['requires'] ?? false; + $requires = ($requires === false || $requires === null) ? '' : (string) $requires; + + $values = [ + $panel_id, + 'intropage', + (string) ($def['name'] ?? $panel_id), + (string) ($def['description'] ?? ''), + (string) ($def['class'] ?? ''), + (int) $level, + (int) ($def['priority'] ?? 50), + (string) ($def['alarm'] ?? 'grey'), + (string) ($def['width'] ?? 'quarter-panel'), + (string) ($def['height'] ?? 'normal'), + !empty($def['height_fixed']) ? 1 : 0, + !empty($def['force']) ? 1 : 0, + $requires, + $file, + (string) ($def['update_func'] ?? ''), + !empty($def['details_func']) ? (string) $def['details_func'] : '', + !empty($def['trends_func']) ? (string) $def['trends_func'] : '', + (int) ($def['refresh'] ?? 3600), + (int) ($def['trefresh'] ?? 3600), + json_encode([]), + ]; + + 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 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), last_updated=NOW()', + $values); +} diff --git a/intropage_panels.php b/intropage_panels.php new file mode 100644 index 0000000..7e994e2 --- /dev/null +++ b/intropage_panels.php @@ -0,0 +1,429 @@ + __('Enable', 'intropage'), + 2 => __('Disable', 'intropage'), +]; + +set_default_action(); + +switch (get_request_var('action')) { + case 'actions': + intropage_panels_form_actions(); + + break; + default: + top_header(); + + intropage_panels(); + + bottom_footer(); + + break; +} + +/** + * Processes the Enable/Disable bulk action submitted from the panel library + * list: validates the selected panel ids and toggles each panel's registration + * `enabled` flag, then returns to the list. + * + * @return void + * + * @global array $panel_actions The action dropdown map (Enable/Disable). + */ +function intropage_panels_form_actions(): void { + global $panel_actions; + + if (!api_user_realm_auth('intropage_panels.php')) { + raise_message('intropage_permissions', __('Intropage - Permission Denied', 'intropage'), MESSAGE_LEVEL_ERROR); + header('Location: intropage_panels.php?header=false'); + + exit; + } + + if (isset_request_var('selected_items')) { + $selected_items = json_decode(get_nfilter_request_var('selected_items'), true); + + if (is_array($selected_items)) { + $enable = (get_nfilter_request_var('drp_action') == '1'); + + foreach ($selected_items as $panel_id) { + // Panel ids are validated on registration to [A-Za-z0-9_]; re-check here. + if (is_string($panel_id) && preg_match('/^[A-Za-z0-9_]{1,50}$/', $panel_id)) { + intropage_set_panel_enabled($panel_id, $enable); + } + } + } + + header('Location: intropage_panels.php?header=false'); + + exit; + } + + /* collect the panels selected on the previous page */ + $panel_list = ''; + $panel_array = []; + + foreach ($_POST as $var => $val) { + if (preg_match('/^chk_([a-z0-9_]+)$/i', $var, $matches)) { + $panel_id = $matches[1]; + + $name = db_fetch_cell_prepared('SELECT name + FROM plugin_intropage_panel_registration + WHERE panel_id = ?', + [$panel_id]); + + $panel_list .= '
  • ' . html_escape(intropage_prefix_panel_name($panel_id, (string) $name)) . '
  • '; + $panel_array[] = $panel_id; + } + } + + top_header(); + + form_start('intropage_panels.php'); + + html_start_box($panel_actions[get_nfilter_request_var('drp_action')] ?? __('Panels', 'intropage'), '60%', '', '3', 'center', ''); + + if (cacti_sizeof($panel_array)) { + if (get_nfilter_request_var('drp_action') == '1') { + $message = __n('Click \'Continue\' to Enable the following Panel.', 'Click \'Continue\' to Enable the following Panels.', cacti_sizeof($panel_array), 'intropage'); + $title = __('Enable Panel', 'intropage'); + } else { + $message = __n('Click \'Continue\' to Disable the following Panel. Disabled panels are hidden from dashboards and skipped by the poller, but their data is retained.', 'Click \'Continue\' to Disable the following Panels. Disabled panels are hidden from dashboards and skipped by the poller, but their data is retained.', cacti_sizeof($panel_array), 'intropage'); + $title = __('Disable Panel', 'intropage'); + } + + print "

    $message

      $panel_list
    "; + + $save_html = " "; + } else { + raise_message(40); + header('Location: intropage_panels.php?header=false'); + + exit; + } + + print " + + + + $save_html + "; + + html_end_box(); + + form_end(); + + bottom_footer(); +} + +/** + * Renders the Panel Library management page: a filterable, sortable table of + * every registered panel (core and third-party) with a source-plugin dropdown + * filter and Enable/Disable bulk actions. + * + * @return void + * + * @global array $panel_actions The action dropdown map (Enable/Disable). + */ +function intropage_panels(): void { + global $panel_actions; + + if (!api_user_realm_auth('intropage_panels.php')) { + raise_message('intropage_permissions', __('Intropage - Permission Denied', 'intropage'), MESSAGE_LEVEL_ERROR); + + return; + } + + $filters = [ + 'rows' => [ + 'filter' => FILTER_VALIDATE_INT, + 'pageset' => true, + 'default' => '-1', + ], + 'page' => [ + 'filter' => FILTER_VALIDATE_INT, + 'default' => '1', + ], + 'filter' => [ + 'filter' => FILTER_DEFAULT, + 'pageset' => true, + 'default' => '', + ], + 'plugin' => [ + 'filter' => FILTER_CALLBACK, + 'pageset' => true, + 'default' => '0', + 'options' => ['options' => 'sanitize_search_string'], + ], + 'sort_column' => [ + 'filter' => FILTER_CALLBACK, + 'default' => 'name', + 'options' => ['options' => 'sanitize_search_string'], + ], + 'sort_direction' => [ + 'filter' => FILTER_CALLBACK, + 'default' => 'ASC', + 'options' => ['options' => 'sanitize_search_string'], + ], + ]; + + validate_store_request_vars($filters, 'sess_intropage_panels'); + + if (get_request_var('rows') == '-1') { + $rows = read_config_option('num_rows_table'); + } else { + $rows = get_request_var('rows'); + } + + intropage_panels_filter(); + + /* build the where clause */ + $sql_where = ''; + $sql_params = []; + + if (get_request_var('filter') != '') { + $sql_where = 'WHERE (name LIKE ? OR panel_id LIKE ?)'; + + $sql_params[] = '%' . get_request_var('filter') . '%'; + $sql_params[] = '%' . get_request_var('filter') . '%'; + } + + if (get_request_var('plugin') != '0' && get_request_var('plugin') != '') { + $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . 'plugin = ?'; + + $sql_params[] = get_request_var('plugin'); + } + + $total_rows = db_fetch_cell_prepared("SELECT COUNT(*) + FROM plugin_intropage_panel_registration + $sql_where", + $sql_params); + + $sql_order = get_order_string(); + $sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows; + + $panel_list = db_fetch_assoc_prepared("SELECT * + FROM plugin_intropage_panel_registration + $sql_where + $sql_order + $sql_limit", + $sql_params); + + $nav = html_nav_bar('intropage_panels.php?filter=' . get_request_var('filter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 9, __('Panels', 'intropage'), 'page', 'main'); + + form_start('intropage_panels.php', 'chk'); + + print $nav; + + html_start_box('', '100%', '', '3', 'center', ''); + + $display_text = [ + 'name' => [ + 'display' => __('Panel Name', 'intropage'), + 'align' => 'left', + 'sort' => 'ASC', + 'tip' => __('The display name of this panel.', 'intropage'), + ], + 'plugin' => [ + 'display' => __('Source', 'intropage'), + 'align' => 'left', + 'sort' => 'ASC', + 'tip' => __('The plugin that provides this panel. Intropage\'s own panels show as Core.', 'intropage'), + ], + 'class' => [ + 'display' => __('Category', 'intropage'), + 'align' => 'left', + 'sort' => 'ASC', + 'tip' => __('The panel category.', 'intropage'), + ], + 'level' => [ + 'display' => __('Level', 'intropage'), + 'align' => 'left', + 'sort' => 'ASC', + 'tip' => __('System panels are shared by all users; User panels are per-user.', 'intropage'), + ], + 'requires' => [ + 'display' => __('Requires', 'intropage'), + 'align' => 'left', + 'sort' => 'ASC', + 'tip' => __('Plugins that must be enabled for this panel to render.', 'intropage'), + ], + 'refresh' => [ + 'display' => __('Refresh', 'intropage'), + 'align' => 'right', + 'sort' => 'ASC', + 'tip' => __('The panel data collection interval.', 'intropage'), + ], + 'update_func' => [ + 'display' => __('Update Function', 'intropage'), + 'align' => 'left', + 'sort' => 'ASC', + 'tip' => __('The function the poller calls to collect this panel\'s data.', 'intropage'), + ], + 'enabled' => [ + 'display' => __('Status', 'intropage'), + 'align' => 'right', + 'sort' => 'DESC', + 'tip' => __('Whether the panel is enabled.', 'intropage'), + ], + ]; + + html_header_sort_checkbox($display_text, get_request_var('sort_column'), get_request_var('sort_direction'), false); + + if (cacti_sizeof($panel_list)) { + foreach ($panel_list as $panel) { + $source = ($panel['plugin'] === 'intropage') ? __('Core', 'intropage') : ucwords(str_replace(['_', '-'], ' ', $panel['plugin'])); + $level = ((int) $panel['level'] === 0) ? __('System', 'intropage') : __('User', 'intropage'); + $status = ((int) $panel['enabled'] === 1) ? __('Enabled', 'intropage') : __('Disabled', 'intropage'); + + form_alternate_row('line' . $panel['panel_id'], true, ((int) $panel['enabled'] !== 1)); + + form_selectable_cell(filter_value(intropage_prefix_panel_name($panel['panel_id'], $panel['name']), get_request_var('filter')), $panel['panel_id']); + form_selectable_cell(html_escape($source), $panel['panel_id']); + form_selectable_cell(html_escape($panel['class']), $panel['panel_id']); + form_selectable_cell($level, $panel['panel_id']); + form_selectable_cell(html_escape($panel['requires'] != '' ? $panel['requires'] : __('None', 'intropage')), $panel['panel_id']); + form_selectable_cell(intropage_readable_interval((float) $panel['refresh'], 0, false), $panel['panel_id'], '', 'right'); + form_selectable_cell(html_escape($panel['update_func']), $panel['panel_id']); + form_selectable_cell($status, $panel['panel_id'], '', 'right'); + form_checkbox_cell($panel['name'], $panel['panel_id']); + + form_end_row(); + } + } else { + print "" . __('No Panels Found', 'intropage') . ''; + } + + html_end_box(false); + + if (cacti_sizeof($panel_list)) { + print $nav; + } + + draw_actions_dropdown($panel_actions); + + form_end(); +} + +/** + * Renders the Panel Library filter box: a text search, a source-plugin + * dropdown and a rows-per-page selector, matching Cacti's standard filter UI + * (as used by cdef.php). + * + * @return void + */ +function intropage_panels_filter(): void { + $plugins = db_fetch_assoc('SELECT DISTINCT plugin + FROM plugin_intropage_panel_registration + ORDER BY plugin'); + + html_start_box(__('Intropage Panel Library', 'intropage'), '100%', '', '3', 'center', ''); + + ?> + + +
    + + + + + + + + + + + +
    + + + + >\n" "Language-Team: Cacti Developers \n" @@ -302,6 +302,10 @@ msgstr "" msgid "Panel not found" msgstr "" +#: includes/functions.php +msgid "This panel is unavailable because its required plugin is disabled." +msgstr "" + #: includes/functions.php msgid "The Panel includes a render function but it does not exist." msgstr "" diff --git a/manifest.json b/manifest.json index 83ede1f..530e629 100644 --- a/manifest.json +++ b/manifest.json @@ -17,6 +17,7 @@ "includes/", "index.php", "intropage.php", + "intropage_panels.php", "js/", "locales/", "manifest.json", 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..57fd8b5 100644 --- a/poller_intropage.php +++ b/poller_intropage.php @@ -107,6 +107,15 @@ // Make intropage first to gather correct stats intropage_correct_load_order(); +// Keep the panel registration catalog in sync with the panellib/ directory: +// re-register built-in panels whenever a panel file's mtime changes, so the +// Panel Library and management page read from the table instead of rebuilding +// from disk on every request. +intropage_sync_core_registrations(); + +// 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/setup.php b/setup.php index b485959..9d2b2ad 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