From 251934ce5377c1e15fda96d41d2cab41ada30956 Mon Sep 17 00:00:00 2001 From: Jan-Niclas Loosen Date: Sat, 26 Sep 2026 04:33:15 +0200 Subject: [PATCH] feat: deferred 1a items - menu_rev lock, lit_mcp_guides filter, warnings, schedule guard precision Task 14 (rulings P17/P18, Q10): - lit/menu-get returns menu_rev (Rev::ofMenu over id, parent, position, title, url, object, object_id); lit/menu-set-items requires it, refuses a stale one with rev_mismatch (hint: lit/menu-get) and returns the new menu_rev. Errors::revMismatch takes an optional message/hint. - GuideRepository: filter lit_mcp_guides adds/overrides topics; invalid topic names and non-string content are ignored, files stay the default. - lit/post-trash names front page, posts page and linking menus in the confirmation and as warnings; lit/menu-assign-location needs confirm to remove an assigned menu and names it; lit/post-schedule warns that a private entry becomes public; Divi hints no longer point to non-existing lit-divi-* tools. - PostGuard::missedSchedule: 60 s publish window, zero GMT date falls back to get_gmt_from_date(post_date); post-schedule refuses dates within that window. - write_failed after a clean rollback that keeps a revision/backup says "Die Aenderung wurde nicht gespeichert (... bleibt erhalten)" via the new state parameter (Errors::writeFailed / WriteFailed rolledBackState). - wp-basis-smoke: menu_rev flow, unassign confirm, trash/menu and private-schedule warnings. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01At3V6SjwbMe6eMzVGW3Hs7 --- docs/guides/content-types.md | 13 +++- docs/guides/workflows.md | 11 ++- src/Abilities/Errors.php | 31 ++++++-- src/Abilities/Rev.php | 26 +++++++ src/Abilities/WriteFailed.php | 8 +- src/Guides/GuideRepository.php | 67 ++++++++++++++--- .../WordPress/Content/ContentGetAbility.php | 2 +- .../Content/ContentUpdateAbility.php | 15 +++- .../WordPress/Content/PostPresenter.php | 9 ++- .../Menus/MenuAssignLocationAbility.php | 39 ++++++++-- .../WordPress/Menus/MenuGetAbility.php | 14 +++- .../WordPress/Menus/MenuSetItemsAbility.php | 32 ++++++-- src/Integrations/WordPress/PostGuard.php | 24 ++++-- .../Revisions/RevisionRestoreAbility.php | 7 +- .../Status/PostReplaceWithCopyAbility.php | 3 +- .../WordPress/Status/PostScheduleAbility.php | 21 ++++-- .../WordPress/Status/PostTrashAbility.php | 74 ++++++++++++++++++- tests/Integration/wp-basis-smoke.sh | 39 ++++++++-- tests/Unit/Abilities/ErrorsTest.php | 24 ++++++ tests/Unit/Abilities/RevAndJsonMapTest.php | 25 +++++++ tests/Unit/Abilities/WriteFailedTest.php | 11 +++ tests/Unit/Guides/GuideRepositoryTest.php | 35 +++++++++ .../Content/ContentUpdateAbilityTest.php | 7 +- .../WordPress/Content/PostPresenterTest.php | 3 +- .../Menus/MenuAssignLocationAbilityTest.php | 50 ++++++++++++- .../WordPress/Menus/MenuReadAbilitiesTest.php | 3 + .../Menus/MenuSetItemsAbilityTest.php | 69 +++++++++++++---- .../Integrations/WordPress/PostGuardTest.php | 29 ++++++++ .../Revisions/RevisionRestoreAbilityTest.php | 5 ++ .../Status/PostReplaceWithCopyAbilityTest.php | 3 + .../Status/PostScheduleAbilityTest.php | 41 ++++++++++ .../WordPress/Status/PostTrashAbilityTest.php | 58 +++++++++++++++ 32 files changed, 700 insertions(+), 98 deletions(-) diff --git a/docs/guides/content-types.md b/docs/guides/content-types.md index 4c38efa..cd93d80 100644 --- a/docs/guides/content-types.md +++ b/docs/guides/content-types.md @@ -23,7 +23,9 @@ Werkzeugnamen: `lit-…` sind direkt aufrufbare Tools; `lit/…` sind Abilities, Trefferliste. Geliefert werden nur Einträge, die der verbundene Nutzer selbst bearbeiten darf (fremde Entwürfe/private Inhalte ohne die passende Berechtigung erscheinen nicht). - `lit-content-get`: alle Daten eines Eintrags inkl. Feldern, Begriffen, Beitragsbild und `rev`. - Bei Divi-Seiten fehlt `content`; `hints` verweist auf `lit-divi-outline`. + Bei Divi-Seiten fehlt `content`; Divi-Werkzeuge folgen in einer späteren Version, bis dahin werden + Divi-Inhalte im Divi-Builder bearbeitet (Titel, Auszug, Felder und Begriffe gehen weiter über + `lit-content-update`). ## Anlegen und Ändern @@ -48,13 +50,16 @@ Werkzeugnamen: `lit-…` sind direkt aufrufbare Tools; `lit/…` sind Abilities, - Veröffentlichen, Zurückziehen und Planen sind eigene Werkzeuge (`lit-post-publish`, `lit/post-unpublish`, `lit/post-schedule` mit `date` = „JJJJ-MM-TT HH:MM“ in der Zeitzone der Website). Nur auf ausdrücklichen - Wunsch des Nutzers verwenden. -- `lit/post-trash` legt in den Papierkorb (nie endgültig) und braucht `confirm: true` nach Rückfrage. + Wunsch des Nutzers verwenden. Ein **privater** Eintrag wird durch Planen zum Zeitpunkt öffentlich (die + Antwort warnt davor). +- `lit/post-trash` legt in den Papierkorb (nie endgültig) und braucht `confirm: true` nach Rückfrage. Ist der + Eintrag Startseite, Beitragsseite oder in Menüs verlinkt, nennen Rückfrage und `warnings` das – dem Nutzer + weitergeben. ## Sicher überarbeiten 1. `lit/post-duplicate` → Entwurfskopie; die Antwort enthält die `rev` der Kopie für `lit-content-update`. -2. Kopie mit `lit-content-update` (oder den Divi-Tools) bearbeiten und dem Nutzer die Vorschau zeigen. +2. Kopie mit `lit-content-update` (Divi-Inhalte bis zu den Divi-Werkzeugen im Divi-Builder) bearbeiten und dem Nutzer die Vorschau zeigen. 3. `lit/post-replace-with-copy` übernimmt die Kopie ins Original (ID, URL, Status und Menüeinträge bleiben). Voraussetzungen: die Kopie muss noch Entwurf oder ausstehend sein, `rev` des Originals aus `lit-content-get` ist Pflicht (sie deckt Titel, Inhalt, Auszug und Status ab – Felder/Meta, die direkt am diff --git a/docs/guides/workflows.md b/docs/guides/workflows.md index 25cd116..7d20bb5 100644 --- a/docs/guides/workflows.md +++ b/docs/guides/workflows.md @@ -13,9 +13,12 @@ ## Menüs pflegen -- `lit/menu-get` liefert den Baum. Für größere Umbauten den Baum verändern und vollständig als `items` an - `lit/menu-set-items` senden (bestehende Einträge mit `id`, neue ohne `id`). Wird der Baum unverändert - zurückgeschickt, meldet das Tool „keine Änderung“ und schreibt nichts. +- `lit/menu-get` liefert den Baum und `menu_rev` (Stand des Menüs). `lit/menu-set-items` verlangt diese + `menu_rev`; hat sich das Menü inzwischen geändert, kommt `rev_mismatch` – dann mit `lit/menu-get` neu lesen. + Die Antwort enthält die neue `menu_rev` für weitere Änderungen. +- Für größere Umbauten den Baum verändern und vollständig als `items` an `lit/menu-set-items` senden + (bestehende Einträge mit `id`, neue ohne `id`). Wird der Baum unverändert zurückgeschickt, meldet das Tool + „keine Änderung“ und schreibt nichts. - Für kleine Änderungen `operations`: `{op: "add", item, parent_id?, position?}`, `{op: "move", id, parent_id?, position?}`, `{op: "remove", id}` (Kinder eines entfernten Eintrags rücken an seine Stelle). @@ -29,6 +32,8 @@ - Fallen dabei Einträge weg, verlangt das Tool `confirm: true`; `previous_items` (Stand vorher) erlaubt das Zurückbauen – neu angelegte Einträge erhalten dabei eine neue `id`, CSS-Klassen, Linkziel und Beschreibung gehen verloren. +- `lit/menu-assign-location` mit `menu_id: 0` entfernt ein Menü von seiner Position (es verschwindet dann von + der Website) und braucht dafür `confirm: true` nach Rückfrage; die Antwort nennt das entfernte Menü. ## Einträge eines eigenen Inhaltstyps (Pods) diff --git a/src/Abilities/Errors.php b/src/Abilities/Errors.php index 0624abd..f64576e 100644 --- a/src/Abilities/Errors.php +++ b/src/Abilities/Errors.php @@ -56,13 +56,14 @@ final class Errors return self::make('not_found', $message, $hint, 404); } - public static function revMismatch(): WP_Error + /** $message/$hint replace the post-oriented defaults (e.g. for the menu lock menu_rev). */ + public static function revMismatch(?string $message = null, ?string $hint = null): WP_Error { return self::make( 'rev_mismatch', - 'Der Inhalt wurde seit dem letzten Lesen geändert; nichts wurde geschrieben.', - 'Neu lesen (z. B. lit/content-get, direkt: lit-content-get) und die Änderung auf dem aktuellen Stand ' - . 'wiederholen.', + $message ?? 'Der Inhalt wurde seit dem letzten Lesen geändert; nichts wurde geschrieben.', + $hint ?? 'Neu lesen (z. B. lit/content-get, direkt: lit-content-get) und die Änderung auf dem aktuellen ' + . 'Stand wiederholen.', 409 ); } @@ -105,12 +106,18 @@ final class Errors * * @param array $details Extra error details (e.g. a backup that stays). * @param string|null $hint Replaces the default hint (e.g. "re-read before retrying"). + * @param string|null $state Replaces "Nichts wurde gespeichert." when the rollback left + * something behind on purpose (a backup or revision). */ - public static function writeFailed(string $reason, array $details = [], ?string $hint = null): WP_Error - { + public static function writeFailed( + string $reason, + array $details = [], + ?string $hint = null, + ?string $state = null + ): WP_Error { return self::make( 'write_failed', - trim('Speichern fehlgeschlagen: ' . $reason) . ' Nichts wurde gespeichert.', + trim('Speichern fehlgeschlagen: ' . $reason) . ' ' . ($state ?? 'Nichts wurde gespeichert.'), $hint ?? 'Eingaben prüfen, ggf. korrigieren und erneut versuchen; tritt der Fehler wieder auf, den ' . 'Administrator informieren (Details im PHP-Error-Log der Website).', 500, @@ -118,6 +125,16 @@ final class Errors ); } + /** + * The $state for writeFailed() when a clean rollback deliberately keeps something, e.g. + * "Revision 811" or "Sicherung 88": the change itself is not saved, but "Nichts wurde + * gespeichert" would be untrue. + */ + public static function notSavedKeeping(string $kept): string + { + return sprintf('Die Änderung wurde nicht gespeichert (%s bleibt erhalten).', $kept); + } + /** * A write failed and could not be rolled back completely – something may have been saved. * $state and $hint replace the post-oriented defaults for writes that are not about a post diff --git a/src/Abilities/Rev.php b/src/Abilities/Rev.php index 457e245..f412fbc 100644 --- a/src/Abilities/Rev.php +++ b/src/Abilities/Rev.php @@ -33,6 +33,32 @@ final class Rev ])); } + /** + * Rev of a menu ("menu_rev", optimistic lock of lit/menu-set-items): covers, per item in + * menu order, exactly what lit/menu-set-items compares and writes – id, parent, position, + * title, url and linked object. Other item data (classes, target, …) is never rewritten + * by the tool and therefore not part of the lock. + * + * @param list $items wp_get_nav_menu_items() result. + */ + public static function ofMenu(array $items): string + { + $rows = []; + foreach ($items as $item) { + $rows[] = implode("\0", [ + (string) (int) ($item->ID ?? 0), + (string) (int) ($item->menu_item_parent ?? 0), + (string) (int) ($item->menu_order ?? 0), + (string) ($item->title ?? ''), + (string) ($item->url ?? ''), + (string) ($item->object ?? ''), + (string) (int) ($item->object_id ?? 0), + ]); + } + + return self::of('menu' . "\1" . implode("\1", $rows)); + } + /** * Whether $input carries the current rev of $post (optimistic lock of the post tools). * diff --git a/src/Abilities/WriteFailed.php b/src/Abilities/WriteFailed.php index d4ef312..4fde2cf 100644 --- a/src/Abilities/WriteFailed.php +++ b/src/Abilities/WriteFailed.php @@ -15,7 +15,8 @@ use WP_Error; * lit_write_failed when everything was rolled back, lit_partial_write otherwise. * $state/$hint customise the partial-write error for writes that are not about a post (see * Errors::partialWrite()); $details are added to either error. $rolledBackHint replaces the - * default hint of the write_failed error. + * default hint of the write_failed error, $rolledBackState its "Nichts wurde gespeichert." + * (for rollbacks that deliberately keep a backup or revision). */ final class WriteFailed extends RuntimeException { @@ -30,7 +31,8 @@ final class WriteFailed extends RuntimeException public readonly ?string $state = null, public readonly ?string $hint = null, public readonly array $details = [], - public readonly ?string $rolledBackHint = null + public readonly ?string $rolledBackHint = null, + public readonly ?string $rolledBackState = null ) { $internal = $detail !== '' ? $detail : ($previous !== null ? $previous->getMessage() : $reason); parent::__construct( @@ -43,7 +45,7 @@ final class WriteFailed extends RuntimeException public function toError(): WP_Error { return $this->rolledBack - ? Errors::writeFailed($this->reason, $this->details, $this->rolledBackHint) + ? Errors::writeFailed($this->reason, $this->details, $this->rolledBackHint, $this->rolledBackState) : Errors::partialWrite( $this->reason, $this->postId, diff --git a/src/Guides/GuideRepository.php b/src/Guides/GuideRepository.php index e9b3f4b..05f848a 100644 --- a/src/Guides/GuideRepository.php +++ b/src/Guides/GuideRepository.php @@ -5,19 +5,55 @@ declare(strict_types=1); namespace LIT\MCP\Guides; /** - * Reads guide markdown files from one directory. Topic names are restricted to - * lowercase slugs, so no path outside the directory can ever be read. + * Guide topics: markdown files from one directory (the default), extended or overridden + * by the site via the filter `lit_mcp_guides` (spec §9.2), which returns + * array. Topic names are restricted to lowercase slugs, + * so no path outside the directory can ever be read; filter entries with another name or + * a non-string content are ignored. Filtered content is site-owned and returned as-is. */ final class GuideRepository { private const TOPIC_PATTERN = '/^[a-z0-9]+(?:-[a-z0-9]+)*$/'; + /** @var array|null Filtered topics, read once per instance (= request). */ + private ?array $filtered = null; + public function __construct(private string $directory) { } /** @return list */ public function topics(): array + { + $topics = array_unique(array_merge($this->fileTopics(), array_keys($this->filtered()))); + sort($topics); + + return array_values($topics); + } + + public function get(string $topic): ?string + { + if (! self::isTopic($topic)) { + return null; + } + + $filtered = $this->filtered(); + if (array_key_exists($topic, $filtered)) { + return $filtered[$topic]; + } + + if (! in_array($topic, $this->fileTopics(), true)) { + return null; + } + + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents + $content = file_get_contents($this->directory . '/' . $topic . '.md'); + + return $content === false ? null : $content; + } + + /** @return list */ + private function fileTopics(): array { $files = glob($this->directory . '/*.md'); if ($files === false) { @@ -27,25 +63,34 @@ final class GuideRepository $topics = []; foreach ($files as $file) { $topic = basename($file, '.md'); - if (preg_match(self::TOPIC_PATTERN, $topic) === 1) { + if (self::isTopic($topic)) { $topics[] = $topic; } } - sort($topics); return $topics; } - public function get(string $topic): ?string + /** @return array */ + private function filtered(): array { - if (preg_match(self::TOPIC_PATTERN, $topic) !== 1 || ! in_array($topic, $this->topics(), true)) { - return null; + if ($this->filtered !== null) { + return $this->filtered; } - $path = $this->directory . '/' . $topic . '.md'; - // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents - $content = file_get_contents($path); + $guides = apply_filters('lit_mcp_guides', []); + $this->filtered = []; + foreach (is_array($guides) ? $guides : [] as $topic => $markdown) { + if (is_string($topic) && self::isTopic($topic) && is_string($markdown)) { + $this->filtered[$topic] = $markdown; + } + } - return $content === false ? null : $content; + return $this->filtered; + } + + private static function isTopic(string $topic): bool + { + return preg_match(self::TOPIC_PATTERN, $topic) === 1; } } diff --git a/src/Integrations/WordPress/Content/ContentGetAbility.php b/src/Integrations/WordPress/Content/ContentGetAbility.php index d70db5b..86e5f69 100644 --- a/src/Integrations/WordPress/Content/ContentGetAbility.php +++ b/src/Integrations/WordPress/Content/ContentGetAbility.php @@ -29,7 +29,7 @@ final class ContentGetAbility implements Ability { return 'Liest einen Eintrag vollständig: Kerndaten, Inhalt, Begriffe, alle Felder (Pods/Meta), ' . 'Beitragsbild, rev (für lit-content-update). Bei Divi-Inhalten wird content nicht ausgegeben; ' - . 'hints verweist dann auf lit-divi-outline.'; + . 'hints erklärt dann, wie sie bearbeitet werden.'; } public function inputSchema(): array diff --git a/src/Integrations/WordPress/Content/ContentUpdateAbility.php b/src/Integrations/WordPress/Content/ContentUpdateAbility.php index b8a32d7..687401e 100644 --- a/src/Integrations/WordPress/Content/ContentUpdateAbility.php +++ b/src/Integrations/WordPress/Content/ContentUpdateAbility.php @@ -121,8 +121,7 @@ final class ContentUpdateAbility implements Ability if (array_key_exists('content', $input) && PostPresenter::usesDivi($post)) { return Errors::unsupported( 'Divi-Inhalte können nicht als Rohtext überschrieben werden; nichts wurde gespeichert.', - 'Divi-Struktur über lit-divi-outline und die lit-divi-*-Tools bearbeiten; Titel, Auszug, ' - . 'Felder und Begriffe hier ohne content ändern.' + PostPresenter::DIVI_NOTE . ' Titel, Auszug, Felder und Begriffe hier ohne content ändern.' ); } @@ -235,7 +234,17 @@ final class ContentUpdateAbility implements Ability $detail = sprintf('Update of post %d failed: %s', $postId, $cause->getMessage()); if ($failures === []) { - throw new WriteFailed(self::REASON, true, $postId, $revisionId, $cause, $detail); + throw new WriteFailed( + self::REASON, + true, + $postId, + $revisionId, + $cause, + $detail, + rolledBackState: $revisionId === null + ? null + : Errors::notSavedKeeping(sprintf('Revision %d', $revisionId)) + ); } $this->log->recordPartial( diff --git a/src/Integrations/WordPress/Content/PostPresenter.php b/src/Integrations/WordPress/Content/PostPresenter.php index f9a3cf5..ea8f3f1 100644 --- a/src/Integrations/WordPress/Content/PostPresenter.php +++ b/src/Integrations/WordPress/Content/PostPresenter.php @@ -16,10 +16,11 @@ use WP_Post; */ class PostPresenter { - public const DIVI_HINT = 'Dieser Inhalt ist mit Divi gebaut. Die Divi-Struktur wird über lit-divi-outline ' - . 'gelesen und mit den lit-divi-*-Tools bearbeitet; fehlen diese Tools, kann der Divi-Inhalt hier nicht ' - . 'bearbeitet werden. content wird deshalb nicht ausgegeben; Titel, Auszug, Felder und Begriffe sind ' - . 'über lit/content-update (direkt: lit-content-update) änderbar.'; + public const DIVI_NOTE = 'Divi-Werkzeuge folgen in einer späteren Version; bis dahin im Divi-Builder bearbeiten.'; + + public const DIVI_HINT = 'Dieser Inhalt ist mit Divi gebaut; content wird deshalb nicht ausgegeben. ' + . self::DIVI_NOTE . ' Titel, Auszug, Felder und Begriffe sind über lit/content-update ' + . '(direkt: lit-content-update) änderbar.'; public function __construct(private ContentSchema $schema) { diff --git a/src/Integrations/WordPress/Menus/MenuAssignLocationAbility.php b/src/Integrations/WordPress/Menus/MenuAssignLocationAbility.php index 1e969e7..a7f8344 100644 --- a/src/Integrations/WordPress/Menus/MenuAssignLocationAbility.php +++ b/src/Integrations/WordPress/Menus/MenuAssignLocationAbility.php @@ -13,8 +13,9 @@ use WP_Error; /** * lit/menu-assign-location: assigns a menu to a theme location (menu_id 0 removes - * the assignment). Idempotent: assigning the same menu again, or removing an - * already-empty location, changes nothing but still succeeds. + * the assignment – the menu then disappears from the site, so removing an existing + * assignment needs confirm: true). Idempotent: assigning the same menu again, or + * removing an already-empty location, changes nothing but still succeeds. */ final class MenuAssignLocationAbility implements Ability { @@ -34,7 +35,8 @@ final class MenuAssignLocationAbility implements Ability public function description(): string { - return 'Weist einer Theme-Position (siehe lit/menu-list) ein Menü zu; menu_id 0 entfernt die Zuweisung. ' + return 'Weist einer Theme-Position (siehe lit/menu-list) ein Menü zu; menu_id 0 entfernt die Zuweisung ' + . '(das Menü verschwindet dann von der Website; nur nach Rückfrage beim Nutzer mit confirm: true). ' . 'Das vorher zugewiesene Menü steht in previous_menu_id.'; } @@ -45,6 +47,10 @@ final class MenuAssignLocationAbility implements Ability 'properties' => [ 'location' => ['type' => 'string', 'minLength' => 1], 'menu_id' => ['type' => 'integer', 'minimum' => 0], + 'confirm' => [ + 'type' => 'boolean', + 'description' => 'Nur nötig bei menu_id 0 (Zuweisung entfernen): true nach Bestätigung.', + ], ], 'required' => ['location', 'menu_id'], 'additionalProperties' => false, @@ -90,12 +96,23 @@ final class MenuAssignLocationAbility implements Ability } $previous = MenuLocations::assigned()[$location] ?? 0; + $removed = $menuId === 0 && $previous > 0 ? self::menuLabel($previous) : null; + if ($removed !== null && ($input['confirm'] ?? false) !== true) { + return Errors::confirmRequired(sprintf( + 'Menü %s von der Position %s entfernen? Es wird dort dann nicht mehr angezeigt.', + $removed, + $location + )); + } + MenuLocations::assign($location, $menuId); $action = $menuId > 0 ? 'assigned' : 'unassigned'; - $summary = $menuId > 0 - ? sprintf('Menü %d der Position %s zugewiesen', $menuId, $location) - : sprintf('Zuweisung der Position %s entfernt', $location); + $summary = match (true) { + $menuId > 0 => sprintf('Menü %d der Position %s zugewiesen', $menuId, $location), + $removed !== null => sprintf('Menü %s von der Position %s entfernt', $removed, $location), + default => sprintf('Zuweisung der Position %s entfernt', $location), + }; // The assignment is saved – a change log failure from here on is logged and reported as a warning only. $warnings = []; @@ -113,4 +130,14 @@ final class MenuAssignLocationAbility implements Ability ->with('previous_menu_id', $previous > 0 ? $previous : null) ->toArray(); } + + /** '"Hauptmenü" (ID 3)', or just the ID when the menu itself no longer exists. */ + private static function menuLabel(int $menuId): string + { + $menu = wp_get_nav_menu_object($menuId); + + return is_object($menu) + ? sprintf('"%s" (ID %d)', $menu->name, $menuId) + : sprintf('(ID %d)', $menuId); + } } diff --git a/src/Integrations/WordPress/Menus/MenuGetAbility.php b/src/Integrations/WordPress/Menus/MenuGetAbility.php index 3efed74..44754c6 100644 --- a/src/Integrations/WordPress/Menus/MenuGetAbility.php +++ b/src/Integrations/WordPress/Menus/MenuGetAbility.php @@ -6,6 +6,7 @@ namespace LIT\MCP\Integrations\WordPress\Menus; use LIT\MCP\Abilities\Ability; use LIT\MCP\Abilities\Errors; +use LIT\MCP\Abilities\Rev; use WP_Error; /** @@ -29,7 +30,8 @@ final class MenuGetAbility implements Ability return 'Liefert ein Menü als Baum (id, title, type post/taxonomy/custom, object/object_id, url, ' . 'children). object_id und url sind bei post/taxonomy-Einträgen nur informativ (WordPress leitet ' . 'sie aus dem verlinkten Objekt ab); nur bei custom-Einträgen ist url maßgeblich. Der Baum kann ' - . 'bearbeitet an lit/menu-set-items zurückgegeben werden.'; + . 'bearbeitet an lit/menu-set-items zurückgegeben werden, zusammen mit menu_rev (Stand des Menüs, ' + . 'damit parallele Änderungen nicht überschrieben werden).'; } public function inputSchema(): array @@ -51,8 +53,12 @@ final class MenuGetAbility implements Ability 'name' => ['type' => 'string'], 'locations' => ['type' => 'array', 'items' => ['type' => 'string']], 'items' => ['type' => 'array', 'items' => MenuTree::nodeSchema()], + 'menu_rev' => [ + 'type' => 'string', + 'description' => 'Stand des Menüs; Pflicht für lit/menu-set-items.', + ], ], - 'required' => ['id', 'name', 'locations', 'items'], + 'required' => ['id', 'name', 'locations', 'items', 'menu_rev'], ]; } @@ -82,12 +88,14 @@ final class MenuGetAbility implements Ability } $items = wp_get_nav_menu_items($menuId); + $items = is_array($items) ? $items : []; return [ 'id' => (int) $menu->term_id, 'name' => (string) $menu->name, 'locations' => MenuLocations::of((int) $menu->term_id), - 'items' => MenuTree::build(is_array($items) ? $items : []), + 'items' => MenuTree::build($items), + 'menu_rev' => Rev::ofMenu($items), ]; } } diff --git a/src/Integrations/WordPress/Menus/MenuSetItemsAbility.php b/src/Integrations/WordPress/Menus/MenuSetItemsAbility.php index eb01c5a..e9dbc2c 100644 --- a/src/Integrations/WordPress/Menus/MenuSetItemsAbility.php +++ b/src/Integrations/WordPress/Menus/MenuSetItemsAbility.php @@ -7,6 +7,7 @@ namespace LIT\MCP\Integrations\WordPress\Menus; use LIT\MCP\Abilities\Ability; use LIT\MCP\Abilities\Errors; use LIT\MCP\Abilities\FollowUp; +use LIT\MCP\Abilities\Rev; use LIT\MCP\Abilities\ToolResult; use LIT\MCP\Abilities\WriteFailed; use LIT\MCP\ChangeLog\ChangeLog; @@ -17,7 +18,9 @@ use WP_Error; * as add/move/remove operations. Both run through one path: operations are applied to * the current tree (MenuOperations), the resulting tree is validated as a whole * (MenuWriter::plan) before anything is written, removals need confirm: true, and the - * answer always carries previous_items so a mistake can be rebuilt. Write failures + * answer always carries previous_items so a mistake can be rebuilt. menu_rev (from + * lit/menu-get, Rev::ofMenu) is the optimistic lock: a menu changed since reading is + * refused with rev_mismatch before anything is planned or written. Write failures * surface as WriteFailed (lit_write_failed / lit_partial_write) from MenuWriter::apply. */ final class MenuSetItemsAbility implements Ability @@ -41,7 +44,9 @@ final class MenuSetItemsAbility implements Ability public function description(): string { - return 'Setzt die Einträge eines Menüs. Entweder items = vollständiger Zielbaum oder operations = Liste aus ' + return 'Setzt die Einträge eines Menüs. menu_rev aus lit/menu-get ist Pflicht, damit parallele Änderungen ' + . 'nicht überschrieben werden; die Antwort enthält die neue menu_rev. Entweder items = vollständiger ' + . 'Zielbaum oder operations = Liste aus ' . '{op: add, item, parent_id?, position?}, {op: move, id, parent_id?, position?}, {op: remove, id} ' . '(Kinder eines entfernten Eintrags rücken an seine Stelle; position 0-basiert, ohne = ans Ende). ' . 'Der Baum aus lit/menu-get kann bearbeitet unverändert zurückgegeben werden: bestehende Einträge ' @@ -67,6 +72,10 @@ final class MenuSetItemsAbility implements Ability 'type' => 'object', 'properties' => [ 'menu_id' => ['type' => 'integer', 'minimum' => 1], + 'menu_rev' => [ + 'type' => 'string', + 'description' => 'menu_rev aus lit/menu-get (bzw. aus der letzten Antwort dieses Tools).', + ], 'items' => [ 'type' => 'array', 'items' => ['type' => 'object'], @@ -98,7 +107,7 @@ final class MenuSetItemsAbility implements Ability 'description' => 'Nur nötig, wenn Einträge entfernt werden.', ], ], - 'required' => ['menu_id'], + 'required' => ['menu_id', 'menu_rev'], 'additionalProperties' => false, ]; } @@ -107,7 +116,10 @@ final class MenuSetItemsAbility implements Ability { $tree = ['type' => 'array', 'items' => MenuTree::nodeSchema()]; - return ToolResult::schema(['items' => $tree, 'previous_items' => $tree], ['items', 'previous_items']); + return ToolResult::schema( + ['items' => $tree, 'previous_items' => $tree, 'menu_rev' => ['type' => ['string', 'null']]], + ['items', 'previous_items', 'menu_rev'] + ); } public function annotations(): array @@ -143,6 +155,13 @@ final class MenuSetItemsAbility implements Ability } $current = $this->currentItems($menuId); + if (($input['menu_rev'] ?? null) !== Rev::ofMenu(array_values($current))) { + return Errors::revMismatch( + 'Das Menü wurde seit dem letzten Lesen geändert; nichts wurde geschrieben.', + 'Mit lit/menu-get neu lesen und die Änderung auf dem aktuellen Stand (neue menu_rev) wiederholen.' + ); + } + $previous = MenuTree::build(array_values($current)); $tree = array_key_exists('items', $input) @@ -201,7 +220,7 @@ final class MenuSetItemsAbility implements Ability $warnings ) : null; $after = FollowUp::run( - fn () => MenuTree::build(array_values($this->currentItems($menuId))), + fn () => array_values($this->currentItems($menuId)), $this->name() . ' re-read', 'Das Menü ist gespeichert, der neue Stand konnte aber nicht gelesen werden; mit lit/menu-get abrufen.', $warnings @@ -215,8 +234,9 @@ final class MenuSetItemsAbility implements Ability return $result ->warnings($warnings) ->logId(is_int($logId) ? $logId : null) - ->with('items', is_array($after) ? $after : []) + ->with('items', is_array($after) ? MenuTree::build($after) : []) ->with('previous_items', $previous) + ->with('menu_rev', is_array($after) ? Rev::ofMenu($after) : null) ->toArray(); } diff --git a/src/Integrations/WordPress/PostGuard.php b/src/Integrations/WordPress/PostGuard.php index 2d17de2..b8d3f71 100644 --- a/src/Integrations/WordPress/PostGuard.php +++ b/src/Integrations/WordPress/PostGuard.php @@ -16,6 +16,11 @@ use WP_Post; */ final class PostGuard { + private const ZERO_DATE = '0000-00-00 00:00:00'; + + /** wp_insert_post() publishes a "future" post on save when its date is this close (MINUTE_IN_SECONDS). */ + public const PUBLISH_WINDOW = 60; + /** * Loads an entry the current user may edit. Trashed entries are refused (every write * on them would be surprising: publishing, scheduling or updating a trashed entry); @@ -56,19 +61,26 @@ final class PostGuard } /** - * A scheduled entry whose publication time has passed (WordPress' cron missed it). - * wp_update_post() publishes such an entry on any save, so writes must not touch it. + * A scheduled entry whose publication time has passed (WordPress' cron missed it) or is + * less than a minute away: wp_insert_post() turns "future" into "publish" on any save when + * the date is within the next MINUTE_IN_SECONDS, so writes must not touch such an entry. + * A zero post_date_gmt (never set) falls back to the local post_date, like core does. */ public static function missedSchedule(WP_Post $post): bool { - $gmt = (string) $post->post_date_gmt; - if ($post->post_status !== 'future' || $gmt === '' || $gmt === '0000-00-00 00:00:00') { + if ($post->post_status !== 'future') { return false; } - $time = strtotime($gmt . ' UTC'); + $gmt = (string) $post->post_date_gmt; + if ($gmt === '' || $gmt === self::ZERO_DATE) { + $local = (string) $post->post_date; + $gmt = $local === '' || $local === self::ZERO_DATE ? '' : (string) get_gmt_from_date($local); + } - return $time !== false && $time <= time(); + $time = $gmt === '' ? false : strtotime($gmt . ' UTC'); + + return $time !== false && $time <= time() + self::PUBLISH_WINDOW; } /** diff --git a/src/Integrations/WordPress/Revisions/RevisionRestoreAbility.php b/src/Integrations/WordPress/Revisions/RevisionRestoreAbility.php index c5987a0..e1b3a98 100644 --- a/src/Integrations/WordPress/Revisions/RevisionRestoreAbility.php +++ b/src/Integrations/WordPress/Revisions/RevisionRestoreAbility.php @@ -120,7 +120,12 @@ final class RevisionRestoreAbility implements Ability $backupId = RevisionPoint::capture($postId); $restored = wp_restore_post_revision((int) $revision->ID); if (! $restored) { - return Errors::writeFailed('WordPress konnte die Revision nicht wiederherstellen.'); + return Errors::writeFailed( + 'WordPress konnte die Revision nicht wiederherstellen.', + [], + null, + $backupId === null ? null : Errors::notSavedKeeping(sprintf('Revision %d', $backupId)) + ); } // The restore is saved – failures from here on are logged and reported as warnings only. diff --git a/src/Integrations/WordPress/Status/PostReplaceWithCopyAbility.php b/src/Integrations/WordPress/Status/PostReplaceWithCopyAbility.php index f59db22..69a3646 100644 --- a/src/Integrations/WordPress/Status/PostReplaceWithCopyAbility.php +++ b/src/Integrations/WordPress/Status/PostReplaceWithCopyAbility.php @@ -306,7 +306,8 @@ final class PostReplaceWithCopyAbility implements Ability $detail, null, null, - $details + $details, + rolledBackState: Errors::notSavedKeeping(sprintf('Sicherung %d im Papierkorb', $backupId)) ); } diff --git a/src/Integrations/WordPress/Status/PostScheduleAbility.php b/src/Integrations/WordPress/Status/PostScheduleAbility.php index 4bd7bbb..f517d96 100644 --- a/src/Integrations/WordPress/Status/PostScheduleAbility.php +++ b/src/Integrations/WordPress/Status/PostScheduleAbility.php @@ -43,8 +43,8 @@ final class PostScheduleAbility implements Ability public function description(): string { return 'Plant die Veröffentlichung eines Eintrags zu einem Zeitpunkt in der Zukunft (Ortszeit der ' - . 'Website). Ein bereits veröffentlichter Eintrag ist bis dahin offline. Nur auf ausdrücklichen ' - . 'Wunsch des Nutzers verwenden.'; + . 'Website). Ein bereits veröffentlichter Eintrag ist bis dahin offline; ein privater Eintrag wird ' + . 'zum Zeitpunkt öffentlich. Nur auf ausdrücklichen Wunsch des Nutzers verwenden.'; } public function inputSchema(): array @@ -99,10 +99,11 @@ final class PostScheduleAbility implements Ability return Errors::invalidInput('Ungültiges Datum.', ['date' => 'Format JJJJ-MM-TT HH:MM erwartet']); } - if ($date->getTimestamp() <= time()) { + // Within PUBLISH_WINDOW WordPress would publish at once instead of scheduling. + if ($date->getTimestamp() <= time() + PostGuard::PUBLISH_WINDOW) { return Errors::invalidInput( - 'Der Zeitpunkt muss in der Zukunft liegen.', - ['date' => 'liegt nicht in der Zukunft'], + 'Der Zeitpunkt muss mindestens eine Minute in der Zukunft liegen.', + ['date' => 'liegt nicht (mindestens eine Minute) in der Zukunft'], 'Zum sofortigen Veröffentlichen lit/post-publish (direkt: lit-post-publish) verwenden.' ); } @@ -134,7 +135,15 @@ final class PostScheduleAbility implements Ability } // The status change is saved – failures from here on are logged and reported as warnings only. - $change = (new PostChangeResult($this->name(), $this->log, $postId))->afterSave($input, 'Planen'); + $warnings = $post->post_status === 'private' + ? [sprintf( + 'Der Eintrag war privat und wird am %s ÖFFENTLICH veröffentlicht; soll er privat bleiben, die Planung ' + . 'in WordPress zurücknehmen.', + $raw + )] + : []; + $change = (new PostChangeResult($this->name(), $this->log, $postId, 'die Änderung', $warnings)) + ->afterSave($input, 'Planen'); $title = (string) $post->post_title; $summary = sprintf('"%s" geplant für %s', $title, $raw) . ($post->post_status === 'publish' ? ' (war veröffentlicht und ist bis dahin offline)' : ''); diff --git a/src/Integrations/WordPress/Status/PostTrashAbility.php b/src/Integrations/WordPress/Status/PostTrashAbility.php index b2aff09..f421d44 100644 --- a/src/Integrations/WordPress/Status/PostTrashAbility.php +++ b/src/Integrations/WordPress/Status/PostTrashAbility.php @@ -16,7 +16,9 @@ use WP_Error; use WP_Post; /** - * lit/post-trash: moves an entry to the trash – never a permanent delete. When the + * lit/post-trash: moves an entry to the trash – never a permanent delete. Trashing the + * static front page, the posts page or an entry linked in a menu is allowed but named in + * the confirmation question and as a warning in the result. When the * trash itself is disabled (EMPTY_TRASH_DAYS = 0), wp_trash_post() would delete the * entry permanently (wp-includes/post.php: `if ( ! EMPTY_TRASH_DAYS ) return * wp_delete_post( $post_id, true );`), so this tool refuses instead of calling it. @@ -48,7 +50,8 @@ final class PostTrashAbility implements Ability public function description(): string { return 'Legt einen Eintrag in den Papierkorb (nie endgültig löschen; wiederherstellbar in WordPress). ' - . 'Erst nach Rückfrage beim Nutzer mit confirm: true aufrufen.'; + . 'Erst nach Rückfrage beim Nutzer mit confirm: true aufrufen. Ist der Eintrag Startseite, ' + . 'Beitragsseite oder in Menüs verlinkt, nennen Rückfrage und warnings das.'; } public function inputSchema(): array @@ -96,7 +99,12 @@ final class PostTrashAbility implements Ability $postId = (int) $post->ID; $title = (string) $post->post_title; if (($input['confirm'] ?? false) !== true) { - return Errors::confirmRequired(sprintf('"%s" (ID %d) in den Papierkorb legen?', $title, $postId)); + $impact = $post->post_status === 'trash' ? [] : $this->impact($post); + + return Errors::confirmRequired( + trim(sprintf('"%s" (ID %d) in den Papierkorb legen? %s', $title, $postId, implode(' ', $impact))), + $impact === [] ? [] : ['warnings' => $impact] + ); } if ($post->post_status === 'trash') { @@ -113,6 +121,7 @@ final class PostTrashAbility implements Ability ); } + $impact = $this->impact($post); $trashed = StatusWrite::run( static fn () => wp_trash_post($postId), $this->name(), @@ -128,7 +137,7 @@ final class PostTrashAbility implements Ability } // The change is saved – a failure of the change log from here on is a warning only. - $change = (new PostChangeResult($this->name(), $this->log, $postId)) + $change = (new PostChangeResult($this->name(), $this->log, $postId, 'die Änderung', $impact)) ->log((string) $post->post_type, sprintf('"%s" in den Papierkorb gelegt', $title)); $summary = sprintf('"%s" liegt im Papierkorb und ist dort wiederherstellbar.', $title); @@ -138,6 +147,63 @@ final class PostTrashAbility implements Ability ->toArray(); } + /** + * What visibly breaks when $post is in the trash: the static front page / posts page + * setting points to it, or menus link it (WordPress hides such menu items while the + * entry is trashed). + * + * @return list + */ + private function impact(WP_Post $post): array + { + $postId = (int) $post->ID; + $title = (string) $post->post_title; + $impact = []; + if (get_option('show_on_front') === 'page') { + if ((int) get_option('page_on_front') === $postId) { + $impact[] = sprintf( + '"%s" ist als Startseite der Website eingestellt; im Papierkorb ist sie für Besucher nicht ' + . 'mehr erreichbar – unter Einstellungen → Lesen eine andere Startseite wählen.', + $title + ); + } + + if ((int) get_option('page_for_posts') === $postId) { + $impact[] = sprintf( + '"%s" ist als Beitragsseite der Website eingestellt; im Papierkorb ist die Beitragsübersicht ' + . 'nicht mehr erreichbar – unter Einstellungen → Lesen eine andere Beitragsseite wählen.', + $title + ); + } + } + + $menus = $this->linkingMenus($postId); + if ($menus !== []) { + $impact[] = sprintf( + '"%s" ist in %s %s verlinkt; WordPress blendet diese Menüeinträge aus, solange der Eintrag im ' + . 'Papierkorb liegt.', + $title, + count($menus) === 1 ? 'dem Menü' : 'den Menüs', + implode(', ', array_map(static fn (string $name): string => '"' . $name . '"', $menus)) + ); + } + + return $impact; + } + + /** @return list Names of the menus with an item linking $postId. */ + private function linkingMenus(int $postId): array + { + $items = wp_get_associated_nav_menu_items($postId, 'post_type'); + if (! is_array($items) || $items === []) { + return []; + } + + $names = wp_get_object_terms(array_values($items), 'nav_menu', ['fields' => 'names']); + + return is_array($names) ? array_values(array_unique(array_map('strval', $names))) : []; + } + /** @param array $input */ private function load(array $input): WP_Post|WP_Error { diff --git a/tests/Integration/wp-basis-smoke.sh b/tests/Integration/wp-basis-smoke.sh index 959c285..f44cf25 100644 --- a/tests/Integration/wp-basis-smoke.sh +++ b/tests/Integration/wp-basis-smoke.sh @@ -99,7 +99,15 @@ PAST=$(ability lit/post-schedule "{\"post_id\":$PAGE_ID,\"date\":\"2020-01-01 10 [ "$(error_code "$PAST")" = "validation_failed" ] || fail "past schedule accepted: $PAST" tool lit-post-publish "{\"post_id\":$PAGE_ID}" >/dev/null [ "$(wp post get "$PAGE_ID" --field=post_status)" = "publish" ] || fail "scheduled page did not publish now" -pass "publish/unpublish/schedule, past dates rejected" +PRIVATE=$(tool lit-content-create '{"post_type":"page","title":"LIT Smoke Privat"}') +PRIVATE_ID=$(echo "$PRIVATE" | jq -r '.changed[0].id // empty') +[ -n "$PRIVATE_ID" ] || fail "content-create (private): $PRIVATE" +CREATED_POSTS+=("$PRIVATE_ID") +wp post update "$PRIVATE_ID" --post_status=private >/dev/null +SCHEDULED_PRIVATE=$(ability lit/post-schedule "{\"post_id\":$PRIVATE_ID,\"date\":\"$FUTURE\"}") +echo "$SCHEDULED_PRIVATE" | jq -e '.ok == true and (.warnings | any(contains("ÖFFENTLICH")))' >/dev/null \ + || fail "scheduling a private page does not warn: $SCHEDULED_PRIVATE" +pass "publish/unpublish/schedule, past dates rejected, private schedule warns" # 6. Copy and replace (lit-content-update, lit/post-replace-with-copy: rev required) COPY=$(ability lit/post-duplicate "{\"post_id\":$PAGE_ID}") @@ -153,29 +161,44 @@ REFUSED=$(tool lit-content-update "{\"post_id\":$MISSED_ID,\"rev\":\"$MISSED_REV [ "$(wp post get "$MISSED_ID" --field=post_status)" = "future" ] || fail "missed schedule got published" pass "content-update refuses a missed schedule instead of publishing it" -# 9. Menus +# 9. Menus (lit/menu-set-items: menu_rev from lit/menu-get required) MENU=$(ability lit/menu-create '{"name":"LIT Smoke Menü"}') MENU_ID=$(echo "$MENU" | jq -r '.menu_id // empty') [ -n "$MENU_ID" ] || fail "menu-create: $MENU" -ability lit/menu-set-items "{\"menu_id\":$MENU_ID,\"items\":[{\"type\":\"post\",\"object_id\":$PAGE_ID,\"children\":[{\"type\":\"custom\",\"url\":\"/kontakt\",\"title\":\"Kontakt\"}]}]}" \ - | jq -e '.ok == true' >/dev/null || fail "menu-set-items (tree)" +MENU_REV=$(ability lit/menu-get "{\"menu_id\":$MENU_ID}" | jq -r '.menu_rev // empty') +[ -n "$MENU_REV" ] || fail "menu-get lacks menu_rev" +NOREV=$(ability lit/menu-set-items "{\"menu_id\":$MENU_ID,\"menu_rev\":\"000000000000\",\"items\":[]}") +[ "$(error_code "$NOREV")" = "rev_mismatch" ] || fail "stale menu_rev accepted: $NOREV" +SET=$(ability lit/menu-set-items "{\"menu_id\":$MENU_ID,\"menu_rev\":\"$MENU_REV\",\"items\":[{\"type\":\"post\",\"object_id\":$PAGE_ID,\"children\":[{\"type\":\"custom\",\"url\":\"/kontakt\",\"title\":\"Kontakt\"}]}]}") +echo "$SET" | jq -e '.ok == true and (.menu_rev | type) == "string"' >/dev/null || fail "menu-set-items (tree): $SET" +STALE_MENU=$(ability lit/menu-set-items "{\"menu_id\":$MENU_ID,\"menu_rev\":\"$MENU_REV\",\"items\":[]}") +[ "$(error_code "$STALE_MENU")" = "rev_mismatch" ] || fail "outdated menu_rev accepted: $STALE_MENU" TREE=$(ability lit/menu-get "{\"menu_id\":$MENU_ID}") +[ "$(echo "$TREE" | jq -r '.menu_rev')" = "$(echo "$SET" | jq -r '.menu_rev')" ] || fail "menu_rev of set-items differs from menu-get" CHILD_ID=$(echo "$TREE" | jq -r '.items[0].children[0].id // empty') [ "$(echo "$TREE" | jq -r '.items[0].children[0].title')" = "Kontakt" ] || fail "menu tree: $TREE" -UNCHANGED_ARGS=$(jq -cn --argjson id "$MENU_ID" --argjson items "$(echo "$TREE" | jq -c '.items')" '{menu_id: $id, items: $items}') +UNCHANGED_ARGS=$(echo "$TREE" | jq -c --argjson id "$MENU_ID" '{menu_id: $id, menu_rev: .menu_rev, items: .items}') UNCHANGED=$(ability lit/menu-set-items "$UNCHANGED_ARGS") echo "$UNCHANGED" | jq -e '.summary | contains("keine Änderung")' >/dev/null || fail "menu no-op: $UNCHANGED" -REMOVE=$(ability lit/menu-set-items "{\"menu_id\":$MENU_ID,\"operations\":[{\"op\":\"remove\",\"id\":$CHILD_ID}]}") +MENU_REV=$(echo "$UNCHANGED" | jq -r '.menu_rev') +REMOVE=$(ability lit/menu-set-items "{\"menu_id\":$MENU_ID,\"menu_rev\":\"$MENU_REV\",\"operations\":[{\"op\":\"remove\",\"id\":$CHILD_ID}]}") [ "$(error_code "$REMOVE")" = "confirm_required" ] || fail "menu removal without confirm: $REMOVE" -ability lit/menu-set-items "{\"menu_id\":$MENU_ID,\"operations\":[{\"op\":\"remove\",\"id\":$CHILD_ID}],\"confirm\":true}" \ +ability lit/menu-set-items "{\"menu_id\":$MENU_ID,\"menu_rev\":\"$MENU_REV\",\"operations\":[{\"op\":\"remove\",\"id\":$CHILD_ID}],\"confirm\":true}" \ | jq -e '(.previous_items[0].children | length) == 1 and (.items[0].children | length) == 0' >/dev/null \ || fail "menu removal with confirm" LOCATION=$(ability lit/menu-list '{}' | jq -r '.locations[0].location // empty') if [ -n "$LOCATION" ]; then ability lit/menu-assign-location "{\"location\":\"$LOCATION\",\"menu_id\":$MENU_ID}" | jq -e '.ok == true' >/dev/null \ || fail "menu-assign-location" + UNASSIGN=$(ability lit/menu-assign-location "{\"location\":\"$LOCATION\",\"menu_id\":0}") + [ "$(error_code "$UNASSIGN")" = "confirm_required" ] || fail "unassign without confirm: $UNASSIGN" + ability lit/menu-assign-location "{\"location\":\"$LOCATION\",\"menu_id\":0,\"confirm\":true}" \ + | jq -e '.summary | contains("LIT Smoke Menü")' >/dev/null || fail "unassign with confirm does not name the menu" fi -pass "menu create, tree, no-op resend, operations with confirm, location" +TRASH_LINKED=$(ability lit/post-trash "{\"post_id\":$PAGE_ID,\"confirm\":true}") +echo "$TRASH_LINKED" | jq -e '.changed[0].action == "trashed" and (.warnings | any(contains("LIT Smoke Menü")))' >/dev/null \ + || fail "trashing a menu-linked page does not name the menu: $TRASH_LINKED" +pass "menu create, menu_rev lock, tree, no-op resend, operations with confirm, location (unassign with confirm), trash warns about menu link" # 10. WordPress settings (whitelist) ability lit/wp-settings-get '{"group":"general"}' | jq -e '.settings[] | select(.key == "blogname")' >/dev/null \ diff --git a/tests/Unit/Abilities/ErrorsTest.php b/tests/Unit/Abilities/ErrorsTest.php index 8a63e63..9eda029 100644 --- a/tests/Unit/Abilities/ErrorsTest.php +++ b/tests/Unit/Abilities/ErrorsTest.php @@ -67,6 +67,30 @@ final class ErrorsTest extends TestCase self::assertStringContainsString('erneut', $payload['hint']); } + public function testWriteFailedCanDescribeWhatWasKept(): void + { + $error = Errors::writeFailed( + 'Felder konnten nicht gespeichert werden.', + [], + null, + 'Die Änderung wurde nicht gespeichert (Revision 811 bleibt erhalten).' + ); + + $message = json_decode($error->get_error_message(), true)['message']; + self::assertStringNotContainsString('Nichts wurde gespeichert', $message); + self::assertStringEndsWith('Die Änderung wurde nicht gespeichert (Revision 811 bleibt erhalten).', $message); + } + + public function testRevMismatchCanNameItsOwnObjectAndReadTool(): void + { + $error = Errors::revMismatch('Das Menü wurde geändert.', 'Mit lit/menu-get neu lesen.'); + + self::assertSame('lit_rev_mismatch', $error->get_error_code()); + self::assertSame('Das Menü wurde geändert.', json_decode($error->get_error_message(), true)['message']); + self::assertSame('Mit lit/menu-get neu lesen.', $error->get_error_data()['hint']); + self::assertStringContainsString('lit/content-get', Errors::revMismatch()->get_error_data()['hint']); + } + public function testPartialWriteNamesWhatMayHaveBeenSavedAndWarnsAgainstRetrying(): void { $error = Errors::partialWrite('Felder konnten nicht gespeichert werden.', 5, 811); diff --git a/tests/Unit/Abilities/RevAndJsonMapTest.php b/tests/Unit/Abilities/RevAndJsonMapTest.php index bce6cf1..b91c7cd 100644 --- a/tests/Unit/Abilities/RevAndJsonMapTest.php +++ b/tests/Unit/Abilities/RevAndJsonMapTest.php @@ -49,6 +49,31 @@ final class RevAndJsonMapTest extends TestCase self::assertFalse(Rev::matches(['rev' => 123], $post)); } + public function testMenuRevCoversTheComparedFieldsOfEveryItem(): void + { + $item = static fn (array $overrides = []): object => (object) array_merge([ + 'ID' => 10, + 'menu_item_parent' => '0', + 'menu_order' => 1, + 'title' => 'Start', + 'url' => '/', + 'object' => 'page', + 'object_id' => '110', + 'classes' => [''], + ], $overrides); + $rev = Rev::ofMenu([$item()]); + + self::assertMatchesRegularExpression('/^[0-9a-f]{12}$/', $rev); + self::assertSame($rev, Rev::ofMenu([$item()])); + self::assertSame($rev, Rev::ofMenu([$item(['classes' => ['x']])]), 'not compared by menu-set-items'); + self::assertNotSame($rev, Rev::ofMenu([])); + self::assertNotSame($rev, Rev::ofMenu([$item(), $item(['ID' => 11])])); + foreach (['ID' => 12, 'menu_item_parent' => '9', 'menu_order' => 2, 'title' => 'Home', 'url' => '/x', + 'object' => 'post', 'object_id' => '111'] as $key => $value) { + self::assertNotSame($rev, Rev::ofMenu([$item([$key => $value])]), $key); + } + } + public function testEmptyMapBecomesJsonObject(): void { self::assertInstanceOf(stdClass::class, JsonMap::of([])); diff --git a/tests/Unit/Abilities/WriteFailedTest.php b/tests/Unit/Abilities/WriteFailedTest.php index 7babd6a..e062e62 100644 --- a/tests/Unit/Abilities/WriteFailedTest.php +++ b/tests/Unit/Abilities/WriteFailedTest.php @@ -56,6 +56,17 @@ final class WriteFailedTest extends TestCase self::assertSame(3, $error->get_error_data()['menu_id']); } + public function testRolledBackStateReplacesNothingWasSavedOfWriteFailedOnly(): void + { + $state = 'Die Änderung wurde nicht gespeichert (Sicherung 88 bleibt erhalten).'; + $clean = (new WriteFailed('x', true, rolledBackState: $state))->toError(); + $partial = (new WriteFailed('x', false, rolledBackState: $state))->toError(); + + self::assertStringContainsString($state, $clean->get_error_message()); + self::assertStringNotContainsString('Nichts wurde gespeichert', $clean->get_error_message()); + self::assertStringNotContainsString($state, $partial->get_error_message()); + } + public function testCleanRollbackKeepsItsDetails(): void { $error = (new WriteFailed('Nicht übernommen.', true, details: ['backup_id' => 88]))->toError(); diff --git a/tests/Unit/Guides/GuideRepositoryTest.php b/tests/Unit/Guides/GuideRepositoryTest.php index fd9450d..b1f1d17 100644 --- a/tests/Unit/Guides/GuideRepositoryTest.php +++ b/tests/Unit/Guides/GuideRepositoryTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace LIT\MCP\Tests\Unit\Guides; +use Brain\Monkey\Filters; use LIT\MCP\Guides\GuideRepository; use LIT\MCP\Tests\Unit\TestCase; @@ -48,6 +49,40 @@ final class GuideRepositoryTest extends TestCase ]; } + public function testFilesAreTheDefaultWhenNoFilterIsRegistered(): void + { + Filters\expectApplied('lit_mcp_guides')->once()->with([])->andReturn([]); + + self::assertSame(['divi-shortform', 'overview'], $this->guides->topics()); + self::assertStringContainsString('Testinhalt Kurzform', (string) $this->guides->get('divi-shortform')); + } + + public function testTheFilterAddsAndOverridesTopicsAndIgnoresInvalidNames(): void + { + Filters\expectApplied('lit_mcp_guides')->andReturn([ + 'site-rules' => "# Regeln\nas-is", + 'overview' => 'Eigene Übersicht', + '../../wp-config' => 'nope', + 'Upper' => 'nope', + 'not-string' => ['nope'], + 7 => 'nope', + ]); + + self::assertSame(['divi-shortform', 'overview', 'site-rules'], $this->guides->topics()); + self::assertSame("# Regeln\nas-is", $this->guides->get('site-rules')); + self::assertSame('Eigene Übersicht', $this->guides->get('overview')); + self::assertNull($this->guides->get('../../wp-config')); + self::assertNull($this->guides->get('Upper')); + self::assertNull($this->guides->get('not-string')); + } + + public function testANonArrayFilterResultIsIgnored(): void + { + Filters\expectApplied('lit_mcp_guides')->andReturn('kaputt'); + + self::assertSame(['divi-shortform', 'overview'], $this->guides->topics()); + } + public function testMissingDirectoryYieldsNoTopics(): void { self::assertSame([], (new GuideRepository('/nonexistent/dir'))->topics()); diff --git a/tests/Unit/Integrations/WordPress/Content/ContentUpdateAbilityTest.php b/tests/Unit/Integrations/WordPress/Content/ContentUpdateAbilityTest.php index 2f8aed8..9db7dd5 100644 --- a/tests/Unit/Integrations/WordPress/Content/ContentUpdateAbilityTest.php +++ b/tests/Unit/Integrations/WordPress/Content/ContentUpdateAbilityTest.php @@ -116,7 +116,9 @@ final class ContentUpdateAbilityTest extends TestCase ->execute(['post_id' => 5, 'rev' => Rev::ofPost($this->post), 'content' => '

Neu

']); self::assertSame('lit_unsupported', $result->get_error_code()); - self::assertStringContainsString('lit-divi-outline', $result->get_error_message()); + self::assertStringNotContainsString('lit-divi', $result->get_error_message()); + self::assertStringContainsString('Divi-Werkzeuge folgen in einer späteren Version; bis dahin im Divi-Builder ' + . 'bearbeiten.', $result->get_error_data()['hint']); } public function testNothingToChangeIsAValidationError(): void @@ -231,6 +233,9 @@ final class ContentUpdateAbilityTest extends TestCase self::assertTrue($failure->rolledBack); self::assertSame('lit_write_failed', $failure->toError()->get_error_code()); + $message = $failure->toError()->get_error_message(); + self::assertStringNotContainsString('Nichts wurde gespeichert', $message); + self::assertStringContainsString('Die Änderung wurde nicht gespeichert (Revision 811 bleibt erhalten).', $message); self::assertSame([ ['post_title' => 'Unser Team', 'post_name' => 'unser-team', 'ID' => 5], ['post_name' => 'team', 'ID' => 5], diff --git a/tests/Unit/Integrations/WordPress/Content/PostPresenterTest.php b/tests/Unit/Integrations/WordPress/Content/PostPresenterTest.php index 47d4ca5..cd1b3d9 100644 --- a/tests/Unit/Integrations/WordPress/Content/PostPresenterTest.php +++ b/tests/Unit/Integrations/WordPress/Content/PostPresenterTest.php @@ -87,7 +87,8 @@ final class PostPresenterTest extends TestCase self::assertTrue($full['divi']); self::assertNull($full['content']); self::assertNull($full['featured_image']); - self::assertStringContainsString('lit-divi-outline', $full['hints'][0]); + self::assertStringNotContainsString('lit-divi', $full['hints'][0]); + self::assertStringContainsString('Divi-Werkzeuge folgen in einer späteren Version', $full['hints'][0]); self::assertInstanceOf(stdClass::class, $full['terms']); self::assertInstanceOf(stdClass::class, $full['fields']); self::assertSame(Rev::ofPost($post), $full['rev']); diff --git a/tests/Unit/Integrations/WordPress/Menus/MenuAssignLocationAbilityTest.php b/tests/Unit/Integrations/WordPress/Menus/MenuAssignLocationAbilityTest.php index b76a71e..9ceccca 100644 --- a/tests/Unit/Integrations/WordPress/Menus/MenuAssignLocationAbilityTest.php +++ b/tests/Unit/Integrations/WordPress/Menus/MenuAssignLocationAbilityTest.php @@ -18,7 +18,11 @@ final class MenuAssignLocationAbilityTest extends TestCase Functions\when('get_registered_nav_menus')->justReturn(['primary-menu' => 'Hauptmenü']); Functions\when('get_nav_menu_locations')->justReturn(['primary-menu' => 3]); Functions\when('wp_get_nav_menu_object')->alias( - static fn (int $id) => $id === 8 ? (object) ['term_id' => 8, 'name' => 'Neu'] : false + static fn (int $id) => match ($id) { + 8 => (object) ['term_id' => 8, 'name' => 'Neu'], + 3 => (object) ['term_id' => 3, 'name' => 'Hauptmenü'], + default => false, + } ); } @@ -42,7 +46,21 @@ final class MenuAssignLocationAbilityTest extends TestCase self::assertSame(6, $result['log_id']); } - public function testZeroRemovesTheAssignment(): void + public function testRemovingAnAssignmentNeedsConfirmation(): void + { + Functions\expect('set_theme_mod')->never(); + + $result = (new MenuAssignLocationAbility(Mockery::mock(ChangeLog::class))) + ->execute(['location' => 'primary-menu', 'menu_id' => 0]); + + self::assertSame('lit_confirm_required', $result->get_error_code()); + self::assertStringContainsString( + '"Hauptmenü" (ID 3)', + json_decode($result->get_error_message(), true)['message'] + ); + } + + public function testZeroRemovesTheAssignmentAndNamesTheRemovedMenu(): void { Functions\expect('set_theme_mod')->once()->with('nav_menu_locations', []); $log = Mockery::mock(ChangeLog::class); @@ -51,16 +69,40 @@ final class MenuAssignLocationAbilityTest extends TestCase 'lit/menu-assign-location', 'menu_location', 'primary-menu', - 'Zuweisung der Position primary-menu entfernt' + 'Menü "Hauptmenü" (ID 3) von der Position primary-menu entfernt' ) ->andReturn(7); - $result = (new MenuAssignLocationAbility($log))->execute(['location' => 'primary-menu', 'menu_id' => 0]); + $result = (new MenuAssignLocationAbility($log)) + ->execute(['location' => 'primary-menu', 'menu_id' => 0, 'confirm' => true]); self::assertSame('unassigned', $result['changed'][0]['action']); + self::assertSame(3, $result['previous_menu_id']); + self::assertStringContainsString('"Hauptmenü" (ID 3)', $result['summary']); self::assertSame(7, $result['log_id']); } + public function testRemovingFromAnEmptyLocationNeedsNoConfirmation(): void + { + Functions\when('get_nav_menu_locations')->justReturn([]); + Functions\expect('set_theme_mod')->once()->with('nav_menu_locations', []); + $log = Mockery::mock(ChangeLog::class); + $log->allows('record')->andReturn(8); + + $result = (new MenuAssignLocationAbility($log))->execute(['location' => 'primary-menu', 'menu_id' => 0]); + + self::assertTrue($result['ok']); + self::assertNull($result['previous_menu_id']); + } + + public function testDescribesTheConfirmationForRemoval(): void + { + $ability = new MenuAssignLocationAbility(Mockery::mock(ChangeLog::class)); + + self::assertArrayHasKey('confirm', $ability->inputSchema()['properties']); + self::assertStringContainsString('confirm: true', $ability->description()); + } + public function testUnknownMenuIsNotFound(): void { Functions\expect('set_theme_mod')->never(); diff --git a/tests/Unit/Integrations/WordPress/Menus/MenuReadAbilitiesTest.php b/tests/Unit/Integrations/WordPress/Menus/MenuReadAbilitiesTest.php index 94beae2..d9d3a6f 100644 --- a/tests/Unit/Integrations/WordPress/Menus/MenuReadAbilitiesTest.php +++ b/tests/Unit/Integrations/WordPress/Menus/MenuReadAbilitiesTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace LIT\MCP\Tests\Unit\Integrations\WordPress\Menus; use Brain\Monkey\Functions; +use LIT\MCP\Abilities\Rev; use LIT\MCP\Integrations\WordPress\Menus\MenuGetAbility; use LIT\MCP\Integrations\WordPress\Menus\MenuListAbility; use LIT\MCP\Tests\Unit\TestCase; @@ -48,6 +49,8 @@ final class MenuReadAbilitiesTest extends TestCase self::assertSame('Hauptmenü', $result['name']); self::assertSame('Start', $result['items'][0]['title']); + self::assertSame(Rev::ofMenu([self::item(10, 0, 'Start')]), $result['menu_rev']); + self::assertContains('menu_rev', $ability->outputSchema()['required']); self::assertSame('lit_not_found', $ability->execute(['menu_id' => 9])->get_error_code()); } diff --git a/tests/Unit/Integrations/WordPress/Menus/MenuSetItemsAbilityTest.php b/tests/Unit/Integrations/WordPress/Menus/MenuSetItemsAbilityTest.php index 9888fc0..ea29135 100644 --- a/tests/Unit/Integrations/WordPress/Menus/MenuSetItemsAbilityTest.php +++ b/tests/Unit/Integrations/WordPress/Menus/MenuSetItemsAbilityTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace LIT\MCP\Tests\Unit\Integrations\WordPress\Menus; use Brain\Monkey\Functions; +use LIT\MCP\Abilities\Rev; use LIT\MCP\Abilities\WriteFailed; use LIT\MCP\ChangeLog\ChangeLog; use LIT\MCP\Integrations\WordPress\Menus\MenuOperations; @@ -26,14 +27,52 @@ final class MenuSetItemsAbilityTest extends TestCase Functions\when('wp_get_nav_menu_items')->justReturn([self::item(10, 0, 'Home', 'custom', '/')]); } + /** The menu_rev of the items wp_get_nav_menu_items() currently returns (what lit/menu-get would show). */ + private static function rev(): string + { + return Rev::ofMenu(wp_get_nav_menu_items(3)); + } + + public function testAStaleOrMissingMenuRevIsRefusedAndNothingIsWritten(): void + { + $writer = Mockery::mock(MenuWriter::class); + $writer->expects('apply')->never(); + $ability = new MenuSetItemsAbility($writer, new MenuOperations(), Mockery::mock(ChangeLog::class)); + + $stale = $ability->execute(['menu_id' => 3, 'menu_rev' => 'abcdefabcdef', 'items' => [['id' => 10]]]); + $missing = $ability->execute(['menu_id' => 3, 'items' => [['id' => 10]]]); + + self::assertSame('lit_rev_mismatch', $stale->get_error_code()); + self::assertStringContainsString('lit/menu-get', $stale->get_error_data()['hint']); + self::assertStringContainsString('Menü', $stale->get_error_message()); + self::assertSame('lit_rev_mismatch', $missing->get_error_code()); + self::assertContains('menu_rev', $ability->inputSchema()['required']); + self::assertStringContainsString('menu_rev', $ability->description()); + } + + public function testTheResultCarriesTheNewMenuRev(): void + { + $writer = Mockery::mock(MenuWriter::class); + $writer->allows('plan')->andReturn(['errors' => [], 'removals' => [], 'warnings' => []]); + $writer->allows('apply')->andReturn(['created' => 0, 'updated' => 1, 'removed' => 0]); + $log = Mockery::mock(ChangeLog::class); + $log->allows('record')->andReturn(30); + + $result = (new MenuSetItemsAbility($writer, new MenuOperations(), $log))->execute( + ['menu_id' => 3, 'menu_rev' => self::rev(), 'items' => [['id' => 10]]] + ); + + self::assertSame(self::rev(), $result['menu_rev']); + } + public function testItemsAndOperationsAreMutuallyExclusive(): void { $ability = new MenuSetItemsAbility(new MenuWriter(), new MenuOperations(), Mockery::mock(ChangeLog::class)); - self::assertSame('lit_validation_failed', $ability->execute(['menu_id' => 3])->get_error_code()); + self::assertSame('lit_validation_failed', $ability->execute(['menu_id' => 3, 'menu_rev' => self::rev()])->get_error_code()); self::assertSame( 'lit_validation_failed', - $ability->execute(['menu_id' => 3, 'items' => [], 'operations' => [['op' => 'remove', 'id' => 10]]]) + $ability->execute(['menu_id' => 3, 'menu_rev' => self::rev(), 'items' => [], 'operations' => [['op' => 'remove', 'id' => 10]]]) ->get_error_code() ); } @@ -52,7 +91,7 @@ final class MenuSetItemsAbilityTest extends TestCase Functions\expect('wp_delete_post')->never(); $ability = new MenuSetItemsAbility(new MenuWriter(), new MenuOperations(), Mockery::mock(ChangeLog::class)); - $result = $ability->execute(['menu_id' => 3, 'items' => []]); + $result = $ability->execute(['menu_id' => 3, 'menu_rev' => self::rev(), 'items' => []]); self::assertSame('lit_confirm_required', $result->get_error_code()); self::assertSame([['id' => 10, 'title' => 'Home']], $result->get_error_data()['removals']); @@ -66,7 +105,7 @@ final class MenuSetItemsAbilityTest extends TestCase $ability = new MenuSetItemsAbility(new MenuWriter(), new MenuOperations(), Mockery::mock(ChangeLog::class)); $result = $ability->execute([ - 'menu_id' => 3, + 'menu_id' => 3, 'menu_rev' => self::rev(), 'confirm' => true, 'items' => [['id' => 10], ['type' => 'custom', 'url' => 'javascript:alert(1)', 'title' => 'X']], ]); @@ -81,7 +120,7 @@ final class MenuSetItemsAbilityTest extends TestCase $writer->expects('apply')->never(); $ability = new MenuSetItemsAbility($writer, new MenuOperations(), Mockery::mock(ChangeLog::class)); - $result = $ability->execute(['menu_id' => 3, 'operations' => [['op' => 'move', 'id' => 99]]]); + $result = $ability->execute(['menu_id' => 3, 'menu_rev' => self::rev(), 'operations' => [['op' => 'move', 'id' => 99]]]); self::assertSame('lit_validation_failed', $result->get_error_code()); } @@ -95,7 +134,7 @@ final class MenuSetItemsAbilityTest extends TestCase $log->expects('record')->with('lit/menu-set-items', 'nav_menu', '3', Mockery::type('string'))->andReturn(21); $result = (new MenuSetItemsAbility($writer, new MenuOperations(), $log))->execute([ - 'menu_id' => 3, + 'menu_id' => 3, 'menu_rev' => self::rev(), 'operations' => [['op' => 'add', 'item' => ['type' => 'custom', 'url' => '/blog', 'title' => 'Blog']]], ]); @@ -116,7 +155,7 @@ final class MenuSetItemsAbilityTest extends TestCase $log->allows('record')->andReturn(22); $result = (new MenuSetItemsAbility($writer, new MenuOperations(), $log))->execute( - ['menu_id' => 3, 'items' => [], 'confirm' => true] + ['menu_id' => 3, 'menu_rev' => self::rev(), 'items' => [], 'confirm' => true] ); self::assertSame(10, $result['previous_items'][0]['id']); @@ -134,7 +173,7 @@ final class MenuSetItemsAbilityTest extends TestCase $log->expects('record')->never(); $result = (new MenuSetItemsAbility(new MenuWriter(), new MenuOperations(), $log))->execute( - ['menu_id' => 3, 'items' => MenuTree::build($items)] + ['menu_id' => 3, 'menu_rev' => self::rev(), 'items' => MenuTree::build($items)] ); self::assertSame('Menü "Hauptmenü": keine Änderung.', $result['summary']); @@ -151,7 +190,7 @@ final class MenuSetItemsAbilityTest extends TestCase $ability = new MenuSetItemsAbility($writer, new MenuOperations(), Mockery::mock(ChangeLog::class)); $result = $ability->execute( - ['menu_id' => 3, 'items' => [['type' => 'post', 'object_id' => 7]], 'allow_unpublished' => true] + ['menu_id' => 3, 'menu_rev' => self::rev(), 'items' => [['type' => 'post', 'object_id' => 7]], 'allow_unpublished' => true] ); self::assertSame('lit_validation_failed', $result->get_error_code()); @@ -169,7 +208,7 @@ final class MenuSetItemsAbilityTest extends TestCase $log = Mockery::mock(ChangeLog::class); $log->allows('record')->andReturn(24); $ability = new MenuSetItemsAbility(new MenuWriter(), new MenuOperations(), $log); - $input = ['menu_id' => 3, 'operations' => [['op' => 'add', 'item' => ['type' => 'post', 'object_id' => 7]]]]; + $input = ['menu_id' => 3, 'menu_rev' => self::rev(), 'operations' => [['op' => 'add', 'item' => ['type' => 'post', 'object_id' => 7]]]]; $refused = $ability->execute($input); $allowed = $ability->execute($input + ['allow_unpublished' => true]); @@ -190,7 +229,7 @@ final class MenuSetItemsAbilityTest extends TestCase $ability = new MenuSetItemsAbility(new MenuWriter(), new MenuOperations(), Mockery::mock(ChangeLog::class)); $result = $ability->execute([ - 'menu_id' => 3, + 'menu_id' => 3, 'menu_rev' => self::rev(), 'allow_unpublished' => true, 'operations' => [['op' => 'add', 'item' => ['type' => 'post', 'object_id' => 7]]], ]); @@ -209,7 +248,7 @@ final class MenuSetItemsAbilityTest extends TestCase $ability = new MenuSetItemsAbility($writer, new MenuOperations(), $log); $this->expectException(WriteFailed::class); - $ability->execute(['menu_id' => 3, 'items' => [['id' => 10]]]); + $ability->execute(['menu_id' => 3, 'menu_rev' => self::rev(), 'items' => [['id' => 10]]]); } public function testAPartialWriteIsLoggedAsPartial(): void @@ -222,7 +261,7 @@ final class MenuSetItemsAbilityTest extends TestCase $ability = new MenuSetItemsAbility($writer, new MenuOperations(), $log); $this->expectException(WriteFailed::class); - $ability->execute(['menu_id' => 3, 'items' => [['id' => 10]]]); + $ability->execute(['menu_id' => 3, 'menu_rev' => self::rev(), 'items' => [['id' => 10]]]); } public function testAChangeLogFailureIsOnlyAWarning(): void @@ -237,7 +276,7 @@ final class MenuSetItemsAbilityTest extends TestCase try { $result = (new MenuSetItemsAbility($writer, new MenuOperations(), $log))->execute( - ['menu_id' => 3, 'items' => [['id' => 10]]] + ['menu_id' => 3, 'menu_rev' => self::rev(), 'items' => [['id' => 10]]] ); } finally { ini_set('error_log', (string) $errorLog); @@ -253,7 +292,7 @@ final class MenuSetItemsAbilityTest extends TestCase Functions\when('current_user_can')->justReturn(false); $ability = new MenuSetItemsAbility(new MenuWriter(), new MenuOperations(), Mockery::mock(ChangeLog::class)); - self::assertSame('lit_forbidden', $ability->permission(['menu_id' => 3])->get_error_code()); + self::assertSame('lit_forbidden', $ability->permission(['menu_id' => 3, 'menu_rev' => self::rev()])->get_error_code()); } public function testIsDestructiveAndDescribesWhenConfirmIsNeeded(): void diff --git a/tests/Unit/Integrations/WordPress/PostGuardTest.php b/tests/Unit/Integrations/WordPress/PostGuardTest.php index f36fd87..ed06161 100644 --- a/tests/Unit/Integrations/WordPress/PostGuardTest.php +++ b/tests/Unit/Integrations/WordPress/PostGuardTest.php @@ -67,11 +67,40 @@ final class PostGuardTest extends TestCase self::assertTrue(PostGuard::missedSchedule(new WP_Post(['post_status' => 'future', 'post_date_gmt' => $past]))); self::assertFalse(PostGuard::missedSchedule(new WP_Post(['post_status' => 'future', 'post_date_gmt' => $future]))); self::assertFalse(PostGuard::missedSchedule(new WP_Post(['post_status' => 'draft', 'post_date_gmt' => $past]))); + Functions\when('get_gmt_from_date')->justReturn(''); self::assertFalse(PostGuard::missedSchedule( new WP_Post(['post_status' => 'future', 'post_date_gmt' => '0000-00-00 00:00:00']) )); } + public function testMissedScheduleIncludesTheLastMinuteBeforePublication(): void + { + // wp_update_post() publishes a future post on save when its date is within the next 60 seconds. + $in30s = gmdate('Y-m-d H:i:s', time() + 30); + $in5min = gmdate('Y-m-d H:i:s', time() + 300); + + self::assertTrue(PostGuard::missedSchedule(new WP_Post(['post_status' => 'future', 'post_date_gmt' => $in30s]))); + self::assertFalse(PostGuard::missedSchedule(new WP_Post(['post_status' => 'future', 'post_date_gmt' => $in5min]))); + } + + public function testMissedScheduleFallsBackToTheLocalDateWhenTheGmtDateIsZero(): void + { + Functions\when('get_gmt_from_date')->alias( + static fn (string $local): string => $local === '2020-01-01 10:00:00' ? '2020-01-01 09:00:00' : $local + ); + + self::assertTrue(PostGuard::missedSchedule(new WP_Post([ + 'post_status' => 'future', + 'post_date_gmt' => '0000-00-00 00:00:00', + 'post_date' => '2020-01-01 10:00:00', + ]))); + self::assertFalse(PostGuard::missedSchedule(new WP_Post([ + 'post_status' => 'future', + 'post_date_gmt' => '0000-00-00 00:00:00', + 'post_date' => '2099-01-01 10:00:00', + ]))); + } + public function testStatusStableRefusesAMissedScheduleWithAHint(): void { $post = new WP_Post(['ID' => 5, 'post_status' => 'future', 'post_date_gmt' => gmdate('Y-m-d H:i:s', time() - 60)]); diff --git a/tests/Unit/Integrations/WordPress/Revisions/RevisionRestoreAbilityTest.php b/tests/Unit/Integrations/WordPress/Revisions/RevisionRestoreAbilityTest.php index 97df141..7da15f0 100644 --- a/tests/Unit/Integrations/WordPress/Revisions/RevisionRestoreAbilityTest.php +++ b/tests/Unit/Integrations/WordPress/Revisions/RevisionRestoreAbilityTest.php @@ -171,6 +171,11 @@ final class RevisionRestoreAbilityTest extends TestCase ]); self::assertSame('lit_write_failed', $result->get_error_code()); + self::assertStringNotContainsString('Nichts wurde gespeichert', $result->get_error_message()); + self::assertStringContainsString( + 'Die Änderung wurde nicht gespeichert (Revision 813 bleibt erhalten).', + $result->get_error_message() + ); } public function testFailuresAfterTheWriteOnlyAddWarnings(): void diff --git a/tests/Unit/Integrations/WordPress/Status/PostReplaceWithCopyAbilityTest.php b/tests/Unit/Integrations/WordPress/Status/PostReplaceWithCopyAbilityTest.php index 6095927..e330e34 100644 --- a/tests/Unit/Integrations/WordPress/Status/PostReplaceWithCopyAbilityTest.php +++ b/tests/Unit/Integrations/WordPress/Status/PostReplaceWithCopyAbilityTest.php @@ -231,6 +231,9 @@ final class PostReplaceWithCopyAbilityTest extends TestCase self::assertTrue($e->rolledBack); self::assertSame('lit_write_failed', $e->toError()->get_error_code()); self::assertSame(88, $e->toError()->get_error_data()['backup_id']); + $message = $e->toError()->get_error_message(); + self::assertStringNotContainsString('Nichts wurde gespeichert', $message); + self::assertStringContainsString('Die Änderung wurde nicht gespeichert (Sicherung 88', $message); } } diff --git a/tests/Unit/Integrations/WordPress/Status/PostScheduleAbilityTest.php b/tests/Unit/Integrations/WordPress/Status/PostScheduleAbilityTest.php index d17e550..0e38ffc 100644 --- a/tests/Unit/Integrations/WordPress/Status/PostScheduleAbilityTest.php +++ b/tests/Unit/Integrations/WordPress/Status/PostScheduleAbilityTest.php @@ -54,6 +54,33 @@ final class PostScheduleAbilityTest extends TestCase self::assertStringContainsString('2099-06-01 09:30', $result['summary']); } + public function testWarnsThatAPrivatePostBecomesPublic(): void + { + Functions\when('get_post')->justReturn(new WP_Post(['ID' => 5, 'post_type' => 'post', 'post_title' => 'Intern', 'post_status' => 'private'])); + Functions\when('wp_update_post')->justReturn(5); + Functions\when('get_post_status')->justReturn('future'); + $log = Mockery::mock(ChangeLog::class); + $log->allows('record')->andReturn(4); + + $result = $this->ability($log)->execute(['post_id' => 5, 'date' => '2099-06-01 09:30']); + + self::assertCount(1, $result['warnings']); + self::assertStringContainsString('öffentlich', $result['warnings'][0]); + self::assertStringContainsString('2099-06-01 09:30', $result['warnings'][0]); + } + + public function testADraftGetsNoPrivacyWarning(): void + { + Functions\when('wp_update_post')->justReturn(5); + Functions\when('get_post_status')->justReturn('future'); + $log = Mockery::mock(ChangeLog::class); + $log->allows('record')->andReturn(4); + + $result = $this->ability($log)->execute(['post_id' => 5, 'date' => '2099-06-01 09:30']); + + self::assertSame([], $result['warnings']); + } + public function testAHookThrowingDuringTheWriteIsAPartialWrite(): void { Functions\when('wp_update_post')->alias(static function (): void { @@ -95,4 +122,18 @@ final class PostScheduleAbilityTest extends TestCase self::assertStringContainsString('Zukunft', $past->get_error_message()); self::assertSame('lit_validation_failed', $impossible->get_error_code()); } + + public function testADateWithinTheNextMinuteIsRejectedBecauseWordPressWouldPublishAtOnce(): void + { + Functions\expect('wp_update_post')->never(); + // The start of the next minute: always in the future, but at most 60 seconds away. + $soon = (new \DateTimeImmutable('@' . (intdiv(time(), 60) * 60 + 60))) + ->setTimezone(new DateTimeZone('Europe/Berlin')); + Functions\when('get_post_status')->justReturn('future'); + + $result = $this->ability(Mockery::mock(ChangeLog::class)) + ->execute(['post_id' => 5, 'date' => $soon->format('Y-m-d H:i')]); + + self::assertSame('lit_validation_failed', $result->get_error_code()); + } } diff --git a/tests/Unit/Integrations/WordPress/Status/PostTrashAbilityTest.php b/tests/Unit/Integrations/WordPress/Status/PostTrashAbilityTest.php index 4aefab5..8563a08 100644 --- a/tests/Unit/Integrations/WordPress/Status/PostTrashAbilityTest.php +++ b/tests/Unit/Integrations/WordPress/Status/PostTrashAbilityTest.php @@ -16,6 +16,19 @@ use WP_Post; final class PostTrashAbilityTest extends TestCase { + protected function setUp(): void + { + parent::setUp(); + $this->options([]); + Functions\when('wp_get_associated_nav_menu_items')->justReturn([]); + } + + /** @param array $options */ + private function options(array $options): void + { + Functions\when('get_option')->alias(static fn (string $name, mixed $default = false) => $options[$name] ?? $default); + } + private function ability(ChangeLog $log): PostTrashAbility { Functions\when('get_post')->justReturn(new WP_Post(['ID' => 5, 'post_type' => 'page', 'post_title' => 'Alt', 'post_status' => 'publish'])); @@ -93,6 +106,51 @@ final class PostTrashAbilityTest extends TestCase self::assertStringContainsString('bereits im Papierkorb', $result['summary']); } + public function testWarnsWhenTrashingTheFrontPageOrThePostsPage(): void + { + $this->options(['show_on_front' => 'page', 'page_on_front' => '5', 'page_for_posts' => '9']); + Functions\when('wp_trash_post')->justReturn(new WP_Post(['ID' => 5])); + $log = Mockery::mock(ChangeLog::class); + $log->allows('record')->andReturn(3); + $ability = $this->ability($log); + + $confirm = $ability->execute(['post_id' => 5]); + $result = $ability->execute(['post_id' => 5, 'confirm' => true]); + + self::assertStringContainsString('Startseite', $confirm->get_error_message()); + self::assertCount(1, $result['warnings']); + self::assertStringContainsString('Startseite', $result['warnings'][0]); + self::assertTrue($result['ok']); + + $this->options(['show_on_front' => 'page', 'page_on_front' => '9', 'page_for_posts' => '5']); + self::assertStringContainsString('Beitragsseite', $ability->execute(['post_id' => 5, 'confirm' => true])['warnings'][0]); + + $this->options(['show_on_front' => 'posts', 'page_on_front' => '5']); + self::assertSame([], $ability->execute(['post_id' => 5, 'confirm' => true])['warnings']); + } + + public function testWarnsAndNamesTheMenusThatLinkThePost(): void + { + Functions\when('wp_get_associated_nav_menu_items')->alias( + static fn (int $id, string $type): array => $id === 5 && $type === 'post_type' ? [40, 41] : [] + ); + Functions\when('wp_get_object_terms')->alias( + static fn (array $ids, string $taxonomy, array $args): array => + $ids === [40, 41] && $taxonomy === 'nav_menu' && $args === ['fields' => 'names'] + ? ['Hauptmenü', 'Footer', 'Hauptmenü'] + : [] + ); + Functions\when('wp_trash_post')->justReturn(new WP_Post(['ID' => 5])); + $log = Mockery::mock(ChangeLog::class); + $log->allows('record')->andReturn(3); + + $result = $this->ability($log)->execute(['post_id' => 5, 'confirm' => true]); + + self::assertCount(1, $result['warnings']); + self::assertStringContainsString('"Hauptmenü", "Footer"', $result['warnings'][0]); + self::assertSame(1, substr_count($result['warnings'][0], 'Hauptmenü')); + } + public function testIsDestructiveAndIndirect(): void { $ability = $this->ability(Mockery::mock(ChangeLog::class));