Extensions #12
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
$snippet = \Plugi\Setting::get('ext--tracking--head') ?? '';
|
||||
?>
|
||||
<section class="card border border-base-300/60 bg-base-100 shadow-sm" aria-labelledby="tracking-settings-title">
|
||||
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
|
||||
<div>
|
||||
<h2 class="card-title text-xl" id="tracking-settings-title">Tracking snippet</h2>
|
||||
<p class="mt-1 text-sm text-base-content/60">Add one HTML or JavaScript snippet to the public page head.</p>
|
||||
</div>
|
||||
<div class="alert alert-warning" role="alert">
|
||||
<i class="ph ph-warning-circle" aria-hidden="true"></i>
|
||||
<span>Saved code is inserted as-is and executes on every public page. Only save code you trust.</span>
|
||||
</div>
|
||||
<form method="post" action="<?= phpb_e(phpb_full_url('/ext--tracking/save')) ?>" class="space-y-4">
|
||||
<?php phpb_csrf_field(); ?>
|
||||
<div class="form-control w-full">
|
||||
<label class="label" for="tracking-snippet">
|
||||
<span class="label-text">HTML / JavaScript</span>
|
||||
</label>
|
||||
<textarea id="tracking-snippet" name="snippet" rows="14" spellcheck="false" class="textarea textarea-bordered w-full font-mono"><?= phpb_e($snippet) ?></textarea>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Save snippet</button>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'title' => 'Tracking',
|
||||
'author' => 'Paul Spenke',
|
||||
'identifier' => 'tracking',
|
||||
'licence' => 'MIT',
|
||||
'version' => '1.0.0',
|
||||
];
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
use Plugi\Extensions;
|
||||
use Plugi\Setting;
|
||||
|
||||
Extensions::addRoutes([
|
||||
'/ext--tracking/save' => __DIR__ . '/routes/save.php',
|
||||
]);
|
||||
|
||||
Extensions::registerBackend('tracking', [
|
||||
'title' => 'Tracking',
|
||||
'include' => __DIR__ . '/admin/tracking.php',
|
||||
'icon' => '<i class="ph ph-code"></i>',
|
||||
]);
|
||||
|
||||
Extensions::registerHtmlBlock(static fn (): string => Setting::get('ext--tracking--head') ?? '', 'head');
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
phpb_requires_authenticated();
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !phpb_validate_csrf()) {
|
||||
http_response_code(403);
|
||||
exit('Forbidden');
|
||||
}
|
||||
|
||||
if (!isset($_POST['snippet']) || !is_string($_POST['snippet'])) {
|
||||
http_response_code(400);
|
||||
exit('Invalid snippet');
|
||||
}
|
||||
|
||||
$saved = (new \Plugi\Repositories\SettingRepository())->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.',
|
||||
]);
|
||||
@@ -0,0 +1,185 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/../../../plugi-core/src/Contracts/SettingRepositoryContract.php';
|
||||
require_once __DIR__ . '/../../../plugi-core/src/Core/DB.php';
|
||||
require_once __DIR__ . '/../../../plugi-core/src/Extensions.php';
|
||||
require_once __DIR__ . '/../../../plugi-core/src/Repositories/BaseRepository.php';
|
||||
require_once __DIR__ . '/../../../plugi-core/src/Repositories/SettingRepository.php';
|
||||
require_once __DIR__ . '/../../../plugi-core/src/Contracts/SettingContract.php';
|
||||
require_once __DIR__ . '/../../../plugi-core/src/Setting.php';
|
||||
|
||||
function phpb_remove_non_alpha_numeric(string $value): string
|
||||
{
|
||||
return preg_replace('/\W*/', '', $value);
|
||||
}
|
||||
|
||||
class TrackingTestDatabase extends \Plugi\Core\DB
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this->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 '<input type="hidden" name="_token" value="test">';
|
||||
}
|
||||
|
||||
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 = '<script>window.tracking = "saved";</script>';
|
||||
(new \Plugi\Repositories\SettingRepository())->updateSettings([
|
||||
'ext--tracking--head' => $snippet,
|
||||
]);
|
||||
|
||||
$GLOBALS['trackingTestAuthenticated'] = true;
|
||||
$GLOBALS['trackingTestCsrfValid'] = false;
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_POST = ['snippet' => '<script>window.tracking = "invalid-csrf";</script>'];
|
||||
|
||||
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 = "<script>window.tracking = 'saved';</script>";
|
||||
$_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'] = '<script>window.tracking = "unauthorized";</script>';
|
||||
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");
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
|
||||
use Plugi\Extensions;
|
||||
use Plugi\Setting;
|
||||
|
||||
$activeLanguages = phpb_active_languages();
|
||||
?>
|
||||
@@ -104,57 +105,59 @@ $activeLanguages = phpb_active_languages();
|
||||
</section>
|
||||
</div>
|
||||
<div id="settings-panel-3" class="space-y-6" role="tabpanel" aria-labelledby="settings-tab-3" tabindex="0" x-show="activeTab === 3">
|
||||
<div class="flex flex-col gap-4">
|
||||
<?php foreach (Extensions::getConfigs() as $extKey => $config):
|
||||
if (count(Extensions::getSettings($extKey)) === 0) {
|
||||
continue;
|
||||
} ?>
|
||||
<details class="collapse collapse-arrow border border-base-300 bg-base-100">
|
||||
<summary class="collapse-title text-lg font-semibold"><?= phpb_e(
|
||||
$config["title"],
|
||||
) ?></summary>
|
||||
<div class="collapse-content">
|
||||
<div class="space-y-4">
|
||||
<?php foreach (
|
||||
Extensions::getSettings($extKey)
|
||||
as $setting
|
||||
): ?>
|
||||
<?php if ($setting["type"] === "text"): ?>
|
||||
<label class="form-control w-full gap-2">
|
||||
<span class="label-text"><?= phpb_e(
|
||||
$setting["label"] ?:
|
||||
$setting["name"],
|
||||
) ?></span>
|
||||
<input type="text" name="<?= phpb_e(
|
||||
$setting["key"],
|
||||
) ?>" value="<?= phpb_e(
|
||||
<?php foreach (Extensions::getConfigs() as $extKey => $config):
|
||||
$extensionSettings = Extensions::getSettings($extKey);
|
||||
$activationKey = "extensions--{$extKey}--enabled";
|
||||
?>
|
||||
<section class="space-y-4 rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<h3 class="text-lg font-semibold"><?= phpb_e($config["title"]) ?></h3>
|
||||
<label class="label cursor-pointer gap-3">
|
||||
<span class="label-text">Enabled</span>
|
||||
<input type="hidden" name="<?= phpb_e($activationKey) ?>" value="0">
|
||||
<input type="checkbox" name="<?= phpb_e($activationKey) ?>" value="1" class="toggle toggle-primary" aria-label="Enable <?= phpb_e($config["title"]) ?>" <?= Setting::get($activationKey) === "1" ? "checked" : "" ?> />
|
||||
</label>
|
||||
</div>
|
||||
<?php if ($extensionSettings !== []): ?>
|
||||
<details class="collapse collapse-arrow border border-base-300 bg-base-100">
|
||||
<summary class="collapse-title text-base font-semibold">Extension settings</summary>
|
||||
<div class="collapse-content">
|
||||
<div class="space-y-4">
|
||||
<?php foreach ($extensionSettings as $setting): ?>
|
||||
<?php if ($setting["type"] === "text"): ?>
|
||||
<label class="form-control w-full gap-2">
|
||||
<span class="label-text"><?= phpb_e(
|
||||
$setting["label"] ?: $setting["name"],
|
||||
) ?></span>
|
||||
<input type="text" name="<?= phpb_e(
|
||||
$setting["key"],
|
||||
) ?>" value="<?= phpb_e(
|
||||
$setting["value"],
|
||||
) ?>" class="input input-bordered w-full" />
|
||||
</label>
|
||||
<?php endif; ?>
|
||||
<?php if ($setting["type"] === "toggle"): ?>
|
||||
<div class="form-control" x-data="{state: <?= phpb_e(
|
||||
$setting["value"],
|
||||
) ?>}">
|
||||
<label class="label cursor-pointer">
|
||||
<span class="label-text"><?= phpb_e(
|
||||
$setting["label"] ?:
|
||||
$setting["name"],
|
||||
) ?></span>
|
||||
<input type='hidden' :value="state" name="<?= phpb_e(
|
||||
$setting["key"],
|
||||
) ?>">
|
||||
<input type="checkbox" class="toggle" x-model="state" />
|
||||
</label>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
<?php endif; ?>
|
||||
<?php if ($setting["type"] === "toggle"): ?>
|
||||
<div class="form-control" x-data="{state: <?= phpb_e(
|
||||
$setting["value"],
|
||||
) ?>}">
|
||||
<label class="label cursor-pointer">
|
||||
<span class="label-text"><?= phpb_e(
|
||||
$setting["label"] ?: $setting["name"],
|
||||
) ?></span>
|
||||
<input type='hidden' :value="state" name="<?= phpb_e(
|
||||
$setting["key"],
|
||||
) ?>">
|
||||
<input type="checkbox" class="toggle" x-model="state" />
|
||||
</label>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
<?php
|
||||
endforeach; ?>
|
||||
</div>
|
||||
</details>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<div class="flex justify-end border-t border-base-300 pt-6">
|
||||
<button type="submit" class="btn btn-primary">
|
||||
|
||||
+21
-10
@@ -82,6 +82,7 @@ class Plugi
|
||||
$this->setDatabaseConnection();
|
||||
$this->checkDatabaseDefinition();
|
||||
$this->hydrateConfig();
|
||||
$this->loadEnabledExtensions();
|
||||
}
|
||||
|
||||
// init the default authentication, if enabled
|
||||
@@ -160,20 +161,10 @@ class Plugi
|
||||
$extensionFile = 'extensions/' . $extFolder . '/extension.php';
|
||||
$configFile = 'extensions/' . $extFolder . '/config.php';
|
||||
if ($entry->isDir() && ! $entry->isDot() && file_exists($extensionFile) && file_exists($configFile)) {
|
||||
require $extensionFile;
|
||||
$extConfig = include($configFile);
|
||||
$extConfig['dir'] = 'extensions/' . $extFolder;
|
||||
$extKey = $extConfig['identifier'];
|
||||
Extensions::registerConfig($extKey, $extConfig);
|
||||
if(array_key_exists('assets', $extConfig) && is_array($extConfig['assets'])){
|
||||
foreach ($extConfig['assets'] as $asset) {
|
||||
Extensions::registerAsset(
|
||||
'/extensions/'.$extFolder.$asset['src'],
|
||||
$asset['type'],
|
||||
$asset['location'],
|
||||
);
|
||||
}
|
||||
}
|
||||
if(array_key_exists('settings', $extConfig) && is_array($extConfig['settings'])){
|
||||
Extensions::addSettings(array_map(function ($setting) use($extKey){
|
||||
$setting['key'] = 'ext--' . $extKey . '--' . $setting['name'];
|
||||
@@ -186,6 +177,26 @@ class Plugi
|
||||
}
|
||||
}
|
||||
|
||||
public function loadEnabledExtensions()
|
||||
{
|
||||
foreach (Extensions::getConfigs() as $extKey => $extConfig) {
|
||||
if (Setting::get('extensions--' . $extKey . '--enabled') !== '1') {
|
||||
continue;
|
||||
}
|
||||
|
||||
require $extConfig['dir'] . '/extension.php';
|
||||
if (array_key_exists('assets', $extConfig) && is_array($extConfig['assets'])) {
|
||||
foreach ($extConfig['assets'] as $asset) {
|
||||
Extensions::registerAsset(
|
||||
'/extensions/' . basename($extConfig['dir']) . $asset['src'],
|
||||
$asset['type'],
|
||||
$asset['location'],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Plugi configuration to the given array.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
use Plugi\Core\DB;
|
||||
use Plugi\Extensions;
|
||||
use Plugi\Plugi;
|
||||
use Plugi\Setting;
|
||||
|
||||
chdir(dirname(__DIR__, 2));
|
||||
|
||||
require_once __DIR__ . '/../src/Extensions.php';
|
||||
require_once __DIR__ . '/../src/Contracts/SettingContract.php';
|
||||
require_once __DIR__ . '/../src/Contracts/SettingRepositoryContract.php';
|
||||
require_once __DIR__ . '/../src/Setting.php';
|
||||
require_once __DIR__ . '/../src/Core/DB.php';
|
||||
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
|
||||
require_once __DIR__ . '/../src/Repositories/SettingRepository.php';
|
||||
require_once __DIR__ . '/../src/Plugi.php';
|
||||
|
||||
function phpb_config(string $key)
|
||||
{
|
||||
$value = $GLOBALS['phpb_config'];
|
||||
foreach (explode('.', $key) as $part) {
|
||||
if (! is_array($value) || ! array_key_exists($part, $value)) {
|
||||
return null;
|
||||
}
|
||||
$value = $value[$part];
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
function phpb_instance(string $name, array $params = []): ?string
|
||||
{
|
||||
return $name === 'setting' ? Setting::class : null;
|
||||
}
|
||||
|
||||
function phpb_current_language(): string
|
||||
{
|
||||
return 'en';
|
||||
}
|
||||
|
||||
function phpb_remove_non_alpha_numeric(string $value): string
|
||||
{
|
||||
return preg_replace('/[^a-zA-Z0-9]/', '', $value);
|
||||
}
|
||||
|
||||
class ExtensionActivationTestDatabase extends DB
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this->pdo = new PDO('sqlite::memory:');
|
||||
$this->pdo->exec('CREATE TABLE settings (id INTEGER PRIMARY KEY AUTOINCREMENT, setting TEXT UNIQUE, value TEXT, is_array INTEGER)');
|
||||
$this->databaseName = 'extension_activation_test';
|
||||
}
|
||||
|
||||
public function setActivation(?string $value): void
|
||||
{
|
||||
if ($value === null) {
|
||||
$statement = $this->pdo->prepare('DELETE FROM settings WHERE setting = ?');
|
||||
$statement->execute(['extensions--form--enabled']);
|
||||
return;
|
||||
}
|
||||
|
||||
$statement = $this->pdo->prepare('INSERT OR REPLACE INTO settings (setting, value, is_array) VALUES (?, ?, 0)');
|
||||
$statement->execute(['extensions--form--enabled', $value]);
|
||||
}
|
||||
}
|
||||
|
||||
class ExtensionActivationTestPlugi extends Plugi
|
||||
{
|
||||
public function setDatabaseConnection()
|
||||
{
|
||||
global $phpb_db;
|
||||
$phpb_db = $GLOBALS['extensionActivationTestDatabase'];
|
||||
}
|
||||
|
||||
public function checkDatabaseDefinition()
|
||||
{
|
||||
}
|
||||
|
||||
public function loadTranslations($language)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
$database = new ExtensionActivationTestDatabase();
|
||||
$GLOBALS['extensionActivationTestDatabase'] = $database;
|
||||
$_ENV['DATABASE_PREFIX'] = '';
|
||||
$settingValues = new ReflectionProperty(Setting::class, 'settings');
|
||||
$registryDefaults = [
|
||||
'settings' => [],
|
||||
'configs' => [],
|
||||
'backends' => [],
|
||||
'routes' => [],
|
||||
'blocks' => [],
|
||||
'layouts' => [],
|
||||
'assets' => ['header' => [], 'footer' => [], 'admin-header' => [], 'admin-footer' => []],
|
||||
'htmlBlocks' => ['head' => [], 'body-start' => [], 'body-end' => [], 'admin-head' => [], 'admin-body-start' => [], 'admin-body-end' => []],
|
||||
];
|
||||
$config = [
|
||||
'general' => ['language' => 'en'],
|
||||
'storage' => ['use_database' => true],
|
||||
'auth' => ['use_login' => false],
|
||||
'website_manager' => ['use_website_manager' => false],
|
||||
'theme' => ['folder' => dirname(__DIR__, 2) . '/themes', 'active_theme' => 'default'],
|
||||
];
|
||||
|
||||
$boot = static function (?string $activationState) use ($database, $registryDefaults, $settingValues, $config): void {
|
||||
$database->setActivation($activationState);
|
||||
$settingValues->setValue(null, null);
|
||||
foreach ($registryDefaults as $property => $value) {
|
||||
(new ReflectionProperty(Extensions::class, $property))->setValue(null, $value);
|
||||
}
|
||||
new ExtensionActivationTestPlugi($config);
|
||||
};
|
||||
|
||||
$boot('1');
|
||||
if (! isset(Extensions::getRoutes()['/ext--form/submit'])
|
||||
|| ! isset(Extensions::getBackends()['ext--form'])
|
||||
|| ! isset(Extensions::getBlocks()['form-wrapper'])) {
|
||||
throw new RuntimeException('A persisted enabled state should register the extension during bootstrap.');
|
||||
}
|
||||
if (! str_contains(Extensions::getHeaderAssets(), '/extensions/plugi-ext-form/assets/dist.css')
|
||||
|| ! str_contains(Extensions::getFooterAssets(), '/extensions/plugi-ext-form/assets/dist.js')) {
|
||||
throw new RuntimeException('A persisted enabled state should register config-declared assets during bootstrap.');
|
||||
}
|
||||
|
||||
$boot('0');
|
||||
if (Extensions::getRoutes() !== [] || Extensions::getBackends() !== [] || Extensions::getBlocks() !== []) {
|
||||
throw new RuntimeException('A persisted disabled state should not register runtime features during bootstrap.');
|
||||
}
|
||||
if (Extensions::getHeaderAssets() !== '' || Extensions::getFooterAssets() !== '' || Extensions::getHtmlBlocks('head') !== '') {
|
||||
throw new RuntimeException('A persisted disabled state should not register assets or HTML hooks during bootstrap.');
|
||||
}
|
||||
$configs = Extensions::getConfigs();
|
||||
if (! isset($configs['form']['settings'][0]['name']) || $configs['form']['settings'][0]['name'] !== 'email') {
|
||||
throw new RuntimeException('Disabled extensions should retain their settings metadata.');
|
||||
}
|
||||
$db = (new ReflectionClass(DB::class))->newInstanceWithoutConstructor();
|
||||
if (! isset($db->getDBDefinition()['ext__form_entries'])) {
|
||||
throw new RuntimeException('Disabled extensions should retain their schema definitions.');
|
||||
}
|
||||
|
||||
$boot(null);
|
||||
if (Extensions::getRoutes() !== [] || Extensions::getBackends() !== [] || Extensions::getBlocks() !== []) {
|
||||
throw new RuntimeException('An absent activation state should remain disabled during bootstrap.');
|
||||
}
|
||||
|
||||
fwrite(STDOUT, "PASS: bootstrap loads only extensions with a persisted enabled state.\n");
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
use Plugi\Extensions;
|
||||
|
||||
require_once __DIR__ . '/../src/Extensions.php';
|
||||
|
||||
$callbackValue = '<script>window.tracking = "first";</script>';
|
||||
|
||||
Extensions::registerHtmlBlock('<meta name="static" content="unchanged">', 'head');
|
||||
Extensions::registerHtmlBlock(static function () use (&$callbackValue): string {
|
||||
return $callbackValue;
|
||||
}, 'head');
|
||||
|
||||
$expected = '<meta name="static" content="unchanged">' . $callbackValue;
|
||||
if (Extensions::getHtmlBlocks('head') !== $expected) {
|
||||
throw new RuntimeException('Static and callback HTML blocks should render in registration order.');
|
||||
}
|
||||
|
||||
$callbackValue = '<script>window.tracking = "updated";</script>';
|
||||
$expected = '<meta name="static" content="unchanged">' . $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");
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
use Plugi\Core\DB;
|
||||
use Plugi\Extensions;
|
||||
use Plugi\Plugi;
|
||||
use Plugi\Repositories\SettingRepository;
|
||||
use Plugi\Setting;
|
||||
|
||||
chdir(dirname(__DIR__, 2));
|
||||
|
||||
require_once __DIR__ . '/../src/Extensions.php';
|
||||
require_once __DIR__ . '/../src/Contracts/SettingContract.php';
|
||||
require_once __DIR__ . '/../src/Contracts/SettingRepositoryContract.php';
|
||||
require_once __DIR__ . '/../src/Setting.php';
|
||||
require_once __DIR__ . '/../src/Core/DB.php';
|
||||
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
|
||||
require_once __DIR__ . '/../src/Repositories/SettingRepository.php';
|
||||
require_once __DIR__ . '/../src/Plugi.php';
|
||||
|
||||
function phpb_active_languages(): array
|
||||
{
|
||||
return ['en' => []];
|
||||
}
|
||||
|
||||
function phpb_config(string $key): ?string
|
||||
{
|
||||
return match ($key) {
|
||||
'general.language' => 'en',
|
||||
'theme.active_theme' => 'default',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
function phpb_csrf_field(): void
|
||||
{
|
||||
echo '<input type="hidden" name="_csrf_token" value="test-token">';
|
||||
}
|
||||
|
||||
function phpb_e($value): string
|
||||
{
|
||||
return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
|
||||
function phpb_instance(string $name): string
|
||||
{
|
||||
return Setting::class;
|
||||
}
|
||||
|
||||
function phpb_themes(): array
|
||||
{
|
||||
return ['default' => ['title' => 'Default']];
|
||||
}
|
||||
|
||||
function phpb_trans(string $key): array|string
|
||||
{
|
||||
return $key === 'languages' ? ['en' => 'English'] : $key;
|
||||
}
|
||||
|
||||
function phpb_url(string $module, array $parameters = []): string
|
||||
{
|
||||
return '/' . $module;
|
||||
}
|
||||
|
||||
function phpb_remove_non_alpha_numeric(string $value): string
|
||||
{
|
||||
return preg_replace('/[^a-zA-Z0-9]/', '', $value);
|
||||
}
|
||||
|
||||
class ExtensionSettingsTestDatabase extends DB
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this->pdo = new PDO('sqlite::memory:');
|
||||
$this->pdo->exec('CREATE TABLE settings (id INTEGER PRIMARY KEY AUTOINCREMENT, setting TEXT, value TEXT, is_array INTEGER)');
|
||||
$this->databaseName = 'extension_settings_test';
|
||||
}
|
||||
}
|
||||
|
||||
$settingValues = new ReflectionProperty(Setting::class, 'settings');
|
||||
$settingValues->setValue(null, []);
|
||||
|
||||
$plugi = new Plugi();
|
||||
$plugi->loadExtensions();
|
||||
Extensions::addSettings([[
|
||||
'name' => 'enabled',
|
||||
'key' => 'ext--form--enabled',
|
||||
'type' => 'text',
|
||||
'label' => 'Extension field named enabled',
|
||||
'default' => '',
|
||||
]]);
|
||||
|
||||
$renderSettings = static function (): string {
|
||||
ob_start();
|
||||
require __DIR__ . '/../src/Modules/WebsiteManager/resources/views/tabs/settings.php';
|
||||
return ob_get_clean();
|
||||
};
|
||||
|
||||
$uncheckedSettings = $renderSettings();
|
||||
foreach (Extensions::getConfigs() as $extKey => $config) {
|
||||
if (substr_count($uncheckedSettings, 'name="extensions--' . $extKey . '--enabled"') !== 2) {
|
||||
throw new RuntimeException('Each discovered extension should submit both enabled and disabled values.');
|
||||
}
|
||||
}
|
||||
if (preg_match('/<input type="checkbox" name="extensions--sitemap--enabled" value="1"[^>]*checked/', $uncheckedSettings)) {
|
||||
throw new RuntimeException('An extension without a saved state should render disabled.');
|
||||
}
|
||||
if (strpos($uncheckedSettings, 'name="extensions--form--enabled" value="0"') > strpos($uncheckedSettings, 'name="extensions--form--enabled" value="1"')) {
|
||||
throw new RuntimeException('The disabled value must precede the checkbox so checked values override it.');
|
||||
}
|
||||
if (substr_count($uncheckedSettings, 'name="ext--form--enabled"') !== 1) {
|
||||
throw new RuntimeException('An extension setting named enabled should not share the activation control name.');
|
||||
}
|
||||
|
||||
$settingValues->setValue(null, ['extensions--form--enabled' => '1', 'ext--form--enabled' => 'kept']);
|
||||
$checkedSettings = $renderSettings();
|
||||
if (! preg_match('/<input type="checkbox" name="extensions--form--enabled" value="1"[^>]*checked/', $checkedSettings)) {
|
||||
throw new RuntimeException('An enabled extension should render its switch as checked.');
|
||||
}
|
||||
if (! preg_match('/<input type="text" name="ext--form--enabled" value="kept"/', $checkedSettings)) {
|
||||
throw new RuntimeException('An extension setting named enabled should retain its submitted value.');
|
||||
}
|
||||
|
||||
$_ENV['DATABASE_PREFIX'] = '';
|
||||
$database = new ExtensionSettingsTestDatabase();
|
||||
$phpb_db = $database;
|
||||
$settingRepository = new SettingRepository();
|
||||
if (! $settingRepository->updateSettings(['extensions--form--enabled' => '1'])
|
||||
|| ! $settingRepository->updateSettings(['extensions--form--enabled' => '0'])) {
|
||||
throw new RuntimeException('The settings repository should persist both enabled and disabled values.');
|
||||
}
|
||||
$saved = $database->select('SELECT value FROM settings WHERE setting = ?', ['extensions--form--enabled']);
|
||||
if (($saved[0]['value'] ?? null) !== '0') {
|
||||
throw new RuntimeException('Saving an unchecked extension switch should replace its earlier enabled state.');
|
||||
}
|
||||
|
||||
fwrite(STDOUT, "PASS: extension switches render and persist explicit on/off values.\n");
|
||||
Reference in New Issue
Block a user