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/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; - } ?> -
- -
-
- - -
-
- -
+ + + +