From 515e4cac1f5b1b2fdd8b4b8bf041c57ae9a6ab7f Mon Sep 17 00:00:00 2001 From: Paul Spenke Date: Mon, 30 Nov 2026 22:51:03 +0100 Subject: [PATCH 1/2] feat(ext-tracking): Add tracking extension for HTML/JS snippets Adds a new extension allowing injection of custom code into the page head. Includes an admin interface for saving snippets, secure save routes with CSRF protection, and tests verifying the functionality. Also updates core Extensions.php to support callable HTML blocks for lazy evaluation. --- .../plugi-ext-tracking/admin/tracking.php | 26 +++ extensions/plugi-ext-tracking/config.php | 9 + extensions/plugi-ext-tracking/extension.php | 16 ++ extensions/plugi-ext-tracking/routes/save.php | 22 +++ .../plugi-ext-tracking/tests/save-snippet.php | 185 ++++++++++++++++++ plugi-core/src/Extensions.php | 10 +- plugi-core/tests/extensions-html-blocks.php | 25 +++ 7 files changed, 290 insertions(+), 3 deletions(-) create mode 100644 extensions/plugi-ext-tracking/admin/tracking.php create mode 100644 extensions/plugi-ext-tracking/config.php create mode 100644 extensions/plugi-ext-tracking/extension.php create mode 100644 extensions/plugi-ext-tracking/routes/save.php create mode 100644 extensions/plugi-ext-tracking/tests/save-snippet.php create mode 100644 plugi-core/tests/extensions-html-blocks.php diff --git a/extensions/plugi-ext-tracking/admin/tracking.php b/extensions/plugi-ext-tracking/admin/tracking.php new file mode 100644 index 0000000..3392240 --- /dev/null +++ b/extensions/plugi-ext-tracking/admin/tracking.php @@ -0,0 +1,26 @@ + +
+
+
+

Tracking snippet

+

Add one HTML or JavaScript snippet to the public page head.

+
+ +
+ +
+ + +
+ +
+
+
\ No newline at end of file diff --git a/extensions/plugi-ext-tracking/config.php b/extensions/plugi-ext-tracking/config.php new file mode 100644 index 0000000..4b9ee1e --- /dev/null +++ b/extensions/plugi-ext-tracking/config.php @@ -0,0 +1,9 @@ + 'Tracking', + 'author' => 'Paul Spenke', + 'identifier' => 'tracking', + 'licence' => 'MIT', + 'version' => '1.0.0', +]; \ No newline at end of file diff --git a/extensions/plugi-ext-tracking/extension.php b/extensions/plugi-ext-tracking/extension.php new file mode 100644 index 0000000..0fefc85 --- /dev/null +++ b/extensions/plugi-ext-tracking/extension.php @@ -0,0 +1,16 @@ + __DIR__ . '/routes/save.php', +]); + +Extensions::registerBackend('tracking', [ + 'title' => 'Tracking', + 'include' => __DIR__ . '/admin/tracking.php', + 'icon' => '', +]); + +Extensions::registerHtmlBlock(static fn (): string => Setting::get('ext--tracking--head') ?? '', 'head'); \ No newline at end of file diff --git a/extensions/plugi-ext-tracking/routes/save.php b/extensions/plugi-ext-tracking/routes/save.php new file mode 100644 index 0000000..a8ecef6 --- /dev/null +++ b/extensions/plugi-ext-tracking/routes/save.php @@ -0,0 +1,22 @@ +updateSettings([ + 'ext--tracking--head' => $_POST['snippet'], +]); + +phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--tracking']), [ + 'message-type' => $saved ? 'success' : 'error', + 'message' => $saved ? 'Tracking snippet saved.' : 'Tracking snippet could not be saved.', +]); \ No newline at end of file diff --git a/extensions/plugi-ext-tracking/tests/save-snippet.php b/extensions/plugi-ext-tracking/tests/save-snippet.php new file mode 100644 index 0000000..6661b46 --- /dev/null +++ b/extensions/plugi-ext-tracking/tests/save-snippet.php @@ -0,0 +1,185 @@ +pdo = new PDO('sqlite::memory:'); + $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $this->pdo->exec('CREATE TABLE settings (id INTEGER PRIMARY KEY AUTOINCREMENT, setting TEXT NOT NULL UNIQUE, value TEXT NOT NULL, is_array INTEGER NOT NULL DEFAULT 0)'); + $this->databaseName = 'tracking_test'; + } +} + +class TrackingTestRedirect extends RuntimeException +{ + public function __construct(public string $url, public array $flashData) + { + parent::__construct('Redirect requested.'); + } +} + +class TrackingTestAuthenticationRequired extends RuntimeException +{ +} + +function phpb_requires_authenticated(): void +{ + if (!($GLOBALS['trackingTestAuthenticated'] ?? false)) { + throw new TrackingTestAuthenticationRequired(); + } +} + +function phpb_validate_csrf(): bool +{ + return $GLOBALS['trackingTestCsrfValid'] ?? false; +} + +function phpb_e(string $value): string +{ + return htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); +} + +function phpb_csrf_field(): void +{ + echo ''; +} + +function phpb_full_url(string $path): string +{ + return '/plugi' . $path; +} + +function phpb_url(string $module, array $parameters = []): string +{ + return $module . '?' . http_build_query($parameters); +} + +function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void +{ + throw new TrackingTestRedirect($url, $flashData); +} + +require __DIR__ . '/../extension.php'; + +if (realpath(\Plugi\Extensions::getRoute('/ext--tracking/save')) !== realpath(__DIR__ . '/../routes/save.php')) { + throw new RuntimeException('The Tracking save route should be registered.'); +} +if (realpath(\Plugi\Extensions::getBackends()['ext--tracking']['include'] ?? '') !== realpath(__DIR__ . '/../admin/tracking.php')) { + throw new RuntimeException('The Tracking Website Manager backend should be registered.'); +} + +$_ENV['DATABASE_PREFIX'] = ''; +$phpb_db = new TrackingTestDatabase(); +ob_start(); +require __DIR__ . '/../admin/tracking.php'; +$trackingEditor = ob_get_clean(); +if (!str_contains($trackingEditor, 'action="/plugi/ext--tracking/save"')) { + throw new RuntimeException('The Tracking editor should post to its registered extension route.'); +} + +if (($argv[1] ?? null) === 'csrf-rejection') { + $snippet = ''; + (new \Plugi\Repositories\SettingRepository())->updateSettings([ + 'ext--tracking--head' => $snippet, + ]); + + $GLOBALS['trackingTestAuthenticated'] = true; + $GLOBALS['trackingTestCsrfValid'] = false; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = ['snippet' => '']; + + register_shutdown_function(static function () use ($phpb_db, $snippet): void { + if (http_response_code() !== 403) { + fwrite(STDERR, "Invalid CSRF should return HTTP 403.\n"); + exit(1); + } + + $saved = $phpb_db->select('SELECT value FROM settings WHERE setting = ?', ['ext--tracking--head']); + if (($saved[0]['value'] ?? null) !== $snippet) { + fwrite(STDERR, "Invalid CSRF must not change the saved snippet.\n"); + exit(1); + } + + fwrite(STDOUT, "PASS: authenticated invalid-CSRF requests are rejected without changing the saved snippet.\n"); + }); + + require __DIR__ . '/../routes/save.php'; + throw new RuntimeException('Authenticated requests with invalid CSRF should be rejected.'); +} + +if (\Plugi\Extensions::getHtmlBlocks('head') !== '') { + throw new RuntimeException('An unset tracking snippet should add no head output.'); +} + +$GLOBALS['trackingTestAuthenticated'] = true; +$GLOBALS['trackingTestCsrfValid'] = true; +$_SERVER['REQUEST_METHOD'] = 'POST'; +$snippet = ""; +$_POST = ['snippet' => $snippet]; + +try { + require __DIR__ . '/../routes/save.php'; +} catch (TrackingTestRedirect $redirect) { + if ($redirect->url !== 'website_manager?tab=ext--tracking' || $redirect->flashData['message-type'] !== 'success') { + throw new RuntimeException('Saving should redirect back to the Tracking editor with success feedback.'); + } +} + +$saved = $phpb_db->select('SELECT value FROM settings WHERE setting = ?', ['ext--tracking--head']); +if (($saved[0]['value'] ?? null) !== $snippet) { + throw new RuntimeException('The submitted snippet should be persisted unchanged.'); +} + +$settingsProperty = new ReflectionProperty(\Plugi\Setting::class, 'settings'); +$settingsProperty->setValue(null, null); +if (\Plugi\Extensions::getHtmlBlocks('head') !== $snippet) { + throw new RuntimeException('The saved tracking snippet should be emitted unchanged in head output.'); +} + +$GLOBALS['trackingTestAuthenticated'] = false; +$_POST['snippet'] = ''; +try { + require __DIR__ . '/../routes/save.php'; + throw new RuntimeException('Unauthenticated requests should be rejected.'); +} catch (TrackingTestAuthenticationRequired) { +} + +$saved = $phpb_db->select('SELECT value FROM settings WHERE setting = ?', ['ext--tracking--head']); +if (($saved[0]['value'] ?? null) !== $snippet) { + throw new RuntimeException('Unauthenticated requests must not change the saved snippet.'); +} + +$process = proc_open([PHP_BINARY, __FILE__, 'csrf-rejection'], [ + 0 => ['pipe', 'r'], + 1 => ['pipe', 'w'], + 2 => ['pipe', 'w'], +], $pipes); +if (!is_resource($process)) { + throw new RuntimeException('Could not start the invalid-CSRF route test.'); +} + +fclose($pipes[0]); +$output = stream_get_contents($pipes[1]); +$error = stream_get_contents($pipes[2]); +fclose($pipes[1]); +fclose($pipes[2]); +$status = proc_close($process); +if ($status !== 0 || !str_contains($output, 'PASS: authenticated invalid-CSRF requests are rejected')) { + throw new RuntimeException(sprintf('The invalid-CSRF route test failed (status %d): %s%s', $status, $output, $error)); +} + +fwrite(STDOUT, "PASS: tracking snippets are saved unchanged; authentication and CSRF are required.\n"); \ No newline at end of file diff --git a/plugi-core/src/Extensions.php b/plugi-core/src/Extensions.php index 7216921..3b5d0de 100644 --- a/plugi-core/src/Extensions.php +++ b/plugi-core/src/Extensions.php @@ -68,10 +68,10 @@ class Extensions /** * Register an HtmlBlock. - * @param string $html + * @param string|callable $html * @param string $location */ - public static function registerHtmlBlock(string $html, string $location = 'head') { + public static function registerHtmlBlock(string|callable $html, string $location = 'head') { self::$htmlBlocks[$location][] = $html; } @@ -245,7 +245,11 @@ class Extensions */ public static function getHtmlBlocks(string $location = 'head'): string { - return implode('', self::$htmlBlocks[$location]); + $html = ''; + foreach (self::$htmlBlocks[$location] as $block) { + $html .= is_string($block) ? $block : $block(); + } + return $html; } /** diff --git a/plugi-core/tests/extensions-html-blocks.php b/plugi-core/tests/extensions-html-blocks.php new file mode 100644 index 0000000..aa540b8 --- /dev/null +++ b/plugi-core/tests/extensions-html-blocks.php @@ -0,0 +1,25 @@ +window.tracking = "first";'; + +Extensions::registerHtmlBlock('', 'head'); +Extensions::registerHtmlBlock(static function () use (&$callbackValue): string { + return $callbackValue; +}, 'head'); + +$expected = '' . $callbackValue; +if (Extensions::getHtmlBlocks('head') !== $expected) { + throw new RuntimeException('Static and callback HTML blocks should render in registration order.'); +} + +$callbackValue = ''; +$expected = '' . $callbackValue; +if (Extensions::getHtmlBlocks('head') !== $expected) { + throw new RuntimeException('HTML-block callbacks should be evaluated each time their location is retrieved.'); +} + +fwrite(STDOUT, "PASS: HTML blocks render strings and lazy callbacks.\n"); \ No newline at end of file From 2e42cd00d20a1171d7ab2e7edaa7b0c70d05df9e Mon Sep 17 00:00:00 2001 From: Paul Spenke Date: Tue, 1 Dec 2026 10:28:46 +0100 Subject: [PATCH 2/2] feat(extensions): Add extension enable/disable toggle and loading logic The settings view now renders a toggle switch for each extension to enable or disable it. The `Plugi` class includes a new method to load extensions based on their enabled state. Tests verify the activation logic and settings persistence. --- .../resources/views/tabs/settings.php | 97 ++++++------ plugi-core/src/Plugi.php | 31 ++-- plugi-core/tests/extensions-activation.php | 148 ++++++++++++++++++ plugi-core/tests/extensions-settings.php | 136 ++++++++++++++++ 4 files changed, 355 insertions(+), 57 deletions(-) create mode 100644 plugi-core/tests/extensions-activation.php create mode 100644 plugi-core/tests/extensions-settings.php diff --git a/plugi-core/src/Modules/WebsiteManager/resources/views/tabs/settings.php b/plugi-core/src/Modules/WebsiteManager/resources/views/tabs/settings.php index 6ec921d..810f021 100644 --- a/plugi-core/src/Modules/WebsiteManager/resources/views/tabs/settings.php +++ b/plugi-core/src/Modules/WebsiteManager/resources/views/tabs/settings.php @@ -1,6 +1,7 @@ @@ -104,57 +105,59 @@ $activeLanguages = phpb_active_languages();
-
- $config): - if (count(Extensions::getSettings($extKey)) === 0) { - continue; - } ?> -
- -
-
- - -
-
- -
+ + + +