diff --git a/agents/plans/ds-companion-embed-rework.md b/agents/plans/ds-companion-embed-rework.md new file mode 100644 index 00000000..3b12cf08 --- /dev/null +++ b/agents/plans/ds-companion-embed-rework.md @@ -0,0 +1,115 @@ +--- +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: completed +--- + +# 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) + +- 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. +- `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 a817a8e6..4570e5e8 100644 --- a/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php +++ b/backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php @@ -4,10 +4,12 @@ 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; use FL\Assistant\Helpers\ScreenshotHelper; +use FL\Assistant\Services\LibraryPostImporter; use FL\Assistant\Services\MediaLibraryService; use FL\Assistant\Clients\Cloud\CloudClient; @@ -194,7 +196,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'] ) ) { @@ -229,30 +231,22 @@ public function preview_library_post( $request ) { * @return array */ public function get_save_data( $request, $post ) { - $data = [ + $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 ( $request->get_param( 'screenshot' ) ) { $data['screenshot'] = $this->get_post_screenshot( $request, $post ); @@ -267,6 +261,34 @@ public function get_save_data( $request, $post ) { 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. * @@ -323,69 +345,67 @@ 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->importer()->import_item( $item ); + + if ( is_wp_error( $result ) ) { + return rest_ensure_response( $this->get_import_error_data( $result ) ); + } - $registered_post_types = get_post_types(); + $response = $this->posts->transform( get_post( $result ) ); + $errors = $with_companions ? $this->importer()->import_companions( $item ) : []; - if ( ! in_array( $item->data->post->post_type, $registered_post_types ) ) { - return rest_ensure_response( - [ - 'error' => true, - 'error_code' => 'post_type_not_registered', - 'post_type' => $item->data->post->post_type, - ] - ); + if ( $errors ) { + $response['companion_errors'] = CompanionPostsHelper::report_errors( $errors ); } - $post_data = $item->data->post; - $meta_data = $item->data->meta; - $term_data = $item->data->terms; + return rest_ensure_response( $response ); + } - $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, - ] - ); + /** + * Returns the importer that creates local posts from library items. + * + * @return LibraryPostImporter + */ + protected function importer() { + return new LibraryPostImporter(); + } - if ( is_wp_error( $new_post_id ) ) { - return rest_ensure_response( - [ - 'error' => true, - ] - ); + /** + * Maps a failed import to the error shape the client reads. + * + * @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 ]; } - $this->import_post_meta_from_library( $new_post_id, $meta_data ); - $this->import_post_terms_from_library( $new_post_id, $term_data ); - $this->regenerate_builder_cache( $new_post_id, $item ); - - return rest_ensure_response( - $this->posts->transform( - get_post( $new_post_id ) - ) - ); + return [ + 'error' => true, + 'error_code' => 'post_type_not_registered', + 'post_type' => $error->get_error_data()['post_type'], + ]; } /** @@ -447,32 +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 ( 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 ) { - 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 - } - } - } + $this->importer()->import_meta( $post_id, $meta ); } /** @@ -483,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 ); } /** @@ -651,6 +605,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 ) { @@ -661,13 +616,23 @@ 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 ); + // 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 ) ], + [ + 'post_id' => $post_id, + 'meta_key' => $key, + ] + ); } + + clean_post_cache( $post_id ); } /** @@ -695,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 new file mode 100644 index 00000000..ec8e424b --- /dev/null +++ b/backend/src/Helpers/CompanionPostsHelper.php @@ -0,0 +1,94 @@ +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; + } + + /** + * 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 new file mode 100644 index 00000000..6d5e55b9 --- /dev/null +++ b/backend/tests/Unit/Controllers/LibraryItemPostCompanionsTest.php @@ -0,0 +1,236 @@ +import_companions( $item ); + } + + 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() { + $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->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() { + $this->allow_post_companions(); + $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->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' ), + $this->companion_entry( 'Still imported' ), + ] + ); + + $errors = $this->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_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->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 ); + } +}