From 2b7638658a02f4cebd945bd7fe777153e955626b Mon Sep 17 00:00:00 2001 From: rahulwalunje Date: Thu, 6 Aug 2026 02:34:07 +0530 Subject: [PATCH 1/7] Cloud libraries: include a page's companion posts on save/import (#518) A page can reference companion posts it needs to render (e.g. a design system via _fl_ds_ref). Previously only the page uploaded to a cloud library, so it arrived at the destination with a dangling reference and no styling. Assistant stays generic and the companion knowledge lives in the plugin that owns the relationship, via two filters mirroring the #517 fl_assistant_post_types_known pattern: - save_to_library() uploads companions first (fl_assistant_library_companion_posts), $seen-deduped, and records their cloud ids on the page item as _fl_asst_companion_items. get_save_data() gains a $with_screenshot flag so companions that never render (a design system) skip a wasted headless capture. - import_from_library() is refactored around a reusable, post-type-agnostic import_item(); import_companions_from_library() reads the recorded ids from the fetched item (not the just-written post meta, which a raw-INSERT leaves stale in cache), pulls each, skips any a plugin reports already present via fl_assistant_library_companion_exists, creates the rest, and strips the linkage meta. Save-only for now; sync_to_library is untouched. Co-Authored-By: Claude Opus 4.8 --- .../Libraries/LibraryItemPostController.php | 198 +++++++++++++++--- 1 file changed, 173 insertions(+), 25 deletions(-) diff --git a/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php b/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php index 242a5436..0a391928 100644 --- a/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php +++ b/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php @@ -13,6 +13,14 @@ class LibraryItemPostController extends ControllerAbstract { + /** + * Meta key stamped on a primary library item recording the cloud item ids of + * its companions, so import can pull them and resolve cross-references. Kept + * in meta (not a dedicated field) so it round-trips through the cloud store + * with no API change; stripped from the page after import. + */ + const COMPANION_ITEMS_META = '_fl_asst_companion_items'; + protected $posts; /** @@ -226,9 +234,13 @@ public function preview_library_post( $request ) { * * @param object $request * @param object $post + * @param bool $with_screenshot Whether to capture a front-end screenshot. + * Companion posts that never render on the + * front end (e.g. a design system) pass false + * to skip a wasteful headless capture. * @return array */ - public function get_save_data( $request, $post ) { + public function get_save_data( $request, $post, $with_screenshot = true ) { $data = [ 'name' => $post->post_title, 'type' => 'post', @@ -251,7 +263,7 @@ public function get_save_data( $request, $post ) { 'media' => [ 'attachments' => $this->get_post_image_paths( $post ), ], - 'screenshot' => $this->get_post_screenshot( $request, $post ), + 'screenshot' => $with_screenshot ? $this->get_post_screenshot( $request, $post ) : null, ]; $thumbnail = get_attached_file( get_post_thumbnail_id( $post ) ); @@ -275,10 +287,18 @@ public function save_to_library( $request ) { $post = get_post( $id ); $client = new CloudClient; - $response = $client->libraries->create_item( - $library_id, - $this->get_save_data( $request, $post ) - ); + // Upload companions first so their cloud ids can be recorded on the + // primary item; import reads them to pull the companions and resolve + // the primary post's cross-references at the destination. + $companion_ids = $this->save_companions_to_library( $request, $post, $library_id, $client ); + + $data = $this->get_save_data( $request, $post ); + + if ( $companion_ids ) { + $data['post_data']['meta'][ self::COMPANION_ITEMS_META ] = [ wp_json_encode( $companion_ids ) ]; + } + + $response = $client->libraries->create_item( $library_id, $data ); if (isset($response->success) && $response->success === false) { return new \WP_Error( 'API Error', $response->message, [ 'status' => 400 ] ); @@ -287,6 +307,43 @@ public function save_to_library( $request ) { return $response; } + /** + * Uploads any companion posts a primary post depends on to the same library. + * + * Plugins declare companions via the `fl_assistant_library_companion_posts` + * filter (mirroring the `fl_assistant_post_types_known` picker filter), so + * Assistant stays generic and the companion knowledge lives in the plugin + * that owns the relationship. Companions are uploaded as their own library + * items; their cloud ids are returned so the primary item can record them. + * + * @param object $request + * @param object $post + * @param int $library_id + * @param CloudClient $client + * @return array Cloud item ids of the uploaded companions. + */ + protected function save_companions_to_library( $request, $post, $library_id, $client ) { + $companions = apply_filters( 'fl_assistant_library_companion_posts', [], $post, $library_id ); + $seen = []; + $ids = []; + + foreach ( $companions as $companion_post ) { + if ( ! $companion_post instanceof \WP_Post || isset( $seen[ $companion_post->ID ] ) ) { + continue; + } + $seen[ $companion_post->ID ] = true; + $response = $client->libraries->create_item( + $library_id, + $this->get_save_data( $request, $companion_post, false ) + ); + if ( isset( $response->id ) ) { + $ids[] = $response->id; + } + } + + return $ids; + } + /** * Replaces a library post with a post on this site. * @@ -333,21 +390,54 @@ public function import_from_library( $request ) { $client = new CloudClient; $item = $client->libraries->get_item( $item->id ); - $registered_post_types = get_post_types(); + $result = $this->import_item( $item ); - if ( ! in_array( $item->data->post->post_type, $registered_post_types ) ) { + if ( is_wp_error( $result ) ) { + if ( 'post_type_not_registered' === $result->get_error_code() ) { + return rest_ensure_response( + [ + 'error' => true, + 'error_code' => 'post_type_not_registered', + 'post_type' => $result->get_error_data()['post_type'], + ] + ); + } return rest_ensure_response( [ 'error' => true, - 'error_code' => 'post_type_not_registered', - 'post_type' => $item->data->post->post_type, ] ); } + $this->import_companions_from_library( $item, $result, $client ); + + return rest_ensure_response( + $this->posts->transform( + get_post( $result ) + ) + ); + } + + /** + * Creates a local post from a fetched cloud library item. + * + * Shared by the import endpoint and companion import so both create posts + * through one path. Post-type-agnostic: meta (including any identity meta a + * companion carries) and terms are copied verbatim. + * + * @param object $item Fetched cloud library item (with `data->post/meta/terms`). + * @return int|\WP_Error New post id, or an error to be mapped by the caller. + */ + protected function import_item( $item ) { + if ( ! in_array( $item->data->post->post_type, get_post_types(), true ) ) { + return new \WP_Error( + 'post_type_not_registered', + 'Post type is not registered on this site.', + [ 'post_type' => $item->data->post->post_type ] + ); + } + $post_data = $item->data->post; - $meta_data = $item->data->meta; - $term_data = $item->data->terms; $new_post_id = wp_insert_post( [ @@ -362,26 +452,84 @@ public function import_from_library( $request ) { 'post_status' => 'publish', 'post_title' => $post_data->post_title, 'post_type' => $post_data->post_type, - ] + ], + true ); if ( is_wp_error( $new_post_id ) ) { - return rest_ensure_response( - [ - 'error' => true, - ] - ); + return $new_post_id; } - $this->import_post_meta_from_library( $new_post_id, $meta_data ); - $this->import_post_terms_from_library( $new_post_id, $term_data ); + $this->import_post_meta_from_library( $new_post_id, $item->data->meta ); + $this->import_post_terms_from_library( $new_post_id, $item->data->terms ); $this->regenerate_builder_cache( $new_post_id, $item ); - return rest_ensure_response( - $this->posts->transform( - get_post( $new_post_id ) - ) - ); + return $new_post_id; + } + + /** + * Imports the companion library items recorded on an imported primary post. + * + * The primary item carries companion cloud ids in `COMPANION_ITEMS_META` + * (stamped at upload). Each companion is pulled and created unless a plugin + * reports it already exists via `fl_assistant_library_companion_exists` — + * the dedup seam where DS-specific UUID matching lives, keeping Assistant + * generic. The linkage meta is stripped from the imported post afterward so a + * later re-save doesn't re-propagate stale ids. + * + * The ids are read from the fetched cloud item, not from the just-imported + * post's meta: import_post_meta_from_library() writes meta with a raw INSERT + * that leaves the meta cache stale, so a same-request get_post_meta() read + * would miss it. + * + * @param object $item Fetched cloud library item (the primary). + * @param int $post_id Imported primary post id. + * @param CloudClient $client + * @return void + */ + protected function import_companions_from_library( $item, $post_id, $client ) { + $companion_ids = $this->get_companion_item_ids( $item ); + + foreach ( $companion_ids as $companion_id ) { + $companion_item = $client->libraries->get_item( $companion_id ); + + if ( ! isset( $companion_item->data->post ) ) { + continue; + } + + $exists = apply_filters( 'fl_assistant_library_companion_exists', false, $companion_item ); + + if ( $exists ) { + continue; + } + + $this->import_item( $companion_item ); + } + + if ( $companion_ids ) { + delete_post_meta( $post_id, self::COMPANION_ITEMS_META ); + } + } + + /** + * Reads the companion cloud item ids recorded on a fetched library item. + * + * @param object $item Fetched cloud library item (with `data->meta`). + * @return array List of companion cloud item ids (empty when none recorded). + */ + protected function get_companion_item_ids( $item ) { + $meta = $item->data->meta ?? null; + $raw = ( $meta && isset( $meta->{self::COMPANION_ITEMS_META}[0] ) ) + ? $meta->{self::COMPANION_ITEMS_META}[0] + : ''; + + if ( ! $raw ) { + return []; + } + + $ids = json_decode( $raw, true ); + + return is_array( $ids ) ? array_map( 'absint', $ids ) : []; } /** From 069abc9de45eb9a513bab50fb2e3ab7948f85596 Mon Sep 17 00:00:00 2001 From: rahulwalunje Date: Thu, 6 Aug 2026 02:34:40 +0530 Subject: [PATCH 2/7] Cloud libraries: slash post content when importing a library item MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit wp_insert_post() unslashes its argument internally, but import_item() passed the fetched post data through unslashed. A design system item stores its CSS as JSON in post_content (with \n escapes), so the missing slash stripped every backslash and turned each \n into a literal 'n' — corrupting the stylesheet the design system builds from it (broken selectors like nn.bb-badge, mangled token/reset blocks) and leaving imported pages unstyled. wp_slash() the array passed to wp_insert_post() so the content survives the internal unslash intact. Not visible on regular pages because their builder data lives in meta (imported via a slash-safe path); it surfaced once #518 started importing design-system posts whose content is post_content JSON. Co-Authored-By: Claude Opus 4.8 --- .../Libraries/LibraryItemPostController.php | 33 +++++++++++-------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php b/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php index 0a391928..5499e9d2 100644 --- a/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php +++ b/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php @@ -439,20 +439,27 @@ protected function import_item( $item ) { $post_data = $item->data->post; + // wp_insert_post() unslashes the array internally, so the content must be + // slashed going in. A design system stores its CSS as JSON in post_content + // (with `\n` escapes); without this, wp_insert_post strips those + // backslashes and turns every `\n` into a literal `n`, corrupting the + // generated stylesheet. $new_post_id = wp_insert_post( - [ - 'comment_status' => $post_data->comment_status, - 'menu_order' => $post_data->menu_order, - 'ping_status' => $post_data->ping_status, - 'post_author' => wp_get_current_user()->ID, - 'post_content' => $post_data->post_content ? $post_data->post_content : '', - 'post_excerpt' => $post_data->post_excerpt ? $post_data->post_excerpt : '', - 'post_mime_type' => $post_data->post_mime_type ? $post_data->post_mime_type : '', - 'post_name' => $post_data->post_name, - 'post_status' => 'publish', - 'post_title' => $post_data->post_title, - 'post_type' => $post_data->post_type, - ], + wp_slash( + [ + 'comment_status' => $post_data->comment_status, + 'menu_order' => $post_data->menu_order, + 'ping_status' => $post_data->ping_status, + 'post_author' => wp_get_current_user()->ID, + 'post_content' => $post_data->post_content ? $post_data->post_content : '', + 'post_excerpt' => $post_data->post_excerpt ? $post_data->post_excerpt : '', + 'post_mime_type' => $post_data->post_mime_type ? $post_data->post_mime_type : '', + 'post_name' => $post_data->post_name, + 'post_status' => 'publish', + 'post_title' => $post_data->post_title, + 'post_type' => $post_data->post_type, + ] + ), true ); From 5cae807f81d21b30b0e5e15b6c66ba6a4519cd35 Mon Sep 17 00:00:00 2001 From: rahulwalunje Date: Thu, 6 Aug 2026 22:39:18 +0530 Subject: [PATCH 3/7] Cloud libraries: store imported meta with $wpdb->insert instead of a raw escaped INSERT MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit import_post_meta_from_library() wrote each meta value with addslashes() + a raw string-interpolated INSERT. On hosts running MySQL in NO_BACKSLASH_ESCAPES mode that query silently fails for large serialized values (e.g. a 49KB _fl_builder_data full of escaped quotes) — the return value was ignored, so the data was never stored and the imported page rendered blank while smaller meta imported fine. Use $wpdb->insert(), which escapes per the connection and is safe on any sql_mode, and clean_post_cache() after the direct writes so same-request reads (asset regeneration) and object-cache hosts see the imported meta. Co-Authored-By: Claude Opus 4.8 --- .../Libraries/LibraryItemPostController.php | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php b/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php index 5499e9d2..61f06fb0 100644 --- a/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php +++ b/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php @@ -615,15 +615,26 @@ public function import_post_meta_from_library( $post_id, $meta ) { } if ( is_array( $meta_value ) && count( $meta_value ) !== 0 ) { foreach ( $meta_value as $value ) { - if ( $value !== null ) { - $value = addslashes( $value ); - } - // @codingStandardsIgnoreStart - $wpdb->query( "INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) values ({$post_id}, '{$meta_key}', '{$value}')" ); - // @codingStandardsIgnoreEnd + // Store the (already-serialized) value verbatim via $wpdb->insert + // so escaping follows the DB connection. The former hand-rolled + // addslashes() + raw INSERT silently failed on hosts running + // NO_BACKSLASH_ESCAPES (large builder blobs never stored → blank + // imports); $wpdb->insert() is escape-safe on any sql_mode. + $wpdb->insert( + $wpdb->postmeta, + [ + 'post_id' => $post_id, + 'meta_key' => $meta_key, + 'meta_value' => $value, + ] + ); } } } + + // The direct writes bypass the meta cache; flush it so same-request reads + // (asset regeneration) and object-cache hosts see the imported meta. + clean_post_cache( $post_id ); } /** From 622e2ad72cafda3e15dea101708e1d25a32de6d7 Mon Sep 17 00:00:00 2001 From: rahulwalunje Date: Thu, 6 Aug 2026 22:39:45 +0530 Subject: [PATCH 4/7] Cloud libraries: preserve serialized meta through the media-url rewrite MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit replace_imported_attachment_urls_in_meta() re-saved each meta value with update_post_meta(), which unslashes internally. For _fl_builder_data — an array of module objects — that strips the escaped quotes (\") inside every module's ds_block_data JSON, making it invalid. The ds-block module can't parse it, so pages built from ds-blocks imported blank whenever the media step ran (i.e. pages with a featured image or other attachments). Slashing the input didn't help because the corruption is on a deeply nested object property. Re-serialize the rewritten value with maybe_serialize() and write it with $wpdb->update() so the bytes are stored verbatim, then clean_post_cache(). Verified end to end: ds_block_data stays valid JSON and the page renders. Co-Authored-By: Claude Opus 4.8 --- .../Libraries/LibraryItemPostController.php | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php b/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php index 61f06fb0..93ba314f 100644 --- a/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php +++ b/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php @@ -813,6 +813,7 @@ public function replace_imported_attachment_urls_in_content( $post_id, $imported * @return void */ public function replace_imported_attachment_urls_in_meta( $post_id, $imported ) { + global $wpdb; $meta = get_post_meta( $post_id ); foreach ( $meta as $key => $val ) { @@ -823,13 +824,27 @@ public function replace_imported_attachment_urls_in_meta( $post_id, $imported ) } elseif ( JsonHelper::is_string_json( $val ) ) { $val = json_decode( $val ); $val = MediaPathHelper::replace_imported_attachment_urls_in_data( $val, $imported ); - $val = wp_slash( json_encode( $val ) ); + $val = json_encode( $val ); } else { $val = MediaPathHelper::replace_imported_attachment_urls_in_string( $val, $imported ); } - update_post_meta( $post_id, $key, $val ); + // Write via $wpdb, not update_post_meta(): the latter unslashes the + // value internally, which strips escaped characters buried in nested + // serialized data (e.g. the \" in each module's ds_block_data JSON) + // and corrupts _fl_builder_data, leaving ds-block pages blank on + // import. maybe_serialize() + a direct update preserves the bytes. + $wpdb->update( + $wpdb->postmeta, + [ 'meta_value' => maybe_serialize( $val ) ], + [ + 'post_id' => $post_id, + 'meta_key' => $key, + ] + ); } + + clean_post_cache( $post_id ); } /** From 7cc55b15e494b2e50a878857c80388c46f6d4f65 Mon Sep 17 00:00:00 2001 From: rahulwalunje Date: Thu, 19 Nov 2026 19:46:23 +0530 Subject: [PATCH 5/7] Cloud libraries: embed companion posts in the page item (#518) A page's companions (its design system) now travel inside the page's own library item, as one JSON string under the `_fl_asst_companions` meta key, instead of as separate library items linked by cloud id. The link survives a library being duplicated or moved, saving several pages no longer uploads repeated copies, and there is no second item to delete by accident. Import creates each embedded companion unless `fl_assistant_library_companion_exists` reports it present. A companion that cannot be created is logged and returned in an additive `companion_errors` response key. Preview imports the page only. The embedded data is never stored on the local post. `get_save_data()` returns to its signature on main. Adds unit tests for the save, import and meta paths, including regressions for the three base import fixes. Co-Authored-By: Claude Fable 5.2 --- agents/plans/ds-companion-embed-rework.md | 105 ++++++ .../Libraries/LibraryItemPostController.php | 354 ++++++++---------- backend/src/Helpers/CompanionPostsHelper.php | 70 ++++ .../LibraryItemPostCompanionsTest.php | 199 ++++++++++ 4 files changed, 529 insertions(+), 199 deletions(-) create mode 100644 agents/plans/ds-companion-embed-rework.md create mode 100644 backend/src/Helpers/CompanionPostsHelper.php create mode 100644 backend/tests/Unit/Controllers/LibraryItemPostCompanionsTest.php diff --git a/agents/plans/ds-companion-embed-rework.md b/agents/plans/ds-companion-embed-rework.md new file mode 100644 index 00000000..ff05b733 --- /dev/null +++ b/agents/plans/ds-companion-embed-rework.md @@ -0,0 +1,105 @@ +--- +name: Embed companion posts in the page library item +overview: Rework PR 519 so a page's design system travels inside the page's own library item instead of as a separate item linked by cloud id. +todos: + - id: helper + content: "Add CompanionPostsHelper (collect, encode, read)" + status: completed + - id: save + content: "Embed companions in get_save_data and remove the separate-item upload" + status: completed + - id: import + content: "Import embedded companions, skip on preview, report failures" + status: completed + - id: cleanup + content: "Split import_item args, fix stale comments" + status: completed + - id: tests + content: "Add LibraryItemPostCompanionsTest and import regression tests" + status: completed + - id: pr-body + content: "Rewrite the PR body for the new format" + status: pending +--- + +# Embed companion posts in the page library item + +**Complexity:** Medium + +## Context + +PR 519 (issue 518) uploads a page's design system as its own cloud library item and records that item's cloud id on the page item in `_fl_asst_companion_items`. The merge check on 2026-11-19 found that this link does not hold up: the cloud's library duplicate gives items new ids while copying their data verbatim, every save uploads another copy of the design system, a deleted companion item silently breaks every page that points at it, and a preview leaves a published design system behind. Companion upload and import failures were also dropped silently. + +The rework stores each companion's post, meta and terms as JSON inside the page item's own meta. The cloud API persists only `post_data.post`, `post_data.meta` and `post_data.terms` (`assistant-cloud-api/app/Traits/LibraryItemPost.php`), so meta is the one channel that needs no API change, and it survives duplicate, move and export because it is part of the item's data. Nothing in the old format has shipped, so there is no migration. + +## Decisions + +- **Link format**: companions are embedded in the page item under one meta key, `_fl_asst_companions`, holding a single JSON string: a list of `{ post, meta, terms }` objects in the same shape `get_item()` returns under `data`. Decided by Rahul 2026-11-19. `_fl_asst_companion_items` and the separate-item upload are removed. +- **Preview**: `preview_library_post` imports the page only, as before the PR. Decided by Rahul 2026-11-19. A page whose design system is not on the site previews unstyled. +- **Filters (BC)**: `fl_assistant_library_companion_posts` and `fl_assistant_library_companion_exists` keep their names; the platform consumer is already merged (`DesignSystemPostType.php:111-132`). The exists filter still receives an object with `->data->post` and `->data->meta`, built from the embedded entry. The posts filter is called with `( [], $post )`; the PR's third `$library_id` argument is dropped because `get_save_data()` has no library id and the consumer registers two arguments. +- **`get_save_data()` signature (BC)**: the `$with_screenshot` parameter added by the PR is removed, restoring the signature on main. +- **Sync**: embedding happens in `get_save_data()`, so `sync_to_library` refreshes the embedded copy too. This reverses the PR's "sync untouched" note on purpose: otherwise a sync would drop the companion. +- **Never store the blob locally**: `import_post_meta_from_library()` skips `_fl_asst_companions`, which covers import, `sync_from_library` and preview in one place. `get_save_data()` also unsets the key from the meta it read before setting a fresh value, so it can never be re-uploaded stale. +- **Failures**: `import_companions()` returns the `WP_Error`s it hit instead of dropping them. `import_from_library` (the boundary) logs each with `error_log` and adds an additive `companion_errors` list (`name`, `code`) to its response. No UI for it in this PR. +- **Size**: companion collection and decoding move to a new `Helpers/CompanionPostsHelper` (about 70 lines) because the controller is already 888 lines. Post creation stays in the controller's `import_item()`, which owns the meta and terms import. + +## Execution Strategy + +**Agents needed:** One + +One controller, one small helper and one test file; the steps depend on each other and the decisions above are settled. + +**Model tiers:** `sonnet`. The scope is well specified; the only judgment call is test design, which follows an existing file. + +## Reading List + +1. `backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php`: the whole file at the branch head; this plan rewrites its companion parts. +2. `backend/tests/Unit/Controllers/LibraryItemPostSaveDataTest.php`: the subclass-without-DI pattern the new tests follow. +3. `../bb-ai-design-system/packages/design-system-runtime/backend/DesignSystem/DesignSystemPostType.php` lines 100 to 135: the two filter callbacks and the `$item` shape they read. Read only; do not change that repo. +4. `../assistant-cloud-api/app/Traits/LibraryItemPost.php`: what the cloud keeps from `post_data`, including the restricted meta keys. +5. `backend/src/Helpers/JsonHelper.php`: the static helper style to match. + +## Implementation + +### Steps + +1. **Helper.** Add `backend/src/Helpers/CompanionPostsHelper.php` with `const META_KEY = '_fl_asst_companions'` and three static methods: `collect( $post )` applies `fl_assistant_library_companion_posts` and returns unique `WP_Post` objects (non-posts dropped, deduped by ID); `encode( array $entries )` returns the JSON string; `read( $item )` decodes `$item->data->meta->{META_KEY}[0]` into a list of item-shaped objects (`(object) [ 'data' => $entry ]`), skipping entries without `post`. Malformed JSON returns an empty list. +2. **Save.** In the controller, extract the `post_data` array that `get_save_data()` builds into `get_post_data( $post )`. In `get_save_data()`, unset `META_KEY` from the meta, then, when `collect()` returns posts, set it to `[ encode( array_map( get_post_data ) ) ]`. Delete `save_companions_to_library()`, `COMPANION_ITEMS_META`, the `$with_screenshot` parameter and the companion block in `save_to_library()`, returning that method to its form on main. +3. **Import.** Replace `import_companions_from_library()` and `get_companion_item_ids()` with `import_companions( $item )`: for each `read()` entry, skip when the exists filter returns true, else call `import_item()`; collect and return any `WP_Error`. Move the body of `import_from_library()` into a protected `import_library_post( $request, $with_companions )`; the public method calls it with `true`, and `preview_library_post()` calls it with `false` in place of `import_from_library()`. When companions ran and errors came back, log them and add `companion_errors` to the response. +4. **Meta.** In `import_post_meta_from_library()`, `continue` past `META_KEY` before the delete and insert. +5. **Cleanup.** Extract the `wp_insert_post` argument array from `import_item()` into `get_insert_post_args( $post_data )` so both stay under 30 lines. Cut the comments at the `wp_slash` and `$wpdb->insert` sites to one sentence each and remove the stale meta-cache paragraph. Every new method gets a docblock with typed `@param` and `@return`. +6. **Tests.** See Testing. +7. **PR body.** Rewrite the "How it works" section for the embedded format, state that preview skips companions, and note that the media URL rewrite no longer fires `updated_post_meta`. Follow the summary-pointers format. Do not edit any changelog. + +### Files Affected + +- `backend/src/Helpers/CompanionPostsHelper.php`: new, about 70 lines. +- `backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php`: steps 2 to 5; net smaller than the current branch. +- `backend/tests/Unit/Controllers/LibraryItemPostCompanionsTest.php`: new, about 200 lines. + +## Testing + +Unit tests, written to the `LibraryItemPostSaveDataTest` pattern with a test subclass exposing the protected methods. Run with `composer tests` (needs Local's PHP 7.4 and `vendor` copied into the worktree). + +- Save: a companion returned by the filter is embedded with its post, meta and terms; the same post returned twice is embedded once; no key when the filter returns nothing; a stale `_fl_asst_companions` value on the post is not re-uploaded. +- Import: an embedded companion is created with `post_content` containing `\n` JSON escapes intact; a companion the exists filter reports present is not created; a companion with an unregistered post type comes back as an error and the page still imports; with `$with_companions` false nothing is created. +- Meta: `import_post_meta_from_library()` does not store `_fl_asst_companions`, and stores a value containing backslashes and quotes byte for byte. +- Regression: `replace_imported_attachment_urls_in_meta()` leaves the `\"` inside a nested `ds_block_data` JSON string in `_fl_builder_data` intact. + +Manual, on the local site with Beaver Builder Platform active: save a page with a design system and confirm one library item; import it on a site without that design system and confirm the page is styled and one design system exists; import again and confirm no second design system; duplicate the library in the cloud and import from the copy; preview the page on a clean site and confirm no design system is created. + +## Risks / Open Questions + +- **Companion media is not carried.** Images referenced only by the design system are not added to the page item's attachments and their URLs are not rewritten. The current PR has the same gap (companion media was uploaded but never imported). Left out here; file a follow-up if design systems reference media. +- **Directly saved design systems can still duplicate.** A design system saved to a library on its own and imported twice is created twice with the same UUID, because a direct import never asks the exists filter. That predates this PR and is not changed here. +- **Old test items.** Library items saved from the current branch carry `_fl_asst_companion_items`; it now imports as inert stray meta. Re-save test pages after the rework. +- **Older plugin versions** import the embedded blob as a large stray meta value on the page and re-upload it on save. Harmless, but it cannot be cleaned up remotely. + +## Implementation Notes (2026-11-19) + +- Steps 1 to 6 are done in the working tree, uncommitted. The PR body is drafted but not applied, because the code is not pushed yet. +- Not tested: the "`$with_companions` false creates nothing" case. `import_library_post()` builds a `CloudClient` and fetches the item over the network, so it has no unit seam; the preview path is covered by the manual check only. +- Added beyond the step list: `get_import_error_data()` and `report_companion_errors()`, split out to keep `import_library_post()` under 30 lines; the unregistered-type and insert errors now carry the post title as `name` in their error data so the report can name the companion. +- Unit suite: the 12 `LibraryItemPost*` tests pass. `TermsControllerTest::test_can_get_terms`, four `PostRepositoryTest` tests and `SearchControllerTest::test_can_search` fail in this worktree and fail the same way on another branch of the main checkout, so they are not from this change. +- `composer lint` cannot find `WordPress-Core` without `--runtime-set installed_paths vendor/wp-coding-standards/wpcs`. With it, the only findings in the changed files are on legacy lines this change does not touch (the `if ($thumbnail)` and two `if (isset($response->success)` lines). +- Manual testing against a cloud library has not been run. diff --git a/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php b/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php index 0360b73e..7963dc6c 100644 --- a/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php +++ b/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php @@ -4,6 +4,7 @@ use FL\Assistant\System\Contracts\ControllerAbstract; use FL\Assistant\Data\Transformers\PostTransformer; +use FL\Assistant\Helpers\CompanionPostsHelper; use FL\Assistant\Helpers\PreviewHelper; use FL\Assistant\Helpers\JsonHelper; use FL\Assistant\Helpers\MediaPathHelper; @@ -13,14 +14,6 @@ class LibraryItemPostController extends ControllerAbstract { - /** - * Meta key stamped on a primary library item recording the cloud item ids of - * its companions, so import can pull them and resolve cross-references. Kept - * in meta (not a dedicated field) so it round-trips through the cloud store - * with no API change; stripped from the page after import. - */ - const COMPANION_ITEMS_META = '_fl_asst_companion_items'; - protected $posts; /** @@ -202,7 +195,7 @@ public function preview_library_post( $request ) { $request->set_param( 'id', $meta->post_id ); $response = $this->sync_from_library( $request ); } else { - $response = $this->import_from_library( $request ); + $response = $this->import_library_post( $request, false ); } if ( isset( $response->data['error'] ) ) { @@ -234,39 +227,27 @@ public function preview_library_post( $request ) { * * @param object $request * @param object $post - * @param bool $with_screenshot Whether to attach the client's screenshot. - * Companion posts (e.g. a design system) pass - * false: the request's screenshot is of the - * primary post, not of them. * @return array */ - public function get_save_data( $request, $post, $with_screenshot = true ) { - $data = [ + public function get_save_data( $request, $post ) { + $companions = CompanionPostsHelper::collect( $post ); + $data = [ 'name' => $post->post_title, 'type' => 'post', - 'post_data' => [ - 'post' => [ - 'comment_status' => $post->comment_status, - 'menu_order' => $post->menu_order, - 'ping_status' => $post->ping_status, - 'post_content' => $post->post_content, - 'post_excerpt' => $post->post_excerpt, - 'post_mime_type' => $post->post_mime_type, - 'post_name' => $post->post_name, - 'post_title' => $post->post_title, - 'post_type' => $post->post_type, - ], - 'meta' => get_post_meta( $post->ID ), - 'terms' => $this->get_post_terms( $post ), - - ], + 'post_data' => $this->get_post_data( $post ), 'media' => [ 'attachments' => $this->get_post_image_paths( $post ), ], ]; + // Companions travel inside this item, so a copied or moved item keeps them. + if ( $companions ) { + $entries = array_map( [ $this, 'get_post_data' ], $companions ); + $data['post_data']['meta'][ CompanionPostsHelper::META_KEY ] = [ CompanionPostsHelper::encode( $entries ) ]; + } + // Omit rather than fall back to HTML: the cloud's HTML screenshot path fails and clears the existing thumb (#530). - if ( $with_screenshot && $request->get_param( 'screenshot' ) ) { + if ( $request->get_param( 'screenshot' ) ) { $data['screenshot'] = $this->get_post_screenshot( $request, $post ); } @@ -279,6 +260,34 @@ public function get_save_data( $request, $post, $with_screenshot = true ) { return $data; } + /** + * Gets the post, meta and terms a library item stores for a post. + * + * @param object $post + * @return array + */ + protected function get_post_data( $post ) { + $meta = get_post_meta( $post->ID ); + + unset( $meta[ CompanionPostsHelper::META_KEY ] ); + + return [ + 'post' => [ + 'comment_status' => $post->comment_status, + 'menu_order' => $post->menu_order, + 'ping_status' => $post->ping_status, + 'post_content' => $post->post_content, + 'post_excerpt' => $post->post_excerpt, + 'post_mime_type' => $post->post_mime_type, + 'post_name' => $post->post_name, + 'post_title' => $post->post_title, + 'post_type' => $post->post_type, + ], + 'meta' => $meta, + 'terms' => $this->get_post_terms( $post ), + ]; + } + /** * Saves a post to a cloud library. * @@ -291,18 +300,10 @@ public function save_to_library( $request ) { $post = get_post( $id ); $client = new CloudClient; - // Upload companions first so their cloud ids can be recorded on the - // primary item; import reads them to pull the companions and resolve - // the primary post's cross-references at the destination. - $companion_ids = $this->save_companions_to_library( $request, $post, $library_id, $client ); - - $data = $this->get_save_data( $request, $post ); - - if ( $companion_ids ) { - $data['post_data']['meta'][ self::COMPANION_ITEMS_META ] = [ wp_json_encode( $companion_ids ) ]; - } - - $response = $client->libraries->create_item( $library_id, $data ); + $response = $client->libraries->create_item( + $library_id, + $this->get_save_data( $request, $post ) + ); if (isset($response->success) && $response->success === false) { return new \WP_Error( 'API Error', $response->message, [ 'status' => 400 ] ); @@ -311,43 +312,6 @@ public function save_to_library( $request ) { return $response; } - /** - * Uploads any companion posts a primary post depends on to the same library. - * - * Plugins declare companions via the `fl_assistant_library_companion_posts` - * filter (mirroring the `fl_assistant_post_types_known` picker filter), so - * Assistant stays generic and the companion knowledge lives in the plugin - * that owns the relationship. Companions are uploaded as their own library - * items; their cloud ids are returned so the primary item can record them. - * - * @param object $request - * @param object $post - * @param int $library_id - * @param CloudClient $client - * @return array Cloud item ids of the uploaded companions. - */ - protected function save_companions_to_library( $request, $post, $library_id, $client ) { - $companions = apply_filters( 'fl_assistant_library_companion_posts', [], $post, $library_id ); - $seen = []; - $ids = []; - - foreach ( $companions as $companion_post ) { - if ( ! $companion_post instanceof \WP_Post || isset( $seen[ $companion_post->ID ] ) ) { - continue; - } - $seen[ $companion_post->ID ] = true; - $response = $client->libraries->create_item( - $library_id, - $this->get_save_data( $request, $companion_post, false ) - ); - if ( isset( $response->id ) ) { - $ids[] = $response->id; - } - } - - return $ids; - } - /** * Replaces a library post with a post on this site. * @@ -380,167 +344,165 @@ public function sync_to_library( $request ) { * @return array */ public function import_from_library( $request ) { + return $this->import_library_post( $request, true ); + } + + /** + * Imports a library post, optionally with the companions embedded in it. + * + * @param object $request + * @param bool $with_companions + * @return \WP_REST_Response + */ + protected function import_library_post( $request, $with_companions ) { $data = $request->get_param( 'item' ); $item = $data ? json_decode( $data ) : null; if ( ! $item ) { - return rest_ensure_response( - [ - 'error' => true, - ] - ); + return rest_ensure_response( [ 'error' => true ] ); } $client = new CloudClient; - $item = $client->libraries->get_item( $item->id ); - + $item = $client->libraries->get_item( $item->id ); $result = $this->import_item( $item ); if ( is_wp_error( $result ) ) { - if ( 'post_type_not_registered' === $result->get_error_code() ) { - return rest_ensure_response( - [ - 'error' => true, - 'error_code' => 'post_type_not_registered', - 'post_type' => $result->get_error_data()['post_type'], - ] - ); - } - return rest_ensure_response( - [ - 'error' => true, - ] - ); + return rest_ensure_response( $this->get_import_error_data( $result ) ); } - $this->import_companions_from_library( $item, $result, $client ); + $response = $this->posts->transform( get_post( $result ) ); + $errors = $with_companions ? $this->import_companions( $item ) : []; - return rest_ensure_response( - $this->posts->transform( - get_post( $result ) - ) - ); + if ( $errors ) { + $response['companion_errors'] = $this->report_companion_errors( $errors ); + } + + return rest_ensure_response( $response ); } /** - * Creates a local post from a fetched cloud library item. + * Maps a failed import to the error shape the client reads. * - * Shared by the import endpoint and companion import so both create posts - * through one path. Post-type-agnostic: meta (including any identity meta a - * companion carries) and terms are copied verbatim. + * @param \WP_Error $error + * @return array + */ + protected function get_import_error_data( $error ) { + if ( 'post_type_not_registered' !== $error->get_error_code() ) { + return [ 'error' => true ]; + } + + return [ + 'error' => true, + 'error_code' => 'post_type_not_registered', + 'post_type' => $error->get_error_data()['post_type'], + ]; + } + + /** + * Creates a local post from a library item or an embedded companion. * - * @param object $item Fetched cloud library item (with `data->post/meta/terms`). - * @return int|\WP_Error New post id, or an error to be mapped by the caller. + * @param object $item + * @return int|\WP_Error */ protected function import_item( $item ) { - if ( ! in_array( $item->data->post->post_type, get_post_types(), true ) ) { + $post_data = $item->data->post; + + if ( ! in_array( $post_data->post_type, get_post_types(), true ) ) { return new \WP_Error( 'post_type_not_registered', 'Post type is not registered on this site.', - [ 'post_type' => $item->data->post->post_type ] + [ + 'post_type' => $post_data->post_type, + 'name' => $post_data->post_title, + ] ); } - $post_data = $item->data->post; - - // wp_insert_post() unslashes the array internally, so the content must be - // slashed going in. A design system stores its CSS as JSON in post_content - // (with `\n` escapes); without this, wp_insert_post strips those - // backslashes and turns every `\n` into a literal `n`, corrupting the - // generated stylesheet. - $new_post_id = wp_insert_post( - wp_slash( - [ - 'comment_status' => $post_data->comment_status, - 'menu_order' => $post_data->menu_order, - 'ping_status' => $post_data->ping_status, - 'post_author' => wp_get_current_user()->ID, - 'post_content' => $post_data->post_content ? $post_data->post_content : '', - 'post_excerpt' => $post_data->post_excerpt ? $post_data->post_excerpt : '', - 'post_mime_type' => $post_data->post_mime_type ? $post_data->post_mime_type : '', - 'post_name' => $post_data->post_name, - 'post_status' => 'publish', - 'post_title' => $post_data->post_title, - 'post_type' => $post_data->post_type, - ] - ), - true - ); + $new_post_id = wp_insert_post( $this->get_insert_post_args( $post_data ), true ); if ( is_wp_error( $new_post_id ) ) { + $new_post_id->add_data( [ 'name' => $post_data->post_title ] ); return $new_post_id; } - $this->import_post_meta_from_library( $new_post_id, $item->data->meta ); - $this->import_post_terms_from_library( $new_post_id, $item->data->terms ); + $this->import_post_meta_from_library( $new_post_id, isset( $item->data->meta ) ? $item->data->meta : null ); + $this->import_post_terms_from_library( $new_post_id, isset( $item->data->terms ) ? $item->data->terms : null ); $this->regenerate_builder_cache( $new_post_id, $item ); return $new_post_id; } /** - * Imports the companion library items recorded on an imported primary post. - * - * The primary item carries companion cloud ids in `COMPANION_ITEMS_META` - * (stamped at upload). Each companion is pulled and created unless a plugin - * reports it already exists via `fl_assistant_library_companion_exists` — - * the dedup seam where DS-specific UUID matching lives, keeping Assistant - * generic. The linkage meta is stripped from the imported post afterward so a - * later re-save doesn't re-propagate stale ids. + * Builds the wp_insert_post() arguments for an imported post. * - * The ids are read from the fetched cloud item, not from the just-imported - * post's meta: import_post_meta_from_library() writes meta with a raw INSERT - * that leaves the meta cache stale, so a same-request get_post_meta() read - * would miss it. - * - * @param object $item Fetched cloud library item (the primary). - * @param int $post_id Imported primary post id. - * @param CloudClient $client - * @return void + * @param object $post_data + * @return array */ - protected function import_companions_from_library( $item, $post_id, $client ) { - $companion_ids = $this->get_companion_item_ids( $item ); + protected function get_insert_post_args( $post_data ) { + // wp_insert_post() unslashes its input, which would strip the backslashes from JSON stored in post_content. + return wp_slash( + [ + 'comment_status' => $post_data->comment_status, + 'menu_order' => $post_data->menu_order, + 'ping_status' => $post_data->ping_status, + 'post_author' => wp_get_current_user()->ID, + 'post_content' => $post_data->post_content ? $post_data->post_content : '', + 'post_excerpt' => $post_data->post_excerpt ? $post_data->post_excerpt : '', + 'post_mime_type' => $post_data->post_mime_type ? $post_data->post_mime_type : '', + 'post_name' => $post_data->post_name, + 'post_status' => 'publish', + 'post_title' => $post_data->post_title, + 'post_type' => $post_data->post_type, + ] + ); + } - foreach ( $companion_ids as $companion_id ) { - $companion_item = $client->libraries->get_item( $companion_id ); + /** + * Imports the companions embedded in a library item, skipping any a plugin reports as already present. + * + * @param object $item + * @return \WP_Error[] + */ + protected function import_companions( $item ) { + $errors = []; - if ( ! isset( $companion_item->data->post ) ) { + foreach ( CompanionPostsHelper::read( $item ) as $companion ) { + if ( apply_filters( 'fl_assistant_library_companion_exists', false, $companion ) ) { continue; } - $exists = apply_filters( 'fl_assistant_library_companion_exists', false, $companion_item ); + $result = $this->import_item( $companion ); - if ( $exists ) { - continue; + if ( is_wp_error( $result ) ) { + $errors[] = $result; } - - $this->import_item( $companion_item ); } - if ( $companion_ids ) { - delete_post_meta( $post_id, self::COMPANION_ITEMS_META ); - } + return $errors; } /** - * Reads the companion cloud item ids recorded on a fetched library item. + * Logs companion import failures and returns them in the shape the response carries. * - * @param object $item Fetched cloud library item (with `data->meta`). - * @return array List of companion cloud item ids (empty when none recorded). + * @param \WP_Error[] $errors + * @return array */ - protected function get_companion_item_ids( $item ) { - $meta = $item->data->meta ?? null; - $raw = ( $meta && isset( $meta->{self::COMPANION_ITEMS_META}[0] ) ) - ? $meta->{self::COMPANION_ITEMS_META}[0] - : ''; - - if ( ! $raw ) { - return []; - } + protected function report_companion_errors( $errors ) { + $reported = []; - $ids = json_decode( $raw, true ); + foreach ( $errors as $error ) { + $data = (array) $error->get_error_data(); + $name = isset( $data['name'] ) ? $data['name'] : ''; - return is_array( $ids ) ? array_map( 'absint', $ids ) : []; + error_log( sprintf( 'Assistant: companion "%s" was not imported: %s', $name, $error->get_error_message() ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log + + $reported[] = [ + 'name' => $name, + 'code' => $error->get_error_code(), + ]; + } + + return $reported; } /** @@ -614,16 +576,15 @@ public function import_post_meta_from_library( $post_id, $meta ) { } foreach ( $meta as $meta_key => $meta_value ) { + if ( CompanionPostsHelper::META_KEY === $meta_key ) { + continue; + } if ( metadata_exists( 'post', $post_id, $meta_key ) ) { delete_metadata( 'post', $post_id, $meta_key ); } if ( is_array( $meta_value ) && count( $meta_value ) !== 0 ) { foreach ( $meta_value as $value ) { - // Store the (already-serialized) value verbatim via $wpdb->insert - // so escaping follows the DB connection. The former hand-rolled - // addslashes() + raw INSERT silently failed on hosts running - // NO_BACKSLASH_ESCAPES (large builder blobs never stored → blank - // imports); $wpdb->insert() is escape-safe on any sql_mode. + // $wpdb->insert() escapes for the connection; a hand-built INSERT fails under NO_BACKSLASH_ESCAPES. $wpdb->insert( $wpdb->postmeta, [ @@ -636,8 +597,7 @@ public function import_post_meta_from_library( $post_id, $meta ) { } } - // The direct writes bypass the meta cache; flush it so same-request reads - // (asset regeneration) and object-cache hosts see the imported meta. + // Direct writes bypass the meta cache. clean_post_cache( $post_id ); } @@ -833,11 +793,7 @@ public function replace_imported_attachment_urls_in_meta( $post_id, $imported ) $val = MediaPathHelper::replace_imported_attachment_urls_in_string( $val, $imported ); } - // Write via $wpdb, not update_post_meta(): the latter unslashes the - // value internally, which strips escaped characters buried in nested - // serialized data (e.g. the \" in each module's ds_block_data JSON) - // and corrupts _fl_builder_data, leaving ds-block pages blank on - // import. maybe_serialize() + a direct update preserves the bytes. + // update_post_meta() unslashes, which strips the escapes inside nested JSON such as ds_block_data. $wpdb->update( $wpdb->postmeta, [ 'meta_value' => maybe_serialize( $val ) ], diff --git a/backend/src/Helpers/CompanionPostsHelper.php b/backend/src/Helpers/CompanionPostsHelper.php new file mode 100644 index 00000000..84ec7ab2 --- /dev/null +++ b/backend/src/Helpers/CompanionPostsHelper.php @@ -0,0 +1,70 @@ +ID ] = $companion; + } + } + + return array_values( $companions ); + } + + /** + * Encodes companion entries, each shaped like a library item's post data. + * + * @param array $entries + * @return string + */ + public static function encode( $entries ) { + return wp_json_encode( $entries ); + } + + /** + * Reads the companions embedded in a fetched library item, as item-shaped objects. + * + * @param object $item + * @return object[] + */ + public static function read( $item ) { + $key = self::META_KEY; + $raw = isset( $item->data->meta->{$key}[0] ) ? $item->data->meta->{$key}[0] : ''; + $entries = is_string( $raw ) ? json_decode( $raw ) : null; + $items = []; + + if ( ! is_array( $entries ) ) { + return []; + } + + foreach ( $entries as $entry ) { + if ( isset( $entry->post->post_type ) ) { + $items[] = (object) [ 'data' => $entry ]; + } + } + + return $items; + } +} diff --git a/backend/tests/Unit/Controllers/LibraryItemPostCompanionsTest.php b/backend/tests/Unit/Controllers/LibraryItemPostCompanionsTest.php new file mode 100644 index 00000000..4a0821a6 --- /dev/null +++ b/backend/tests/Unit/Controllers/LibraryItemPostCompanionsTest.php @@ -0,0 +1,199 @@ +import_item( $item ); + } + + public function run_import_companions( $item ) { + return $this->import_companions( $item ); + } +} + +class LibraryItemPostCompanionsTest extends BaseTestCase { + + const KEY = CompanionPostsHelper::META_KEY; + + private function controller() { + return new CompanionsLibraryItemPostController(); + } + + private function save_data( $post_id ) { + $request = new \WP_REST_Request( 'POST', '/fl-assistant/v1/posts/' . $post_id . '/library/1' ); + + return $this->controller()->get_save_data( $request, get_post( $post_id ) ); + } + + private function declare_companions( array $companions ) { + add_filter( + 'fl_assistant_library_companion_posts', + function () use ( $companions ) { + return $companions; + } + ); + } + + /** + * A fetched library item whose meta embeds the given companion entries. + */ + private function item_with_companions( array $entries ) { + return json_decode( + wp_json_encode( + [ + 'data' => [ + 'meta' => [ self::KEY => [ CompanionPostsHelper::encode( $entries ) ] ], + ], + ] + ) + ); + } + + private function companion_entry( $title, $content = '', $post_type = 'post' ) { + return [ + 'post' => [ + 'comment_status' => 'closed', + 'menu_order' => 0, + 'ping_status' => 'closed', + 'post_content' => $content, + 'post_excerpt' => '', + 'post_mime_type' => '', + 'post_name' => sanitize_title( $title ), + 'post_title' => $title, + 'post_type' => $post_type, + ], + 'meta' => [ '_companion_uuid' => [ 'abc-123' ] ], + 'terms' => [], + ]; + } + + private function find_by_title( $title ) { + return get_posts( + [ + 'post_type' => 'any', + 'post_status' => 'any', + 'title' => $title, + ] + ); + } + + public function test_save_data_embeds_each_declared_companion_once() { + $page_id = self::factory()->post->create( [ 'post_type' => 'page' ] ); + $companion_id = self::factory()->post->create( [ 'post_title' => 'Brand system' ] ); + update_post_meta( $companion_id, '_companion_uuid', 'abc-123' ); + $this->declare_companions( [ get_post( $companion_id ), get_post( $companion_id ), 'not a post' ] ); + + $meta = $this->save_data( $page_id )['post_data']['meta']; + $entries = json_decode( $meta[ self::KEY ][0], true ); + + $this->assertCount( 1, $entries ); + $this->assertSame( 'Brand system', $entries[0]['post']['post_title'] ); + $this->assertSame( [ 'abc-123' ], $entries[0]['meta']['_companion_uuid'] ); + $this->assertArrayHasKey( 'terms', $entries[0] ); + } + + public function test_save_data_has_no_companion_key_without_companions() { + $page_id = self::factory()->post->create( [ 'post_type' => 'page' ] ); + + $this->assertArrayNotHasKey( self::KEY, $this->save_data( $page_id )['post_data']['meta'] ); + } + + public function test_save_data_does_not_upload_a_stale_local_companion_value() { + $page_id = self::factory()->post->create( [ 'post_type' => 'page' ] ); + update_post_meta( $page_id, self::KEY, 'stale' ); + + $this->assertArrayNotHasKey( self::KEY, $this->save_data( $page_id )['post_data']['meta'] ); + } + + public function test_import_creates_a_companion_with_its_content_and_meta_intact() { + $content = wp_json_encode( [ 'base' => ".badge {\n content: \"x\";\n}" ] ); + $item = $this->item_with_companions( [ $this->companion_entry( 'Imported system', $content ) ] ); + + $errors = $this->controller()->run_import_companions( $item ); + $posts = $this->find_by_title( 'Imported system' ); + + $this->assertSame( [], $errors ); + $this->assertCount( 1, $posts ); + $this->assertSame( $content, $posts[0]->post_content ); + $this->assertSame( 'abc-123', get_post_meta( $posts[0]->ID, '_companion_uuid', true ) ); + } + + public function test_import_skips_a_companion_a_plugin_reports_as_present() { + $item = $this->item_with_companions( [ $this->companion_entry( 'Already here' ) ] ); + add_filter( + 'fl_assistant_library_companion_exists', + function ( $exists, $companion ) { + return 'Already here' === $companion->data->post->post_title; + }, + 10, + 2 + ); + + $this->assertSame( [], $this->controller()->run_import_companions( $item ) ); + $this->assertCount( 0, $this->find_by_title( 'Already here' ) ); + } + + public function test_import_returns_an_error_for_a_companion_it_cannot_create() { + $item = $this->item_with_companions( + [ + $this->companion_entry( 'Unknown type', '', 'not_registered_here' ), + $this->companion_entry( 'Still imported' ), + ] + ); + + $errors = $this->controller()->run_import_companions( $item ); + + $this->assertCount( 1, $errors ); + $this->assertSame( 'post_type_not_registered', $errors[0]->get_error_code() ); + $this->assertSame( 'Unknown type', $errors[0]->get_error_data()['name'] ); + $this->assertCount( 1, $this->find_by_title( 'Still imported' ) ); + } + + public function test_import_ignores_a_malformed_companion_value() { + $item = json_decode( wp_json_encode( [ 'data' => [ 'meta' => [ self::KEY => [ 'not json' ] ] ] ] ) ); + + $this->assertSame( [], $this->controller()->run_import_companions( $item ) ); + } + + public function test_imported_meta_keeps_its_bytes_and_never_stores_the_companion_key() { + $post_id = self::factory()->post->create(); + $value = 'a\\"b \\n c\'d'; + $meta = (object) [ + self::KEY => [ 'embedded' ], + '_test_meta' => [ $value ], + ]; + + $this->controller()->import_post_meta_from_library( $post_id, $meta ); + + $this->assertSame( $value, get_post_meta( $post_id, '_test_meta', true ) ); + $this->assertFalse( metadata_exists( 'post', $post_id, self::KEY ) ); + } + + public function test_media_url_rewrite_keeps_escapes_inside_nested_json() { + $post_id = self::factory()->post->create(); + $block_data = '{"html":"

Hi<\/p>"}'; + $node = (object) [ 'settings' => (object) [ 'ds_block_data' => $block_data ] ]; + $meta = (object) [ + '_fl_builder_data' => [ serialize( [ 'node1' => $node ] ) ], // phpcs:ignore + '_fl_builder_data_settings' => [ '' ], + ]; + + $this->controller()->import_post_meta_from_library( $post_id, $meta ); + $this->controller()->replace_imported_attachment_urls_in_meta( $post_id, [] ); + + $stored = get_post_meta( $post_id, '_fl_builder_data', true ); + + $this->assertSame( $block_data, $stored['node1']->settings->ds_block_data ); + } +} From ff2be3be123a5cf444b064c4851bb8dc22a87e99 Mon Sep 17 00:00:00 2001 From: rahulwalunje Date: Thu, 19 Nov 2026 19:46:47 +0530 Subject: [PATCH 6/7] Plan: mark the companion embed rework as implemented (#518) Co-Authored-By: Claude Fable 5.2 --- agents/plans/ds-companion-embed-rework.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/agents/plans/ds-companion-embed-rework.md b/agents/plans/ds-companion-embed-rework.md index ff05b733..3c855aa2 100644 --- a/agents/plans/ds-companion-embed-rework.md +++ b/agents/plans/ds-companion-embed-rework.md @@ -19,7 +19,7 @@ todos: status: completed - id: pr-body content: "Rewrite the PR body for the new format" - status: pending + status: completed --- # Embed companion posts in the page library item @@ -97,7 +97,7 @@ Manual, on the local site with Beaver Builder Platform active: save a page with ## Implementation Notes (2026-11-19) -- Steps 1 to 6 are done in the working tree, uncommitted. The PR body is drafted but not applied, because the code is not pushed yet. +- All steps are done: code pushed as 7cc55b15 and the PR body rewritten on 2026-11-19. - Not tested: the "`$with_companions` false creates nothing" case. `import_library_post()` builds a `CloudClient` and fetches the item over the network, so it has no unit seam; the preview path is covered by the manual check only. - Added beyond the step list: `get_import_error_data()` and `report_companion_errors()`, split out to keep `import_library_post()` under 30 lines; the unregistered-type and insert errors now carry the post title as `name` in their error data so the report can name the companion. - Unit suite: the 12 `LibraryItemPost*` tests pass. `TermsControllerTest::test_can_get_terms`, four `PostRepositoryTest` tests and `SearchControllerTest::test_can_search` fail in this worktree and fail the same way on another branch of the main checkout, so they are not from this change. From 5ba45531c1208db2dff3f34dfa97aae4ca379490 Mon Sep 17 00:00:00 2001 From: rahulwalunje Date: Thu, 19 Nov 2026 20:06:12 +0530 Subject: [PATCH 7/7] Cloud libraries: move post import to LibraryPostImporter and restrict companion types (#518) Post creation from a library item (insert, meta, terms, builder cache, embedded companions) moves from LibraryItemPostController into a new Services/LibraryPostImporter, so the controller stops growing past its size on main. The controller's public import methods stay as delegates with unchanged signatures. A companion is now imported only when its post type is library-portable, the list behind the existing `fl_assistant_post_types_library` filter (default `fl-design-system`), read through the new PostsRepository::get_library_post_types(). Embedded companion data can come from a library another user authored, so it must not choose its own post type. A refused companion is reported as `companion_type_not_allowed`. Co-Authored-By: Claude Fable 5.2 --- agents/plans/ds-companion-embed-rework.md | 10 + .../Libraries/LibraryItemPostController.php | 211 ++-------------- .../src/Data/Repository/PostsRepository.php | 13 +- backend/src/Helpers/CompanionPostsHelper.php | 24 ++ backend/src/Services/LibraryPostImporter.php | 230 ++++++++++++++++++ .../LibraryItemPostCompanionsTest.php | 65 +++-- 6 files changed, 341 insertions(+), 212 deletions(-) create mode 100644 backend/src/Services/LibraryPostImporter.php diff --git a/agents/plans/ds-companion-embed-rework.md b/agents/plans/ds-companion-embed-rework.md index 3c855aa2..3b12cf08 100644 --- a/agents/plans/ds-companion-embed-rework.md +++ b/agents/plans/ds-companion-embed-rework.md @@ -103,3 +103,13 @@ Manual, on the local site with Beaver Builder Platform active: save a page with - Unit suite: the 12 `LibraryItemPost*` tests pass. `TermsControllerTest::test_can_get_terms`, four `PostRepositoryTest` tests and `SearchControllerTest::test_can_search` fail in this worktree and fail the same way on another branch of the main checkout, so they are not from this change. - `composer lint` cannot find `WordPress-Core` without `--runtime-set installed_paths vendor/wp-coding-standards/wpcs`. With it, the only findings in the changed files are on legacy lines this change does not touch (the `if ($thumbnail)` and two `if (isset($response->success)` lines). - Manual testing against a cloud library has not been run. + +## Review follow-up (2026-11-19) + +A second review at ff2be3be1 raised two things, both fixed: + +- **File size.** The controller had grown past its size on main. `import_item()`, `get_insert_post_args()`, `import_companions()` and the bodies of the meta, terms and builder cache imports moved to a new `Services/LibraryPostImporter` (about 230 lines); the three public controller methods remain as one-line delegates, so their signatures are unchanged. Error reporting moved to `CompanionPostsHelper::report_errors()`. The controller is 665 lines, down from 707 on main. +- **Companion post types.** A companion is imported only when its post type is library-portable: the list behind the existing `fl_assistant_post_types_library` filter (default `fl-design-system`), now read through `PostsRepository::get_library_post_types()`. Anything else comes back as a `companion_type_not_allowed` error. The embedded data can come from a library another user authored, so it must not choose its own post type. +- The Context claim that the embedded data survives a library duplicate is unverified: the cloud's duplicate appears to copy items without `post_data` at all, companions or not. Removed from the PR body. +- Left open from that review: the UI does not show `companion_errors`; preview and the response key have no unit test (no seam for the cloud fetch); `sync_from_library` does not import companions; a null meta value is now stored as SQL NULL; the stored value has no version wrapper. + diff --git a/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php b/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php index 7963dc6c..4570e5e8 100644 --- a/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php +++ b/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php @@ -9,6 +9,7 @@ use FL\Assistant\Helpers\JsonHelper; use FL\Assistant\Helpers\MediaPathHelper; use FL\Assistant\Helpers\ScreenshotHelper; +use FL\Assistant\Services\LibraryPostImporter; use FL\Assistant\Services\MediaLibraryService; use FL\Assistant\Clients\Cloud\CloudClient; @@ -364,22 +365,31 @@ protected function import_library_post( $request, $with_companions ) { $client = new CloudClient; $item = $client->libraries->get_item( $item->id ); - $result = $this->import_item( $item ); + $result = $this->importer()->import_item( $item ); if ( is_wp_error( $result ) ) { return rest_ensure_response( $this->get_import_error_data( $result ) ); } $response = $this->posts->transform( get_post( $result ) ); - $errors = $with_companions ? $this->import_companions( $item ) : []; + $errors = $with_companions ? $this->importer()->import_companions( $item ) : []; if ( $errors ) { - $response['companion_errors'] = $this->report_companion_errors( $errors ); + $response['companion_errors'] = CompanionPostsHelper::report_errors( $errors ); } return rest_ensure_response( $response ); } + /** + * Returns the importer that creates local posts from library items. + * + * @return LibraryPostImporter + */ + protected function importer() { + return new LibraryPostImporter(); + } + /** * Maps a failed import to the error shape the client reads. * @@ -398,113 +408,6 @@ protected function get_import_error_data( $error ) { ]; } - /** - * Creates a local post from a library item or an embedded companion. - * - * @param object $item - * @return int|\WP_Error - */ - protected function import_item( $item ) { - $post_data = $item->data->post; - - if ( ! in_array( $post_data->post_type, get_post_types(), true ) ) { - return new \WP_Error( - 'post_type_not_registered', - 'Post type is not registered on this site.', - [ - 'post_type' => $post_data->post_type, - 'name' => $post_data->post_title, - ] - ); - } - - $new_post_id = wp_insert_post( $this->get_insert_post_args( $post_data ), true ); - - if ( is_wp_error( $new_post_id ) ) { - $new_post_id->add_data( [ 'name' => $post_data->post_title ] ); - return $new_post_id; - } - - $this->import_post_meta_from_library( $new_post_id, isset( $item->data->meta ) ? $item->data->meta : null ); - $this->import_post_terms_from_library( $new_post_id, isset( $item->data->terms ) ? $item->data->terms : null ); - $this->regenerate_builder_cache( $new_post_id, $item ); - - return $new_post_id; - } - - /** - * Builds the wp_insert_post() arguments for an imported post. - * - * @param object $post_data - * @return array - */ - protected function get_insert_post_args( $post_data ) { - // wp_insert_post() unslashes its input, which would strip the backslashes from JSON stored in post_content. - return wp_slash( - [ - 'comment_status' => $post_data->comment_status, - 'menu_order' => $post_data->menu_order, - 'ping_status' => $post_data->ping_status, - 'post_author' => wp_get_current_user()->ID, - 'post_content' => $post_data->post_content ? $post_data->post_content : '', - 'post_excerpt' => $post_data->post_excerpt ? $post_data->post_excerpt : '', - 'post_mime_type' => $post_data->post_mime_type ? $post_data->post_mime_type : '', - 'post_name' => $post_data->post_name, - 'post_status' => 'publish', - 'post_title' => $post_data->post_title, - 'post_type' => $post_data->post_type, - ] - ); - } - - /** - * Imports the companions embedded in a library item, skipping any a plugin reports as already present. - * - * @param object $item - * @return \WP_Error[] - */ - protected function import_companions( $item ) { - $errors = []; - - foreach ( CompanionPostsHelper::read( $item ) as $companion ) { - if ( apply_filters( 'fl_assistant_library_companion_exists', false, $companion ) ) { - continue; - } - - $result = $this->import_item( $companion ); - - if ( is_wp_error( $result ) ) { - $errors[] = $result; - } - } - - return $errors; - } - - /** - * Logs companion import failures and returns them in the shape the response carries. - * - * @param \WP_Error[] $errors - * @return array - */ - protected function report_companion_errors( $errors ) { - $reported = []; - - foreach ( $errors as $error ) { - $data = (array) $error->get_error_data(); - $name = isset( $data['name'] ) ? $data['name'] : ''; - - error_log( sprintf( 'Assistant: companion "%s" was not imported: %s', $name, $error->get_error_message() ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log - - $reported[] = [ - 'name' => $name, - 'code' => $error->get_error_code(), - ]; - } - - return $reported; - } - /** * Replaces a post on this site with a post from a library. * @@ -564,41 +467,7 @@ public function sync_from_library( $request ) { * @return void */ public function import_post_meta_from_library( $post_id, $meta ) { - global $wpdb; - - if ( ! $meta || ! is_object( $meta ) ) { - return; - } - - if ( isset( $meta->_fl_builder_data ) ) { - $meta->_fl_builder_draft = $meta->_fl_builder_data; - $meta->_fl_builder_draft_settings = $meta->_fl_builder_data_settings; - } - - foreach ( $meta as $meta_key => $meta_value ) { - if ( CompanionPostsHelper::META_KEY === $meta_key ) { - continue; - } - if ( metadata_exists( 'post', $post_id, $meta_key ) ) { - delete_metadata( 'post', $post_id, $meta_key ); - } - if ( is_array( $meta_value ) && count( $meta_value ) !== 0 ) { - foreach ( $meta_value as $value ) { - // $wpdb->insert() escapes for the connection; a hand-built INSERT fails under NO_BACKSLASH_ESCAPES. - $wpdb->insert( - $wpdb->postmeta, - [ - 'post_id' => $post_id, - 'meta_key' => $meta_key, - 'meta_value' => $value, - ] - ); - } - } - } - - // Direct writes bypass the meta cache. - clean_post_cache( $post_id ); + $this->importer()->import_meta( $post_id, $meta ); } /** @@ -609,48 +478,7 @@ public function import_post_meta_from_library( $post_id, $meta ) { * @return void */ public function import_post_terms_from_library( $post_id, $terms ) { - $terms = is_object( $terms ) ? [ $terms ] : $terms; - - if ( ! $terms || ! is_array( $terms ) || 0 === count( $terms ) ) { - return; - } - - $taxonomies = get_taxonomies( '', 'objects' ); - $taxonomy_terms = []; - - foreach ( $terms as $term ) { - if ( ! isset( $term->name ) || ! isset( $term->taxonomy ) ) { - continue; - } elseif ( ! taxonomy_exists( $term->taxonomy ) ) { - continue; - } elseif ( ! isset( $taxonomy_terms ) ) { - $taxonomy_terms[ $term->taxonomy ] = []; - } - - $existing_term = term_exists( $term->slug, $term->taxonomy ); - $is_hierarchical = ! ! $taxonomies[ $term->taxonomy ]->hierarchical; - - if ( is_array( $existing_term ) ) { - $term_id = $is_hierarchical ? $existing_term['term_taxonomy_id'] : $term->name; - } else { - $new_term = wp_insert_term( - $term->name, - $term->taxonomy, - [ - 'description' => $term->description, - 'slug' => $term->slug, - ] - ); - $term_id = $is_hierarchical ? $new_term['term_taxonomy_id'] : $term->name; - } - - $taxonomy_terms[ $term->taxonomy ][] = $term_id; - } - - foreach ( $taxonomy_terms as $taxonomy => $terms ) { - wp_delete_object_term_relationships( $post_id, $taxonomy ); - wp_set_post_terms( $post_id, $terms, $taxonomy, true ); - } + $this->importer()->import_terms( $post_id, $terms ); } /** @@ -832,13 +660,6 @@ public function get_post_image_paths( $post ) { * @return void */ public function regenerate_builder_cache( $post_id, $item ) { - $meta = (array) $item->data->meta; - - if ( isset( $meta['_fl_builder_data'] ) && class_exists( '\FLBuilderModel' ) ) { - \FLBuilderModel::delete_all_asset_cache( $post_id ); - } - if ( isset( $meta['_elementor_data'] ) && class_exists( 'Elementor\Plugin' ) ) { - \Elementor\Plugin::$instance->files_manager->clear_cache(); - } + $this->importer()->regenerate_builder_cache( $post_id, $item ); } } diff --git a/backend/src/Data/Repository/PostsRepository.php b/backend/src/Data/Repository/PostsRepository.php index 34507158..e35da858 100644 --- a/backend/src/Data/Repository/PostsRepository.php +++ b/backend/src/Data/Repository/PostsRepository.php @@ -132,6 +132,15 @@ private function get_stable_plural_label( \WP_Post_Type $type ) { return $type->labels->name; } + /** + * Returns the non-public post types whose items are portable enough for a cloud library. + * + * @return string[] + */ + public static function get_library_post_types() { + return (array) apply_filters( 'fl_assistant_post_types_library', [ 'fl-design-system' ] ); + } + /** * Get array of post types registered in WordPress * @return array @@ -152,9 +161,7 @@ public function get_types() { // wp_theme taxonomy and code snippets have their own library item type, so // neither belongs in the upload picker. Design systems are portable by UUID, // so they do. - $library = apply_filters( 'fl_assistant_post_types_library', [ - 'fl-design-system', - ] ); + $library = self::get_library_post_types(); // Types to never show $ignore = [ diff --git a/backend/src/Helpers/CompanionPostsHelper.php b/backend/src/Helpers/CompanionPostsHelper.php index 84ec7ab2..ec8e424b 100644 --- a/backend/src/Helpers/CompanionPostsHelper.php +++ b/backend/src/Helpers/CompanionPostsHelper.php @@ -67,4 +67,28 @@ public static function read( $item ) { return $items; } + + /** + * Logs companion import failures and returns them in the shape the response carries. + * + * @param \WP_Error[] $errors + * @return array + */ + public static function report_errors( $errors ) { + $reported = []; + + foreach ( $errors as $error ) { + $data = (array) $error->get_error_data(); + $name = isset( $data['name'] ) ? $data['name'] : ''; + + error_log( sprintf( 'Assistant: companion "%s" was not imported: %s', $name, $error->get_error_message() ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log + + $reported[] = [ + 'name' => $name, + 'code' => $error->get_error_code(), + ]; + } + + return $reported; + } } diff --git a/backend/src/Services/LibraryPostImporter.php b/backend/src/Services/LibraryPostImporter.php new file mode 100644 index 00000000..247df38a --- /dev/null +++ b/backend/src/Services/LibraryPostImporter.php @@ -0,0 +1,230 @@ +data->post; + + if ( ! in_array( $post_data->post_type, get_post_types(), true ) ) { + return new \WP_Error( + 'post_type_not_registered', + 'Post type is not registered on this site.', + [ + 'post_type' => $post_data->post_type, + 'name' => $post_data->post_title, + ] + ); + } + + $new_post_id = wp_insert_post( $this->get_insert_post_args( $post_data ), true ); + + if ( is_wp_error( $new_post_id ) ) { + $new_post_id->add_data( [ 'name' => $post_data->post_title ] ); + return $new_post_id; + } + + $this->import_meta( $new_post_id, isset( $item->data->meta ) ? $item->data->meta : null ); + $this->import_terms( $new_post_id, isset( $item->data->terms ) ? $item->data->terms : null ); + $this->regenerate_builder_cache( $new_post_id, $item ); + + return $new_post_id; + } + + /** + * Builds the wp_insert_post() arguments for an imported post. + * + * @param object $post_data + * @return array + */ + protected function get_insert_post_args( $post_data ) { + // wp_insert_post() unslashes its input, which would strip the backslashes from JSON stored in post_content. + return wp_slash( + [ + 'comment_status' => $post_data->comment_status, + 'menu_order' => $post_data->menu_order, + 'ping_status' => $post_data->ping_status, + 'post_author' => wp_get_current_user()->ID, + 'post_content' => $post_data->post_content ? $post_data->post_content : '', + 'post_excerpt' => $post_data->post_excerpt ? $post_data->post_excerpt : '', + 'post_mime_type' => $post_data->post_mime_type ? $post_data->post_mime_type : '', + 'post_name' => $post_data->post_name, + 'post_status' => 'publish', + 'post_title' => $post_data->post_title, + 'post_type' => $post_data->post_type, + ] + ); + } + + /** + * Imports the companions embedded in a library item and returns the ones that failed. + * + * @param object $item + * @return \WP_Error[] + */ + public function import_companions( $item ) { + $errors = []; + + foreach ( CompanionPostsHelper::read( $item ) as $companion ) { + $result = $this->import_companion( $companion ); + + if ( is_wp_error( $result ) ) { + $errors[] = $result; + } + } + + return $errors; + } + + /** + * Imports one companion unless its post type is not library-portable or a plugin reports it present. + * + * @param object $companion + * @return int|\WP_Error Zero when skipped as already present. + */ + protected function import_companion( $companion ) { + $post_data = $companion->data->post; + + // The entry comes from a library someone else may have authored, so it cannot pick its own post type. + if ( ! in_array( $post_data->post_type, PostsRepository::get_library_post_types(), true ) ) { + return new \WP_Error( + 'companion_type_not_allowed', + 'Post type cannot be imported as a companion.', + [ + 'post_type' => $post_data->post_type, + 'name' => isset( $post_data->post_title ) ? $post_data->post_title : '', + ] + ); + } + + if ( apply_filters( 'fl_assistant_library_companion_exists', false, $companion ) ) { + return 0; + } + + return $this->import_item( $companion ); + } + + /** + * Imports meta for a library post to the site. + * + * @param int $post_id + * @param object $meta + * @return void + */ + public function import_meta( $post_id, $meta ) { + global $wpdb; + + if ( ! $meta || ! is_object( $meta ) ) { + return; + } + + if ( isset( $meta->_fl_builder_data ) ) { + $meta->_fl_builder_draft = $meta->_fl_builder_data; + $meta->_fl_builder_draft_settings = $meta->_fl_builder_data_settings; + } + + foreach ( $meta as $meta_key => $meta_value ) { + if ( CompanionPostsHelper::META_KEY === $meta_key ) { + continue; + } + if ( metadata_exists( 'post', $post_id, $meta_key ) ) { + delete_metadata( 'post', $post_id, $meta_key ); + } + if ( is_array( $meta_value ) && count( $meta_value ) !== 0 ) { + foreach ( $meta_value as $value ) { + // $wpdb->insert() escapes for the connection; a hand-built INSERT fails under NO_BACKSLASH_ESCAPES. + $wpdb->insert( + $wpdb->postmeta, + [ + 'post_id' => $post_id, + 'meta_key' => $meta_key, + 'meta_value' => $value, + ] + ); + } + } + } + + // Direct writes bypass the meta cache. + clean_post_cache( $post_id ); + } + + /** + * Imports terms for a library post to the site. + * + * @param int $post_id + * @param array $terms + * @return void + */ + public function import_terms( $post_id, $terms ) { + $terms = is_object( $terms ) ? [ $terms ] : $terms; + + if ( ! $terms || ! is_array( $terms ) || 0 === count( $terms ) ) { + return; + } + + $taxonomies = get_taxonomies( '', 'objects' ); + $taxonomy_terms = []; + + foreach ( $terms as $term ) { + if ( ! isset( $term->name ) || ! isset( $term->taxonomy ) ) { + continue; + } elseif ( ! taxonomy_exists( $term->taxonomy ) ) { + continue; + } elseif ( ! isset( $taxonomy_terms ) ) { + $taxonomy_terms[ $term->taxonomy ] = []; + } + + $existing_term = term_exists( $term->slug, $term->taxonomy ); + $is_hierarchical = ! ! $taxonomies[ $term->taxonomy ]->hierarchical; + + if ( is_array( $existing_term ) ) { + $term_id = $is_hierarchical ? $existing_term['term_taxonomy_id'] : $term->name; + } else { + $new_term = wp_insert_term( + $term->name, + $term->taxonomy, + [ + 'description' => $term->description, + 'slug' => $term->slug, + ] + ); + $term_id = $is_hierarchical ? $new_term['term_taxonomy_id'] : $term->name; + } + + $taxonomy_terms[ $term->taxonomy ][] = $term_id; + } + + foreach ( $taxonomy_terms as $taxonomy => $terms ) { + wp_delete_object_term_relationships( $post_id, $taxonomy ); + wp_set_post_terms( $post_id, $terms, $taxonomy, true ); + } + } + + /** + * Regenerate the asset cache for posts created with a builder. + * + * @param object $item + * @return void + */ + public function regenerate_builder_cache( $post_id, $item ) { + $meta = (array) $item->data->meta; + + if ( isset( $meta['_fl_builder_data'] ) && class_exists( '\FLBuilderModel' ) ) { + \FLBuilderModel::delete_all_asset_cache( $post_id ); + } + if ( isset( $meta['_elementor_data'] ) && class_exists( 'Elementor\Plugin' ) ) { + \Elementor\Plugin::$instance->files_manager->clear_cache(); + } + } +} diff --git a/backend/tests/Unit/Controllers/LibraryItemPostCompanionsTest.php b/backend/tests/Unit/Controllers/LibraryItemPostCompanionsTest.php index 4a0821a6..6d5e55b9 100644 --- a/backend/tests/Unit/Controllers/LibraryItemPostCompanionsTest.php +++ b/backend/tests/Unit/Controllers/LibraryItemPostCompanionsTest.php @@ -4,22 +4,15 @@ use FL\Assistant\Tests\Unit\BaseTestCase; use FL\Assistant\Controllers\Cloud\Libraries\LibraryItemPostController; use FL\Assistant\Helpers\CompanionPostsHelper; +use FL\Assistant\Services\LibraryPostImporter; /** - * Builds the controller without the DI container and exposes the import - * steps; none of them touch the injected transformer or the cloud client. + * Builds the controller without the DI container; the methods under test + * never touch the injected transformer or the cloud client. */ class CompanionsLibraryItemPostController extends LibraryItemPostController { public function __construct() {} // phpcs:ignore - - public function run_import_item( $item ) { - return $this->import_item( $item ); - } - - public function run_import_companions( $item ) { - return $this->import_companions( $item ); - } } class LibraryItemPostCompanionsTest extends BaseTestCase { @@ -30,6 +23,22 @@ private function controller() { return new CompanionsLibraryItemPostController(); } + /** + * Lets the plain post type stand in for a library-portable companion type. + */ + private function allow_post_companions() { + add_filter( + 'fl_assistant_post_types_library', + function ( $types ) { + return array_merge( $types, [ 'post', 'not_registered_here' ] ); + } + ); + } + + private function import_companions( $item ) { + return ( new LibraryPostImporter() )->import_companions( $item ); + } + private function save_data( $post_id ) { $request = new \WP_REST_Request( 'POST', '/fl-assistant/v1/posts/' . $post_id . '/library/1' ); @@ -117,10 +126,11 @@ public function test_save_data_does_not_upload_a_stale_local_companion_value() { } public function test_import_creates_a_companion_with_its_content_and_meta_intact() { + $this->allow_post_companions(); $content = wp_json_encode( [ 'base' => ".badge {\n content: \"x\";\n}" ] ); $item = $this->item_with_companions( [ $this->companion_entry( 'Imported system', $content ) ] ); - $errors = $this->controller()->run_import_companions( $item ); + $errors = $this->import_companions( $item ); $posts = $this->find_by_title( 'Imported system' ); $this->assertSame( [], $errors ); @@ -130,6 +140,7 @@ public function test_import_creates_a_companion_with_its_content_and_meta_intact } public function test_import_skips_a_companion_a_plugin_reports_as_present() { + $this->allow_post_companions(); $item = $this->item_with_companions( [ $this->companion_entry( 'Already here' ) ] ); add_filter( 'fl_assistant_library_companion_exists', @@ -140,11 +151,12 @@ function ( $exists, $companion ) { 2 ); - $this->assertSame( [], $this->controller()->run_import_companions( $item ) ); + $this->assertSame( [], $this->import_companions( $item ) ); $this->assertCount( 0, $this->find_by_title( 'Already here' ) ); } public function test_import_returns_an_error_for_a_companion_it_cannot_create() { + $this->allow_post_companions(); $item = $this->item_with_companions( [ $this->companion_entry( 'Unknown type', '', 'not_registered_here' ), @@ -152,7 +164,7 @@ public function test_import_returns_an_error_for_a_companion_it_cannot_create() ] ); - $errors = $this->controller()->run_import_companions( $item ); + $errors = $this->import_companions( $item ); $this->assertCount( 1, $errors ); $this->assertSame( 'post_type_not_registered', $errors[0]->get_error_code() ); @@ -160,10 +172,35 @@ public function test_import_returns_an_error_for_a_companion_it_cannot_create() $this->assertCount( 1, $this->find_by_title( 'Still imported' ) ); } + public function test_import_refuses_a_companion_whose_post_type_is_not_library_portable() { + $item = $this->item_with_companions( [ $this->companion_entry( 'Sneaky page', '', 'page' ) ] ); + + $errors = $this->import_companions( $item ); + + $this->assertCount( 1, $errors ); + $this->assertSame( 'companion_type_not_allowed', $errors[0]->get_error_code() ); + $this->assertCount( 0, $this->find_by_title( 'Sneaky page' ) ); + } + + public function test_companion_errors_are_reported_by_name_and_code() { + $item = $this->item_with_companions( [ $this->companion_entry( 'Sneaky page', '', 'page' ) ] ); + $report = CompanionPostsHelper::report_errors( $this->import_companions( $item ) ); + + $this->assertSame( + [ + [ + 'name' => 'Sneaky page', + 'code' => 'companion_type_not_allowed', + ], + ], + $report + ); + } + public function test_import_ignores_a_malformed_companion_value() { $item = json_decode( wp_json_encode( [ 'data' => [ 'meta' => [ self::KEY => [ 'not json' ] ] ] ] ) ); - $this->assertSame( [], $this->controller()->run_import_companions( $item ) ); + $this->assertSame( [], $this->import_companions( $item ) ); } public function test_imported_meta_keeps_its_bytes_and_never_stores_the_companion_key() {