feat: whitelisted WordPress settings tools
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01At3V6SjwbMe6eMzVGW3Hs7
This commit is contained in:
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\WordPress\Settings;
|
||||
|
||||
use LIT\MCP\Abilities\Ability;
|
||||
use LIT\MCP\Abilities\Errors;
|
||||
use LIT\MCP\Abilities\JsonMap;
|
||||
use LIT\MCP\Abilities\ToolResult;
|
||||
use LIT\MCP\ChangeLog\ChangeLog;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* lit/wp-settings-update: writes whitelisted WordPress options, all or nothing.
|
||||
*
|
||||
* Every value is validated against SettingsWhitelist first; nothing is written if any
|
||||
* value is invalid. "At least one setting" is enforced here in code rather than with the
|
||||
* JSON Schema keyword `minProperties`: the plan's Global Constraints list only the JSON
|
||||
* Schema keywords rest_validate_value_from_schema() checks for this project
|
||||
* (type/properties/required/items/enum/minimum/maximum/minLength/maxLength/pattern/
|
||||
* minItems/maxItems/additionalProperties) and `minProperties` is not among them, even
|
||||
* though WordPress core's REST validator does support it (controller ruling C6).
|
||||
*/
|
||||
final class WpSettingsUpdateAbility implements Ability
|
||||
{
|
||||
public function __construct(private SettingsWhitelist $whitelist, private ChangeLog $log)
|
||||
{
|
||||
}
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'lit/wp-settings-update';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'WordPress-Einstellungen ändern';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Ändert freigegebene WordPress-Einstellungen (Schlüssel siehe lit-wp-settings-get). Alle Werte '
|
||||
. 'werden vorher geprüft – bei einem Fehler wird nichts gespeichert. previous enthält die alten Werte. '
|
||||
. 'Gesperrt: admin_email, users_can_register, default_role, siteurl, home.';
|
||||
}
|
||||
|
||||
public function inputSchema(): array
|
||||
{
|
||||
return [
|
||||
'type' => 'object',
|
||||
'properties' => [
|
||||
'settings' => [
|
||||
'type' => 'object',
|
||||
'description' => 'Schlüssel → neuer Wert, mindestens einer, z. B. {"blogname": "Praxis Muster"}.',
|
||||
],
|
||||
],
|
||||
'required' => ['settings'],
|
||||
'additionalProperties' => false,
|
||||
];
|
||||
}
|
||||
|
||||
public function outputSchema(): ?array
|
||||
{
|
||||
return ToolResult::schema(['previous' => ['type' => 'object']], ['previous']);
|
||||
}
|
||||
|
||||
public function annotations(): array
|
||||
{
|
||||
return ['readonly' => false, 'destructive' => false, 'idempotent' => true];
|
||||
}
|
||||
|
||||
public function isDirect(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function permission(array $input): bool|WP_Error
|
||||
{
|
||||
return current_user_can('manage_options')
|
||||
? true
|
||||
: Errors::forbidden('Keine Berechtigung für WordPress-Einstellungen (manage_options).');
|
||||
}
|
||||
|
||||
public function execute(array $input): mixed
|
||||
{
|
||||
$settings = is_array($input['settings'] ?? null) ? $input['settings'] : [];
|
||||
if ($settings === []) {
|
||||
return Errors::invalidInput('Keine Einstellungen angegeben.', ['settings' => 'mindestens ein Schlüssel']);
|
||||
}
|
||||
|
||||
$errors = $this->validateAll($settings);
|
||||
if ($errors !== []) {
|
||||
return Errors::invalidInput(
|
||||
'Einstellungen ungültig; nichts wurde gespeichert.',
|
||||
$errors,
|
||||
'Werte gemäß fields korrigieren; aktuelle Werte über lit-wp-settings-get.'
|
||||
);
|
||||
}
|
||||
|
||||
return $this->write($settings);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $settings
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function validateAll(array $settings): array
|
||||
{
|
||||
$errors = [];
|
||||
foreach ($settings as $key => $value) {
|
||||
$error = $this->whitelist->validate((string) $key, $value, $settings);
|
||||
if ($error !== null) {
|
||||
$errors[(string) $key] = $error;
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* All values are already known-valid; writes only the ones that actually change.
|
||||
* If a write fails partway through, the already-written keys are restored to their
|
||||
* previous values so the call stays all-or-nothing.
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
*/
|
||||
private function write(array $settings): array|WP_Error
|
||||
{
|
||||
$previous = [];
|
||||
foreach ($settings as $key => $value) {
|
||||
$previous[(string) $key] = $this->whitelist->current((string) $key);
|
||||
}
|
||||
|
||||
$changed = [];
|
||||
try {
|
||||
foreach ($settings as $key => $value) {
|
||||
$key = (string) $key;
|
||||
if ($previous[$key] === $value) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->writeOne($key, $value);
|
||||
$changed[] = $key;
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
return $this->fail($changed, $previous, $e);
|
||||
}
|
||||
|
||||
if ($changed === []) {
|
||||
return ToolResult::ok('Keine Änderung – alle Werte waren bereits gesetzt.')
|
||||
->with('previous', JsonMap::of($previous))
|
||||
->toArray();
|
||||
}
|
||||
|
||||
$summary = 'Einstellungen geändert: ' . implode(', ', $changed);
|
||||
$logId = $this->log->record($this->name(), 'option', implode(',', $changed), $summary);
|
||||
|
||||
$result = ToolResult::ok($summary . '.');
|
||||
foreach ($changed as $key) {
|
||||
$result->changed($key, 'option', 'updated', SettingsWhitelist::SETTINGS[$key][2]);
|
||||
}
|
||||
|
||||
return $result->logId($logId)->with('previous', JsonMap::of($previous))->toArray();
|
||||
}
|
||||
|
||||
private function writeOne(string $key, mixed $value): void
|
||||
{
|
||||
if ($key === 'permalink_structure') {
|
||||
$this->setPermalinkStructure((string) $value);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (update_option($key, $this->whitelist->normalize($key, $value)) === false) {
|
||||
throw new RuntimeException(sprintf('update_option(%s) returned false', $key));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A write failed; restores the keys already written to their previous values and
|
||||
* reports write_failed (fully restored) or partial_write (some keys could not be
|
||||
* restored – the client is told which, so it can check and correct them).
|
||||
*
|
||||
* @param list<string> $changed Keys written so far, in write order.
|
||||
* @param array<string, mixed> $previous Their values before this call.
|
||||
*/
|
||||
private function fail(array $changed, array $previous, Throwable $cause): WP_Error
|
||||
{
|
||||
$stuck = [];
|
||||
foreach (array_reverse($changed) as $key) {
|
||||
try {
|
||||
$this->writeOne($key, $previous[$key]);
|
||||
} catch (Throwable $e) {
|
||||
$stuck[] = $key;
|
||||
}
|
||||
}
|
||||
|
||||
error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
|
||||
sprintf('[wp-lit-mcp] wp-settings-update failed: %s', $cause)
|
||||
);
|
||||
|
||||
if ($stuck === []) {
|
||||
return Errors::writeFailed('Eine Einstellung konnte nicht gespeichert werden.');
|
||||
}
|
||||
|
||||
return Errors::partialWrite(
|
||||
'Eine Einstellung konnte nicht gespeichert werden.',
|
||||
null,
|
||||
null,
|
||||
sprintf(
|
||||
'Möglicherweise auf dem neuen, nicht vollständigen Stand: %s.',
|
||||
implode(', ', $stuck)
|
||||
),
|
||||
'Aktuelle Werte über lit-wp-settings-get prüfen und ggf. erneut auf die gewünschten Werte setzen.'
|
||||
);
|
||||
}
|
||||
|
||||
private function setPermalinkStructure(string $structure): void
|
||||
{
|
||||
global $wp_rewrite;
|
||||
$wp_rewrite->set_permalink_structure($structure);
|
||||
flush_rewrite_rules();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user