> $registry Registry. * @return array> */ function aafm_register_wc_products_definitions( array $registry ): array { if ( ! aafm_integration_active( 'woocommerce' ) ) { return $registry; // Host inactive: contribute nothing. } return array_merge( $registry, aafm_wc_products_registry_definitions() ); } /** * Contribute the WooCommerce product definitions to the guard-independent full registry view. * * Unguarded by design: the full view (aafm_get_abilities_registry_full()) enumerates every * WooCommerce ability even when WooCommerce is inactive, for the Integrations tab and the manifest. * The live registration path never reads this filter, so an inactive host still exposes zero tools. * * @param array> $registry Integration rows accumulator. * @return array> */ function aafm_register_wc_products_full_definitions( array $registry ): array { return array_merge( $registry, aafm_wc_products_registry_definitions() ); } /** * The WooCommerce product registry rows, keyed by ability name. The single source of truth for * these abilities' label, description, group, risk, and args builder - consumed by both the * host-guarded live registration callback and the unguarded full-view callback. * * @return array> */ function aafm_wc_products_registry_definitions(): array { return array( 'aafm/wc-list-products' => array( 'label' => __( 'List WooCommerce products', 'agent-abilities-for-mcp' ), 'description' => __( 'Lists WooCommerce products with their id, name, SKU, price, stock status, status, categories, and featured flag, plus a total. Only status is filtered server-side; there is no price, name, or other field filter, so narrowing the returned rows (for example to products under a price) is the caller\'s job. Requires the manage-WooCommerce capability.', 'agent-abilities-for-mcp' ), 'group' => 'reads', 'risk' => 'read', 'subject' => 'woocommerce', 'args_builder' => 'aafm_args_wc_list_products', ), 'aafm/wc-get-product' => array( 'label' => __( 'Get WooCommerce product', 'agent-abilities-for-mcp' ), 'description' => __( 'Reads one WooCommerce product by id, including its description, prices, stock, images, attributes, variation ids, and categories. Requires the manage-WooCommerce capability.', 'agent-abilities-for-mcp' ), 'group' => 'reads', 'risk' => 'read', 'subject' => 'woocommerce', 'args_builder' => 'aafm_args_wc_get_product', ), 'aafm/wc-create-product' => array( 'label' => __( 'Create WooCommerce product', 'agent-abilities-for-mcp' ), 'description' => __( 'Creates a WooCommerce product from a name (required) plus optional type, status, description, prices, SKU, stock, categories, tags, images, and attributes. Requires the manage-WooCommerce capability.', 'agent-abilities-for-mcp' ), 'group' => 'writes', 'risk' => 'write', 'subject' => 'woocommerce', 'args_builder' => 'aafm_args_wc_create_product', ), 'aafm/wc-update-product' => array( 'label' => __( 'Update WooCommerce product', 'agent-abilities-for-mcp' ), 'description' => __( 'Updates a WooCommerce product by id, changing only the fields you send. remove_attributes takes attributes off the product, refusing any that a variation uses and refusing the whole removal on a product with more than 1,000 unpublished variations. Requires the manage-WooCommerce capability.', 'agent-abilities-for-mcp' ), 'group' => 'writes', 'risk' => 'write', 'subject' => 'woocommerce', 'args_builder' => 'aafm_args_wc_update_product', ), 'aafm/wc-delete-product' => array( 'label' => __( 'Delete WooCommerce product', 'agent-abilities-for-mcp' ), 'description' => __( 'Permanently deletes a WooCommerce product by id. This bypasses the Trash and cannot be undone. Requires the manage-WooCommerce capability.', 'agent-abilities-for-mcp' ), 'group' => 'writes', 'risk' => 'destructive', 'subject' => 'woocommerce', 'args_builder' => 'aafm_args_wc_delete_product', ), ); } /** * Resolve a product id to a WC_Product, or null when WooCommerce is unavailable or the id is unknown. * * @param int $id Product id. * @return \WC_Product|null */ function aafm_wc_get_product( int $id ): ?\WC_Product { if ( $id < 1 || ! function_exists( 'wc_get_product' ) ) { return null; } if ( false !== aafm_wc_store_is_core( 'product' ) && ! aafm_exact_object( 'post', $id ) instanceof WP_Post ) { return null; } $product = wc_get_product( $id ); return $product instanceof \WC_Product ? $product : null; } /** * The lean list shape for a product: id, name, sku, price, stock_status, status, categories[], * featured. No description (list rows stay lean). * * @param \WC_Product $product Product. * @return array */ function aafm_redact_wc_product( \WC_Product $product ): array { return array( 'id' => (int) $product->get_id(), 'name' => (string) $product->get_name(), 'sku' => (string) $product->get_sku(), 'price' => (string) $product->get_price(), 'stock_status' => (string) $product->get_stock_status(), 'status' => (string) $product->get_status(), 'categories' => array_map( 'intval', (array) $product->get_category_ids() ), 'featured' => (bool) $product->get_featured(), ); } /** * The full single-product shape: the lean fields plus description, short_description, prices, stock, * images, attributes (a key=>value-ish map cast to object so an empty one encodes as {}), variation * ids, and tags. Never a filesystem path - images are attachment ids, not file paths. * * @param \WC_Product $product Product. * @return array */ function aafm_rich_wc_product( \WC_Product $product ): array { $attributes = array(); foreach ( (array) $product->get_attributes() as $key => $attribute ) { $attributes[ (string) $key ] = aafm_wc_attribute_shape( $attribute ); } $base = aafm_redact_wc_product( $product ); return array_merge( $base, array( 'type' => (string) $product->get_type(), 'description' => (string) $product->get_description(), 'short_description' => (string) $product->get_short_description(), 'regular_price' => (string) $product->get_regular_price(), 'sale_price' => (string) $product->get_sale_price(), 'manage_stock' => (bool) $product->get_manage_stock(), 'stock_quantity' => null === $product->get_stock_quantity() ? null : (int) $product->get_stock_quantity(), 'tags' => array_map( 'intval', (array) $product->get_tag_ids() ), 'image_id' => (int) $product->get_image_id(), // array_values() re-keys sequentially. get_gallery_image_ids() runs the stored // _product_image_gallery meta through array_filter() then wp_parse_id_list() // (array_unique(array_map('absint', ...))), which are both key-preserving. A gallery // meta of "12,0,34" (a gap left by anything writing that meta directly - migrations, // importers, third-party plugins - since only WooCommerce's own save path self-heals // it) yields [0=>12, 2=>34], which json_encode()s as an OBJECT ({"0":12,"2":34}) // against a schema declaring type: array. array_values() forces the JSON array shape. 'images' => array_values( array_map( 'intval', (array) $product->get_gallery_image_ids() ) ), // Cast so an empty attributes map encodes to "{}" (object) per the schema, never "[]". 'attributes' => (object) $attributes, // Same key-gap risk as images, but it never self-heals here: get_children() on a // grouped product reads its child list from the grouped data store, which persists the // array verbatim on save (class-wc-product-grouped-data-store-cpt.php:35) rather than // imploding it back to a clean sequence the way the gallery meta does. // get_children() is not variation-specific - on a grouped product it returns the // grouped child PRODUCT ids, which are not variations. Only a variable product's // children are variations, so every other type reports an empty list. 'variation_ids' => 'variable' === $product->get_type() ? array_values( array_map( 'intval', (array) $product->get_children() ) ) : array(), ) ); } /** * Reduce one WC product attribute to a JSON-safe shape, tolerating either a WC_Product_Attribute * object or a plain array. Never returns a path. * * The `options` array used to be whatever WC_Product_Attribute::get_options() held, which is TWO * different vocabularies wearing one field name: term IDS for a global/taxonomy attribute, literal * strings for a custom one. Nothing in the response said which, so a caller could not tell, and the * ids were not merely unhelpful -- they were unusable by this plugin's own write paths. An agent * that read a product to learn the valid options and fed one to wc-create-product-variation was * refused, by an error that then printed the slugs it should have been given in the first place. * The variation read reports the same field AS a slug, so the two reads contradicted each other. * * So a taxonomy attribute's options are resolved to term SLUGS here, which is the form every write * path in this plugin accepts, and a `taxonomy` flag says which kind of attribute produced them so * a caller never has to guess. * * Resolution is READ-ONLY, through aafm_wc_find_attribute_term(). Read that function's docblock * before reaching for WC_Product_Attribute::get_slugs() here: it looks like exactly the right call * and it can create terms. * * An option that cannot be resolved read-only is omitted rather than emitted in a form no write * path accepts. That is safe precisely because the write path compares against THIS function's * output: an option missing from both sides of the round trip cannot cause a spurious mismatch. * * @param mixed $attribute Attribute (object or array). * @return array */ function aafm_wc_attribute_shape( $attribute ): array { $attribute_id = 0; if ( is_object( $attribute ) && method_exists( $attribute, 'get_name' ) ) { $name = (string) $attribute->get_name(); $options = method_exists( $attribute, 'get_options' ) ? (array) $attribute->get_options() : array(); $attribute_id = method_exists( $attribute, 'get_id' ) ? (int) $attribute->get_id() : 0; } elseif ( is_array( $attribute ) ) { $name = (string) ( $attribute['name'] ?? '' ); $options = (array) ( $attribute['options'] ?? array() ); $attribute_id = (int) ( $attribute['id'] ?? 0 ); } else { $name = ''; $options = array(); } // WooCommerce's own definition of a taxonomy attribute is a non-zero attribute id; the // taxonomy_exists() half keeps a product whose attribute taxonomy has been unregistered from // resolving against nothing and reporting an empty option set as if it were the truth. $is_taxonomy = $attribute_id > 0 && taxonomy_exists( $name ); if ( $is_taxonomy ) { $slugs = array(); foreach ( $options as $option ) { $term = aafm_wc_find_attribute_term( $option, $name ); if ( $term instanceof \WP_Term ) { $slugs[] = (string) $term->slug; } } $options = $slugs; } return array( 'name' => $name, 'taxonomy' => $is_taxonomy, 'options' => array_values( array_map( 'sanitize_text_field', array_map( 'strval', $options ) ) ), ); } /** * The shared output_schema properties for the full single-product shape - the exact field set * aafm_rich_wc_product() emits. Reused by the get/create/update output_schemas so all three stay in * lockstep with the rich assembler. `attributes` is an object (an empty map encodes as {}); the * list-shaped fields are arrays of integers. * * @return array> */ function aafm_wc_product_output_properties(): array { return array( 'id' => array( 'type' => 'integer' ), 'name' => array( 'type' => 'string' ), 'sku' => array( 'type' => 'string' ), 'price' => array( 'type' => 'string' ), 'stock_status' => array( 'type' => 'string' ), 'status' => array( 'type' => 'string' ), 'categories' => array( 'type' => 'array', 'items' => array( 'type' => 'integer' ), ), 'featured' => array( 'type' => 'boolean' ), 'type' => array( 'type' => 'string' ), 'description' => array( 'type' => 'string' ), 'short_description' => array( 'type' => 'string' ), 'regular_price' => array( 'type' => 'string' ), 'sale_price' => array( 'type' => 'string' ), 'manage_stock' => array( 'type' => 'boolean' ), 'stock_quantity' => array( 'type' => array( 'integer', 'null' ) ), 'tags' => array( 'type' => 'array', 'items' => array( 'type' => 'integer' ), ), 'image_id' => array( 'type' => 'integer' ), 'images' => array( 'type' => 'array', 'items' => array( 'type' => 'integer' ), ), 'attributes' => array( 'type' => 'object', // Keys are attribute slugs; each value is a {name, taxonomy, options[]} triple. The key // set is product-defined, so the map is open and the value shape is declared here (A3). 'additionalProperties' => array( 'type' => 'object', 'properties' => array( 'name' => array( 'type' => 'string' ), 'taxonomy' => array( 'type' => 'boolean', 'description' => 'True when this is a global (taxonomy-backed) attribute shared across products, false when it is a custom attribute defined on this product alone. The two behave differently on write: a custom attribute\'s options can be edited through wc-update-product, a global one\'s cannot.', ), 'options' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ), 'description' => 'The attribute\'s declared values, always in the form every write path here accepts. For a global attribute these are term SLUGS (the form wc-create-product-variation expects), not term ids or display names; for a custom attribute they are the literal option strings.', ), ), ), ), 'variation_ids' => array( 'type' => 'array', 'items' => array( 'type' => 'integer' ), 'description' => __( 'Ids of this product\'s variations. Populated only for variable products; every other type (including grouped, whose children are separate products, not variations) reports an empty list.', 'agent-abilities-for-mcp' ), ), ); } /** * Args for aafm/wc-list-products. * * @return array */ function aafm_args_wc_list_products(): array { return array( 'label' => aafm_ability_label( 'aafm/wc-list-products' ), 'description' => aafm_ability_description( 'aafm/wc-list-products' ), 'category' => 'aafm-reads', 'input_schema' => array( 'type' => 'object', 'properties' => array_merge( aafm_pagination_schema_props( 100, __( 'Number of products per page, 1 to 100. Defaults to 20.', 'agent-abilities-for-mcp' ), __( 'Page number of products to return, 1-indexed. Defaults to 1.', 'agent-abilities-for-mcp' ) ), array( 'status' => array( 'type' => 'string', 'description' => "Status filter; 'any' returns all states.", 'enum' => array( 'any', 'publish', 'draft', 'pending', 'private' ), ), ), aafm_lang_schema_fragment() ), 'additionalProperties' => false, ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'products' => array( 'type' => 'array', 'items' => array( 'type' => 'object', 'properties' => array( 'id' => array( 'type' => 'integer' ), 'name' => array( 'type' => 'string' ), 'sku' => array( 'type' => 'string' ), 'price' => array( 'type' => 'string' ), 'stock_status' => array( 'type' => 'string' ), 'status' => array( 'type' => 'string' ), 'categories' => array( 'type' => 'array', 'items' => array( 'type' => 'integer' ), ), 'featured' => array( 'type' => 'boolean' ), ), 'additionalProperties' => false, ), ), 'total' => array( 'type' => 'integer' ), 'language' => array( 'type' => array( 'string', 'null' ), 'description' => __( 'The WPML language the list was scoped to ("all" for every language), or null when WPML is inactive.', 'agent-abilities-for-mcp' ), ), ), ), 'execute_callback' => 'aafm_exec_wc_list_products', 'permission_callback' => 'aafm_wc_perm', 'meta' => array( 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ), ), ); } /** * Execute aafm/wc-list-products. * * @param array $input Validated input. * @return array|\WP_Error */ function aafm_exec_wc_list_products( array $input ) { $lang = aafm_resolve_lang( $input ); if ( is_wp_error( $lang ) ) { return $lang; } $out = array( 'products' => array(), 'total' => 0, 'language' => $lang, ); if ( ! function_exists( 'wc_get_products' ) ) { return $out; } $paging = aafm_paginate_args( $input + array( 'per_page' => 20 ), AAFM_TERMS_PER_PAGE_MAX ); $per_page = $paging['per_page']; $page = $paging['page']; $status = isset( $input['status'] ) ? sanitize_key( (string) $input['status'] ) : 'any'; $build_page = static function () use ( $per_page, $page, $status ) { return wc_get_products( array( 'limit' => $per_page, 'page' => $page, 'status' => $status, 'paginate' => true, ) ); }; // With paginate => true WooCommerce returns an object carrying ->products (the page) and ->total // (the full matching count); total is the grand total for pagination, not the page row count. // // aafm_redact_wc_product() must // run INSIDE the query's own aafm_with_language() scope, not after it restores to ambient - // on both branches. WooCommerce's get_name(), get_price(), and get_category_ids() all apply // vendor filters a theme or plugin can key off ambient language, same defect class as // aafm_exec_get_posts() in posts.php. $shape_language = static function ( ?string $code ) use ( $build_page ): array { return aafm_with_language( $code, static function () use ( $build_page ): array { /** * The raw WooCommerce product query result. * * @var WC_Product[]|\stdClass $query */ $query = $build_page(); $page_items = is_object( $query ) ? (array) $query->products : (array) $query; $rows = array(); foreach ( $page_items as $product ) { if ( $product instanceof \WC_Product ) { $rows[] = aafm_redact_wc_product( $product ); } } return array( 'rows' => $rows, 'found' => is_object( $query ) ? (int) $query->total : count( $page_items ), ); } ); }; if ( 'all' === $lang ) { foreach ( aafm_wpml_all_language_codes_for_iteration() as $code ) { $shaped = $shape_language( $code ); $out['products'] = array_merge( $out['products'], $shaped['rows'] ); $out['total'] += $shaped['found']; } } else { $shaped = $shape_language( $lang ); $out['products'] = $shaped['rows']; $out['total'] = $shaped['found']; } return $out; } /** * Args for aafm/wc-get-product. * * @return array */ function aafm_args_wc_get_product(): array { return array( 'label' => aafm_ability_label( 'aafm/wc-get-product' ), 'description' => aafm_ability_description( 'aafm/wc-get-product' ), 'category' => 'aafm-reads', 'input_schema' => array( 'type' => 'object', 'properties' => array( 'product_id' => array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'The WooCommerce product id to read.', 'agent-abilities-for-mcp' ), ), ), 'required' => array( 'product_id' ), 'additionalProperties' => false, ), 'output_schema' => array( 'type' => 'object', 'properties' => aafm_wc_product_output_properties(), ), 'execute_callback' => 'aafm_exec_wc_get_product', 'permission_callback' => 'aafm_wc_perm', 'meta' => array( 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ), ), ); } /** * Execute aafm/wc-get-product. * * @param array $input Validated input. * @return array|WP_Error */ function aafm_exec_wc_get_product( array $input ) { $product = aafm_wc_get_product( (int) ( $input['product_id'] ?? 0 ) ); if ( null === $product ) { return aafm_generic_error(); } return aafm_rich_wc_product( $product ); } /** * The shared writable product-field properties for the create/update input schemas. * * MEDIUM-4: every nested object/array-of-objects here is itself additionalProperties:false. The * `attributes` items ({name, options}) close their own schema so a smuggled key inside an attribute * is rejected before execute, not just a smuggled top-level field. `images` is a flat int list (no * nested object to close). The top-level schema layered on top is also closed by each args builder. * * @return array> */ function aafm_wc_product_write_properties(): array { return array( 'type' => array( 'type' => 'string', 'enum' => array( 'simple', 'grouped', 'external', 'variable' ), ), 'status' => array( 'type' => 'string', 'description' => "The product's publish state.", 'enum' => array( 'publish', 'draft', 'pending', 'private' ), ), 'description' => array( 'type' => 'string', 'description' => __( "The product's full description, shown on the single product page. Accepts the same HTML as post content.", 'agent-abilities-for-mcp' ), ), 'short_description' => array( 'type' => 'string', 'description' => __( 'A short summary shown near the price on the single product page. Accepts limited HTML.', 'agent-abilities-for-mcp' ), ), 'sku' => array( 'type' => 'string', 'description' => __( "The product's SKU (stock keeping unit). WooCommerce requires SKUs to be unique across products.", 'agent-abilities-for-mcp' ), ), 'regular_price' => array( 'type' => 'string', // Empty string is deliberately accepted alongside a decimal: it is WooCommerce's own // way of clearing a price. set_regular_price() runs the value through // wc_format_decimal(), which returns '' unchanged for an empty input rather than // rejecting it, and aafm_reserved_post_meta_routes() tells an agent to clear // `_regular_price` by sending exactly that. A pattern that only matched a populated // decimal made that documented route impossible to call. 'pattern' => '^$|^\\d+(\\.\\d{1,2})?$', 'description' => 'A decimal price as a string, e.g. "19.99" (no currency symbol or thousands separator), or an empty string to clear the price.', ), 'sale_price' => array( 'type' => 'string', // Same reasoning as regular_price above: an empty string is the normal way to end a // sale (clear the sale price) rather than an invalid one. 'pattern' => '^$|^\\d+(\\.\\d{1,2})?$', 'description' => 'A decimal price as a string, e.g. "14.99" (must be at or below regular_price to take effect), or an empty string to clear the sale price.', ), 'stock_status' => array( 'type' => 'string', 'enum' => array( 'instock', 'outofstock', 'onbackorder' ), 'description' => __( 'Whether the product is in stock, out of stock, or on backorder.', 'agent-abilities-for-mcp' ), ), 'stock_quantity' => array( 'type' => 'integer', 'minimum' => 0, 'description' => 'On-hand quantity (only applied when manage_stock is true).', ), 'manage_stock' => array( 'type' => 'boolean', 'description' => __( 'Whether WooCommerce tracks a numeric stock_quantity for this product.', 'agent-abilities-for-mcp' ), ), 'featured' => array( 'type' => 'boolean', 'description' => __( "Whether the product is marked as featured (used by 'featured products' widgets and shortcodes).", 'agent-abilities-for-mcp' ), ), 'categories' => array( 'type' => 'array', 'items' => array( 'type' => 'integer', 'minimum' => 1, ), 'description' => __( "Product category term ids. Replaces the product's current categories.", 'agent-abilities-for-mcp' ), ), 'tags' => array( 'type' => 'array', 'items' => array( 'type' => 'integer', 'minimum' => 1, ), 'description' => __( "Product tag term ids. Replaces the product's current tags.", 'agent-abilities-for-mcp' ), ), 'image_id' => array( 'type' => 'integer', 'minimum' => 0, 'description' => __( "Attachment id to use as the product's main image.", 'agent-abilities-for-mcp' ), ), 'images' => array( 'type' => 'array', 'items' => array( 'type' => 'integer', 'minimum' => 1, ), 'description' => __( "Attachment ids for the product's image gallery, in display order. Replaces the current gallery.", 'agent-abilities-for-mcp' ), ), 'attributes' => array( 'type' => 'array', 'items' => array( 'type' => 'object', 'properties' => array( 'name' => array( 'type' => 'string', 'description' => __( 'Display name of the custom attribute, for example "Material". This is also the key it is upserted by, so reusing an existing name updates that attribute rather than adding a second one.', 'agent-abilities-for-mcp' ), ), 'options' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ), 'description' => __( 'The attribute\'s possible values, for example ["Cotton", "Wool"]. Sending this replaces that attribute\'s full option list rather than appending to it.', 'agent-abilities-for-mcp' ), ), ), 'required' => array( 'name' ), // MEDIUM-4: close the nested attribute object so a smuggled key is rejected. 'additionalProperties' => false, ), 'description' => __( 'Custom (product-level) attributes as {name, options[]} objects. Each is upserted by name; existing custom attributes not included here are left unchanged, not removed. Global/taxonomy attributes already on the product are not affected by this field.', 'agent-abilities-for-mcp' ), ), ); } /** * Apply a sanitized, validated input map onto a WC_Product via its setters. Only the keys present in * $input are written (PATCH semantics), so an update leaves unsent fields intact. Every value is * sanitized for its kind before it reaches a setter; caller input never reaches a setter raw. * * WC_Product::set_sku() throws WC_Data_Exception when the SKU collides with another product * (abstract-wc-product.php: wc_product_has_unique_sku() fails). Caught here rather than left to * surface as an uncaught exception; every other setter in this function is not known to throw. * * @param \WC_Product $product The product to mutate. * @param array $input Validated input (already schema-checked). * @return \WP_Error|null Null on success, or a WP_Error naming the conflicting SKU. */ function aafm_wc_apply_product_input( \WC_Product $product, array $input ): ?\WP_Error { if ( array_key_exists( 'name', $input ) ) { $product->set_name( aafm_sanitize_plain_text( (string) $input['name'] ) ); } if ( array_key_exists( 'status', $input ) ) { $status = sanitize_key( (string) $input['status'] ); // The operator's force-draft setting covers products too: an explicit request // for a publish-equivalent status is coerced to draft, mirroring the update-post // behaviour. A request that only repeats the product's current status, or an update with // no status field, leaves a live product live. $is_same = $product->get_id() > 0 && $product->get_status() === $status; if ( aafm_force_draft() && ! $is_same && aafm_status_requires_publish_cap( $status ) ) { $status = 'draft'; } $product->set_status( $status ); } if ( array_key_exists( 'sku', $input ) ) { $sku = aafm_sanitize_plain_text( (string) $input['sku'] ); try { $product->set_sku( $sku ); } catch ( \WC_Data_Exception $e ) { return new \WP_Error( 'aafm_wc_duplicate_sku', sprintf( /* translators: %s: the conflicting SKU value. */ __( 'The SKU "%s" is already in use by another product.', 'agent-abilities-for-mcp' ), $sku ) ); } } // WooCommerce stores these two fields as the product post's post_content/post_excerpt, // so they go through the same block-content guard every other // post_content write uses -- strict mode refuses markup that would show as invalid in the // editor instead of silently storing it. if ( array_key_exists( 'description', $input ) ) { // The sanitizer's own warnings are dropped with the guard's: a WooCommerce response // carries no content_warnings key. $description = aafm_kses_block_markup( (string) $input['description'] )['content']; $guard = aafm_block_guard_evaluate( $description ); if ( $guard['error'] instanceof \WP_Error ) { return $guard['error']; } // WooCommerce's data store passes the description to wp_insert_post()/wp_update_post() // unslashed, and both unslash it; slash it here so block attribute escapes keep their backslash. $product->set_description( wp_slash( $description ) ); } if ( array_key_exists( 'short_description', $input ) ) { $short_description = wp_kses_post( (string) $input['short_description'] ); $guard = aafm_block_guard_evaluate( $short_description ); if ( $guard['error'] instanceof \WP_Error ) { return $guard['error']; } $product->set_short_description( $short_description ); } if ( array_key_exists( 'regular_price', $input ) ) { $product->set_regular_price( aafm_wc_sanitize_price( $input['regular_price'] ) ); } if ( array_key_exists( 'sale_price', $input ) ) { $product->set_sale_price( aafm_wc_sanitize_price( $input['sale_price'] ) ); } // WooCommerce admin refuses a sale price above the regular price, and the store otherwise drops it // while the call reads as a success. Checked on the RESULTING pair, so a request that sends only // the sale price is held against the stored regular price. Only when a price was sent, so an // unrelated edit to a product another plugin left in this state still goes through. if ( array_key_exists( 'regular_price', $input ) || array_key_exists( 'sale_price', $input ) ) { $regular = (string) $product->get_regular_price(); $sale = (string) $product->get_sale_price(); if ( '' !== $regular && '' !== $sale && (float) $sale > (float) $regular ) { return new \WP_Error( 'aafm_wc_sale_above_regular', __( 'The sale price cannot be higher than the regular price, so nothing was saved. Lower the sale price or raise the regular price.', 'agent-abilities-for-mcp' ), array( 'status' => 400 ) ); } } // stock_status is derived by WooCommerce from stock_quantity whenever stock is managed, so // validate_props() overwrites a caller-supplied stock_status on save. Refuse the contradictory // pair rather than report a success that never applied. $manage_after = array_key_exists( 'manage_stock', $input ) ? (bool) $input['manage_stock'] : (bool) $product->get_manage_stock(); if ( array_key_exists( 'stock_status', $input ) && $manage_after ) { return new \WP_Error( 'aafm_stock_status_derived', __( 'stock_status cannot be set while manage_stock is true: WooCommerce derives it from stock_quantity. Set stock_quantity instead, or set manage_stock to false.', 'agent-abilities-for-mcp' ) ); } if ( array_key_exists( 'stock_status', $input ) ) { $product->set_stock_status( sanitize_key( (string) $input['stock_status'] ) ); } if ( array_key_exists( 'stock_quantity', $input ) ) { $product->set_stock_quantity( (int) $input['stock_quantity'] ); } if ( array_key_exists( 'manage_stock', $input ) ) { $product->set_manage_stock( (bool) $input['manage_stock'] ); } if ( array_key_exists( 'featured', $input ) ) { $product->set_featured( (bool) $input['featured'] ); } if ( array_key_exists( 'categories', $input ) ) { $product->set_category_ids( array_map( 'absint', (array) $input['categories'] ) ); } if ( array_key_exists( 'tags', $input ) ) { $product->set_tag_ids( array_map( 'absint', (array) $input['tags'] ) ); } if ( array_key_exists( 'image_id', $input ) ) { $product->set_image_id( absint( $input['image_id'] ) ); } if ( array_key_exists( 'images', $input ) ) { $product->set_gallery_image_ids( array_map( 'absint', (array) $input['images'] ) ); } $remove = array_key_exists( 'remove_attributes', $input ) ? (array) $input['remove_attributes'] : array(); if ( array_key_exists( 'attributes', $input ) || array() !== $remove ) { $sanitized = aafm_wc_sanitize_attributes( (array) ( $input['attributes'] ?? array() ) ); // TWO collections, and the difference between them is the entire fix. // // get_attributes() defaults to 'view', which runs woocommerce_product_get_attributes, so // what it returns is what an extension wants DISPLAYED. Carrying those objects into // set_attributes() persists presentation as state, and for a taxonomy attribute that is not // merely untidy: saving one routes through WC_Product_Attribute::get_terms(), which resolves // each option by name and calls wp_insert_term() on a miss, so a display-only string becomes // a real term. Measured: an unchanged echo created a "display-swatch" term. // // So $shown answers exactly one question, did the caller send back what we showed them, and // $stored answers every other, which attributes are really global and which objects are // safe to write. // // WHAT THIS CANNOT FIX, stated so nobody claims more for it later. WooCommerce's own data // store re-reads $product->get_attributes() in VIEW context while saving // (WC_Product_Data_Store_CPT::update_attributes()), so once an attribute change is recorded, // the vendor persists whatever the display filter returns and creates terms for it. Verified // with zero plugin code: a plain WC_Product::save() after an ordinary attribute edit, with // such a filter active, creates the term by itself. What this fix does is make the UNCHANGED // echo record no change at all, which is why the vendor's save path is never entered for it. // A request that genuinely edits some other attribute still goes through WooCommerce, and // that outcome is WooCommerce's to define, not this plugin's to override. $shown = (array) $product->get_attributes(); $stored = (array) $product->get_attributes( 'edit' ); $attribute_error = aafm_wc_global_attribute_change_error( $sanitized, $stored, $shown ); if ( null !== $attribute_error ) { return $attribute_error; } if ( array() !== $remove ) { $stored = aafm_wc_attributes_without( $product, $stored, $remove, $sanitized ); if ( is_wp_error( $stored ) ) { return $stored; } } $product->set_attributes( aafm_wc_build_product_attributes( $sanitized, $stored ) ); } return null; } /** * The stored attributes minus the ones a remove_attributes request names, by name or slug (a global * attribute also by its name without the pa_ prefix). Refuses an unknown name, a name the same call * also sends in attributes, and an attribute any variation of the product uses, naming the variations. * * @param \WC_Product $product The product. * @param array $stored Its stored attributes (edit context). * @param array $names The names or slugs to remove. * @param array> $sanitized The attributes the same call sends. * @return array|\WP_Error What stays. */ function aafm_wc_attributes_without( \WC_Product $product, array $stored, array $names, array $sanitized ) { $by_slug = aafm_wc_attributes_by_slug( $stored ); $remove = array(); $unknown = array(); foreach ( $names as $name ) { $name = aafm_sanitize_plain_text( is_scalar( $name ) ? (string) $name : '' ); $slug = sanitize_title( $name ); if ( ! isset( $by_slug[ $slug ] ) && isset( $by_slug[ 'pa_' . $slug ] ) ) { $slug = 'pa_' . $slug; } if ( '' === $slug || ! isset( $by_slug[ $slug ] ) ) { $unknown[] = $name; continue; } $remove[ $slug ] = true; } if ( array() !== $unknown ) { return new \WP_Error( 'aafm_wc_unknown_attribute', /* translators: %s: comma-separated attribute names the product does not have. */ sprintf( __( 'This product has no attribute named %s, so nothing was saved.', 'agent-abilities-for-mcp' ), implode( ', ', $unknown ) ), array( 'status' => 400 ) ); } foreach ( $sanitized as $item ) { if ( isset( $remove[ sanitize_title( (string) ( $item['name'] ?? '' ) ) ] ) ) { return new \WP_Error( 'aafm_wc_attribute_remove_and_update', __( 'The same attribute cannot be removed and sent in one call, so nothing was saved.', 'agent-abilities-for-mcp' ), array( 'status' => 400 ) ); } } // A variation keys its chosen values by attribute slug. A variation that cannot be loaded counts // as using every attribute, so a failed read never strands one. Any variable product type has // variations (a variable subscription too); a grouped product's children are not variations. // get_children() lists only published and private variations, so the draft and pending ones (the // WooCommerce REST API creates them) are added from the posts table: the statuses 'any' covers // minus those two, so trash and auto-draft stay out. At most 1,000 are checked; with more the call // refuses, because an unchecked variation could lose an attribute it still uses. $in_use = array(); if ( is_a( $product, 'WC_Product_Variable' ) || 0 === strpos( (string) $product->get_type(), 'variable' ) ) { $drafts = get_posts( array( 'post_parent' => $product->get_id(), 'post_type' => 'product_variation', 'post_status' => array_values( array_diff( get_post_stati( array( 'exclude_from_search' => false ) ), array( 'publish', 'private' ) ) ), 'fields' => 'ids', 'numberposts' => 1001, // phpcs:ignore WordPress.WP.PostsPerPage.posts_per_page_numberposts -- ids only, capped one past the limit so a larger set refuses. ) ); if ( count( $drafts ) > 1000 ) { return new \WP_Error( 'aafm_wc_attribute_too_many_variations', __( 'This product has more than 1,000 unpublished variations, too many to check, so nothing was saved. Remove the attribute in WooCommerce instead.', 'agent-abilities-for-mcp' ), array( 'status' => 400 ) ); } $children = array_unique( array_map( 'intval', array_merge( (array) $product->get_children(), $drafts ) ) ); foreach ( $children as $child_id ) { $variation = aafm_wc_get_variation( $child_id ); $chosen = null === $variation ? null : (array) $variation->get_attributes(); foreach ( array_keys( $remove ) as $slug ) { if ( null === $chosen || array_key_exists( $slug, $chosen ) ) { $in_use[ $slug ][] = $child_id; } } } } if ( array() !== $in_use ) { $parts = array(); foreach ( $in_use as $slug => $ids ) { $parts[] = $slug . ' (' . implode( ', ', $ids ) . ')'; } return new \WP_Error( 'aafm_wc_attribute_in_use', /* translators: %s: attribute slugs, each with the ids of the variations that use it. */ sprintf( __( 'Variations use these attributes, so nothing was saved: %s. Delete or change those variations first.', 'agent-abilities-for-mcp' ), implode( '; ', $parts ) ), array( 'status' => 409 ) ); } return array_values( array_diff_key( $by_slug, $remove ) ); } /** * Index a product's attributes by slug, dropping anything that cannot become a WC_Product_Attribute. * * @param array $attributes A product's attribute collection. * @return array */ function aafm_wc_attributes_by_slug( array $attributes ): array { $by_slug = array(); foreach ( $attributes as $attribute ) { $object = aafm_wc_coerce_product_attribute( $attribute ); if ( null === $object || '' === (string) $object->get_name() ) { continue; } $by_slug[ sanitize_title( (string) $object->get_name() ) ] = $object; } return $by_slug; } /** * Refuse an attempt to change a GLOBAL attribute's options through a field that cannot express one. * * The `attributes` input models a custom attribute and nothing else: a name and a list of literal * option strings. A global attribute's options are not strings, they are terms in a taxonomy shared * across every product that uses it, so the field has no way to say what the caller means. The old * behaviour was to accept the write anyway and rebuild the attribute with set_id( 0 ), which * silently DEMOTED it to a local attribute: `_product_attributes` flipped `is_taxonomy` 1 to 0, the * product stopped being connected to the shared taxonomy, and every existing variation keyed on it * was left holding a value the product no longer declared. Nothing in the response said so. * * Resending an attribute UNCHANGED is not refused. That is the ordinary read-modify-write turn -- * read a product, change the price, send the body back -- and it has to stay lossless, so an echo * whose options are already the STORED set is accepted and applied as a no-op by * aafm_wc_build_product_attributes(). Only a genuine attempted CHANGE is refused, because that is * the one this field cannot carry out. * * The comparison runs against aafm_wc_attribute_shape(), the same function the read path emits * from, so the two halves cannot drift into disagreeing about what "unchanged" means. Order is not * significant: a taxonomy attribute's option order is not stored on the product at all (its * `value` is empty and the terms live in the object-term relationship), so a reordered echo is the * same set and refusing it would be pedantry. * * STORED IS THE ONLY REFERENCE A WRITE CAN BE JUDGED AGAINST, and getting that wrong is what R7B-1 * was. This comparison used to run against $shown, on the reasoning that $shown is what the caller * echoed. It is, but that reasoning silently assumes they were echoing. When a display filter hides * a stored term the two readings of the same request are indistinguishable from the request alone: * the caller may be handing back the view unchanged, or asking for exactly that set and so for the * hidden term's removal. Guessing "echo" turned the second one into a no-op against stored state, * so the edit was dropped while the same filter shaped a response that looked like it had worked. * Comparing against $stored guesses nothing: a request that already IS the stored set changes * nothing whichever it meant, and everything else is refused. * * $shown still answers two narrower questions, both about the conversation rather than the state. A * slug that is global in $shown but absent from $stored is a filter's invention, and there is no * honest write for it: creating it would promote a display artefact into stored state, so it is * refused with the rest. And a refused set that matches $shown is refused with a different message, * because "send its current options back unchanged" is useless advice to a caller who just did * exactly that; they need to be told a filter is standing between them and the stored state. * * WHAT THIS DOES NOT COVER, so nobody claims more for it later. It is a guard on this one field, not * on display filtering generally. The response to an accepted no-op is still built in view context, * so a filtered product still reads back filtered here exactly as it does through wc-get-product; * what can no longer happen is the combination that made that dangerous, a response confirming the * set the caller ASKED for while storage holds something else, because any set that differs from * stored is now refused before anything is written. Nothing here addresses WooCommerce's own * view-context re-read during a genuine attribute save (see aafm_wc_apply_product_input()). * * THE RULE THIS FUNCTION IS AN INSTANCE OF, worth more than the function: a safety claim resting on * two functions agreeing needs a test on the AGREEMENT, not on each function. The previous version * of this comparison was correct, the shaper it compared against was correct, and the defect lived * in the join between them, where nothing looked. * * @param array> $sanitized Sanitized {name, options[]} items from the input. * @param array $stored The product's PERSISTED attributes (edit context). * @param array $shown The product's attributes as the caller was shown them. * @return \WP_Error|null Null when nothing global is being changed. */ function aafm_wc_global_attribute_change_error( array $sanitized, array $stored, array $shown ): ?\WP_Error { $stored_by_slug = aafm_wc_attributes_by_slug( $stored ); $shown_by_slug = aafm_wc_attributes_by_slug( $shown ); $refused = array(); $masked = array(); foreach ( $sanitized as $item ) { $name = (string) ( $item['name'] ?? '' ); if ( '' === $name ) { continue; } $slug = sanitize_title( $name ); $stored_previous = $stored_by_slug[ $slug ] ?? null; $shown_previous = $shown_by_slug[ $slug ] ?? null; $stored_is_global = $stored_previous instanceof \WC_Product_Attribute && ! empty( aafm_wc_attribute_shape( $stored_previous )['taxonomy'] ); $shown_is_global = $shown_previous instanceof \WC_Product_Attribute && ! empty( aafm_wc_attribute_shape( $shown_previous )['taxonomy'] ); if ( ! $stored_is_global ) { if ( $shown_is_global ) { // Displayed as global, stored as nothing. A filter made it up. $refused[] = $slug; } continue; // Otherwise a custom attribute, or a genuinely new name: both editable here. } // Compare against what is STORED, because that is the only thing a write changes. $sent = array_map( 'strval', array_values( (array) ( $item['options'] ?? array() ) ) ); $stored_options = array_map( 'strval', array_values( (array) aafm_wc_attribute_shape( $stored_previous )['options'] ) ); sort( $sent ); sort( $stored_options ); if ( $sent === $stored_options ) { continue; // Already the stored set: allowed, and applied as a no-op against it. } // Refused either way. Which message the caller gets depends on whether a display filter is // what put them in this position, because that changes what they can usefully do next. $reference = $shown_previous instanceof \WC_Product_Attribute ? $shown_previous : $stored_previous; $displayed = array_map( 'strval', array_values( (array) aafm_wc_attribute_shape( $reference )['options'] ) ); sort( $displayed ); if ( $sent === $displayed ) { $masked[] = $slug; continue; } $refused[] = $slug; } // A masked attribute is reported first and on its own. Its cause is the surprising one and its // remedy is different, and the whole request is refused either way, so a genuine change sent // alongside one is simply refused again, with its own message, on the next attempt. if ( array() !== $masked ) { return new \WP_Error( 'aafm_wc_global_attribute_display_masked', sprintf( /* translators: %s: comma-separated list of global attribute slugs whose displayed options differ from the stored ones. */ __( 'Something on this site is filtering what these global attributes show, so the options you were given for them are not the ones stored: %s. Sending those options back could mean "leave this alone" or it could mean "remove the terms I was not shown", and nothing in the request says which, so it is refused instead of guessed at. To change other fields, leave the attributes field out. Changing a global attribute\'s own options is not available through this plugin; that has to be done in the WooCommerce admin.', 'agent-abilities-for-mcp' ), implode( ', ', $masked ) ) ); } if ( array() === $refused ) { return null; } return new \WP_Error( 'aafm_wc_global_attribute_not_editable', sprintf( /* translators: %s: comma-separated list of global attribute slugs the request tried to change. */ __( 'These are global attributes, shared with every other product that uses them, so their options cannot be changed through this product: %s. This field only describes a product\'s own custom attributes, and it has no way to express a global attribute\'s terms. Changing a global attribute\'s options is not available through this plugin\'s abilities; add or remove the option in the WooCommerce admin under Products > Attributes, then use wc-create-product-variation or wc-update-product-variation here to build variations with it. Send its current options back unchanged to leave it alone.', 'agent-abilities-for-mcp' ), implode( ', ', $refused ) ) ); } /** * Build the WC_Product_Attribute set to write, merging the caller's attributes onto the product's * existing ones by slug. * * WC_Product::set_attributes() keeps ONLY WC_Product_Attribute instances and pre-nulls every * existing attribute key (abstract-wc-product.php set_attributes()). Passing plain {name, options} * arrays therefore silently drops the requested attributes on create, and on update the pre-null * wipes whatever the caller did not resend (orphaning any variations built on those attributes). * This rebuilds each requested attribute as a real object and seeds the set with the existing * attributes so unmentioned ones survive: sent attributes are upserted by slug, unsent ones are * preserved. * * Caller-sent attributes are treated as custom (product-level) attributes: id 0, plain-string * options, visible by default. The input schema only models custom attributes, so a global/taxonomy * attribute the caller does not name is preserved untouched but is never fabricated from strings. * * @param array> $sanitized Sanitized {name, options[]} items from the input. * @param array $existing The product's current attributes (objects or arrays). * @return array */ function aafm_wc_build_product_attributes( array $sanitized, array $existing ): array { if ( ! class_exists( 'WC_Product_Attribute' ) ) { return array(); } // Seed the merged set with the product's existing attributes, keyed by slug, so any the caller // does not resend outlives set_attributes()'s pre-null. $by_slug = array(); $next_pos = 0; foreach ( $existing as $attribute ) { $object = aafm_wc_coerce_product_attribute( $attribute ); if ( null === $object || '' === (string) $object->get_name() ) { continue; } $by_slug[ sanitize_title( (string) $object->get_name() ) ] = $object; $next_pos = max( $next_pos, (int) $object->get_position() + 1 ); } foreach ( $sanitized as $item ) { $name = (string) ( $item['name'] ?? '' ); if ( '' === $name ) { continue; } $slug = sanitize_title( $name ); $previous = $by_slug[ $slug ] ?? null; // A GLOBAL attribute resent unchanged. Anything else global was already refused by // aafm_wc_global_attribute_change_error(), so the only correct action left is to leave the // existing object exactly as it is. Rebuilding it is what caused the damage: the fresh // object below pins set_id( 0 ), and the attribute id IS the taxonomy binding, so a rebuild // demotes a shared attribute to a local one and strands every variation keyed on it. if ( $previous instanceof \WC_Product_Attribute && (int) $previous->get_id() > 0 ) { $by_slug[ $slug ] = $previous; continue; } $object = new \WC_Product_Attribute(); $object->set_id( 0 ); $object->set_name( $name ); $object->set_options( array_values( (array) ( $item['options'] ?? array() ) ) ); if ( $previous instanceof \WC_Product_Attribute ) { // Replacing an existing attribute: keep its visibility, variation flag, and slot so a // value edit does not silently unhide it or drop it from the product's variations. $object->set_visible( (bool) $previous->get_visible() ); $object->set_variation( (bool) $previous->get_variation() ); $object->set_position( (int) $previous->get_position() ); } else { $object->set_visible( true ); $object->set_variation( false ); $object->set_position( $next_pos ); ++$next_pos; } $by_slug[ $slug ] = $object; } return array_values( $by_slug ); } /** * Coerce a stored attribute (a WC_Product_Attribute object or a WC-shaped array) into a * WC_Product_Attribute, so existing attributes can be carried through a merge write. Returns null * for anything that cannot become an attribute. * * @param mixed $attribute Stored attribute. * @return \WC_Product_Attribute|null */ function aafm_wc_coerce_product_attribute( $attribute ): ?\WC_Product_Attribute { if ( ! class_exists( 'WC_Product_Attribute' ) ) { return null; } if ( $attribute instanceof \WC_Product_Attribute ) { return $attribute; } if ( ! is_array( $attribute ) ) { return null; } $object = new \WC_Product_Attribute(); $object->set_id( (int) ( $attribute['id'] ?? 0 ) ); $object->set_name( (string) ( $attribute['name'] ?? '' ) ); $object->set_options( array_values( (array) ( $attribute['options'] ?? array() ) ) ); $object->set_position( (int) ( $attribute['position'] ?? 0 ) ); $object->set_visible( (bool) ( $attribute['visible'] ?? true ) ); $object->set_variation( (bool) ( $attribute['variation'] ?? false ) ); return $object; } /** * Sanitize a list of attribute input items to {name, options[]} maps, dropping anything else. * * @param array $attributes Raw attribute items. * @return array> */ function aafm_wc_sanitize_attributes( array $attributes ): array { $clean = array(); foreach ( $attributes as $attribute ) { if ( ! is_array( $attribute ) ) { continue; } $options = array(); foreach ( (array) ( $attribute['options'] ?? array() ) as $option ) { $options[] = aafm_sanitize_plain_text( (string) $option ); } $clean[] = array( 'name' => aafm_sanitize_plain_text( (string) ( $attribute['name'] ?? '' ) ), 'options' => $options, ); } return $clean; } /** * Args for aafm/wc-create-product. * * @return array */ function aafm_args_wc_create_product(): array { $properties = aafm_wc_product_write_properties(); $properties['name'] = array( 'type' => 'string', 'minLength' => 1, 'description' => __( "The product's title. Required; the product is not created without one.", 'agent-abilities-for-mcp' ), ); // This ability only builds simple products (see aafm_exec_wc_create_product): a non-simple // request is rejected rather than silently downgraded, so the create-only restriction is // documented here rather than on the shared write-properties description, which is also the // base for the update ability's own type description (aafm_args_wc_update_product()). $properties['type']['enum'] = array( 'simple' ); $properties['type']['description'] = __( "The product's type. This ability only creates simple products. For a variable product, create the parent in WooCommerce and add its variations with wc-create-product-variation.", 'agent-abilities-for-mcp' ); return array( 'label' => aafm_ability_label( 'aafm/wc-create-product' ), 'description' => aafm_ability_description( 'aafm/wc-create-product' ), 'category' => 'aafm-writes', 'input_schema' => array( 'type' => 'object', 'properties' => $properties, 'required' => array( 'name' ), 'additionalProperties' => false, ), 'output_schema' => array( 'type' => 'object', 'properties' => aafm_wc_product_output_properties(), ), 'execute_callback' => 'aafm_exec_wc_create_product', 'permission_callback' => 'aafm_wc_perm', 'meta' => array( 'annotations' => array( 'readonly' => false, 'destructive' => false, ), ), ); } /** * Execute aafm/wc-create-product. * * @param array $input Validated input. * @return array|WP_Error */ function aafm_exec_wc_create_product( array $input ) { if ( ! class_exists( 'WC_Product' ) || ! class_exists( 'WC_Product_Simple' ) ) { return aafm_generic_error(); } $name = aafm_sanitize_plain_text( (string) ( $input['name'] ?? '' ) ); if ( '' === $name ) { return aafm_generic_error(); } // This generic create only builds simple products. A variable/grouped/external product is a // different construction (and, for variable, needs variations added afterward), so reject a // non-simple request rather than silently downgrading it to a simple product and reporting // success. The schema enumerates the other types, but they are not honored here. $requested_type = isset( $input['type'] ) ? (string) $input['type'] : 'simple'; if ( 'simple' !== $requested_type ) { return new \WP_Error( 'aafm_wc_unsupported_product_type', __( 'This tool only creates simple products. For a variable product, create the parent in WooCommerce and add its variations with wc-create-product-variation.', 'agent-abilities-for-mcp' ), array( 'status' => 400 ) ); } // WooCommerce's own create path // (WC_REST_Products_Controller::prepare_object_for_database()) never instantiates the bare // WC_Product base class - it builds a WC_Product_Simple when no type or id is given, matching // this ability's exact case. No observable difference either way (WC_Product::get_type() // already defaults to 'simple', and the response is rebuilt from a fresh wc_get_product() read // after save() regardless), but this uses the vendor's own create-path class rather than one it // never uses for a new product. $product = new \WC_Product_Simple(); unset( $input['type'] ); $error = aafm_wc_apply_product_input( $product, $input ); if ( null !== $error ) { return $error; } // WooCommerce defaults an unset status to publish on save, so with the operator's // force-draft setting on, an omitted status must land as draft. An explicit // publish-equivalent request was already coerced inside aafm_wc_apply_product_input(). if ( aafm_force_draft() && ! array_key_exists( 'status', $input ) ) { $product->set_status( 'draft' ); } $id = (int) aafm_wc_write( 'save', array( 'object' => $product, 'entity' => 'product', ) )['returned']; $saved = aafm_wc_get_product( $id ); if ( null === $saved ) { return aafm_generic_error(); } return aafm_rich_wc_product( $saved ); } /** * Args for aafm/wc-update-product. * * @return array */ function aafm_args_wc_update_product(): array { $properties = aafm_wc_product_write_properties(); $properties['product_id'] = array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'The WooCommerce product id to update.', 'agent-abilities-for-mcp' ), ); $properties['name'] = array( 'type' => 'string', 'minLength' => 1, 'description' => __( "The product's title. Omit to leave the existing title unchanged.", 'agent-abilities-for-mcp' ), ); $properties['remove_attributes'] = array( 'type' => 'array', 'description' => __( 'Names or slugs of attributes to remove from this product, for example ["Color"] or ["pa_color"]. An attribute any variation of the product uses is refused, naming those variations, and so is a name the product does not have. A product with more than 1,000 unpublished variations is too many to check, so the removal is refused. Do not send the same attribute in attributes too.', 'agent-abilities-for-mcp' ), 'items' => array( 'type' => 'string', 'minLength' => 1, ), ); // A product's type cannot be changed once created (converting between simple/grouped/ // external/variable is a non-trivial operation this ability does not implement -- see // aafm_exec_wc_update_product()). Sending a value that matches the product's current type is // accepted as a no-op; a mismatched value is refused with an error rather than silently // discarded, so this override replaces the create-facing description (which does not apply // here) with one that is true for update, mirroring the `attributes` override in // aafm_args_wc_update_product_variation() (variations.php). $properties['type']['description'] = __( "The product's current type. A value matching the product's existing type is accepted as a no-op; a different value is rejected with an error, since converting a product between simple, grouped, external, and variable is not supported. Omit this field to leave the type unchanged.", 'agent-abilities-for-mcp' ); return array( 'label' => aafm_ability_label( 'aafm/wc-update-product' ), 'description' => aafm_ability_description( 'aafm/wc-update-product' ), 'category' => 'aafm-writes', 'input_schema' => array( 'type' => 'object', 'properties' => $properties, 'required' => array( 'product_id' ), 'additionalProperties' => false, ), 'output_schema' => array( 'type' => 'object', 'properties' => aafm_wc_product_output_properties(), ), 'execute_callback' => 'aafm_exec_wc_update_product', 'permission_callback' => 'aafm_wc_perm', 'meta' => array( 'annotations' => array( 'readonly' => false, 'destructive' => false, ), ), ); } /** * Execute aafm/wc-update-product. * * @param array $input Validated input. * @return array|WP_Error */ function aafm_exec_wc_update_product( array $input ) { $product = aafm_wc_get_product( (int) ( $input['product_id'] ?? 0 ) ); if ( null === $product ) { return aafm_generic_error(); } // description/short_description are the only two fields // aafm_wc_apply_product_input() routes to this product post's post_content/post_excerpt, so an // EXISTING product owned by a foreign page builder gets the same refusal every other // content-write ability gives -- but only when one of those two fields is actually present. // Checking this unconditionally refused unrelated price/SKU/stock/ // category/status updates on a builder-owned product, which never touch post_content or // post_excerpt and so have nothing for the builder to silently ignore. A brand-new product has // no prior owner, so aafm_exec_wc_create_product() does not need this check either way. if ( array_key_exists( 'description', $input ) || array_key_exists( 'short_description', $input ) ) { $owning_builder = aafm_post_has_foreign_builder_ownership( $product->get_id() ); if ( false !== $owning_builder ) { return aafm_page_builder_owned_error( $owning_builder ); } } // `type` cannot be changed on update -- converting a product between simple/grouped/external/ // variable is a non-trivial operation this ability does not implement. A caller-sent value // matching the product's actual current type is a harmless no-op; a mismatched value used to // be silently discarded (the caller saw success and an unconverted product). Refuse it instead // so a caller trying to change the type learns immediately, rather than papering over the gap. if ( array_key_exists( 'type', $input ) ) { $current_type = $product->get_type(); if ( (string) $input['type'] !== $current_type ) { return aafm_wc_product_type_mismatch_error( $current_type, (string) $input['type'] ); } } unset( $input['product_id'], $input['type'] ); $error = aafm_wc_apply_product_input( $product, $input ); if ( null !== $error ) { return $error; } $id = (int) aafm_wc_write( 'save', array( 'object' => $product, 'entity' => 'product', ) )['returned']; $saved = aafm_wc_get_product( $id ); if ( null === $saved ) { return aafm_generic_error(); } return aafm_rich_wc_product( $saved ); } /** * Build the WP_Error returned when aafm/wc-update-product receives a `type` that does not match * the product's actual current type. Converting a product between simple/grouped/external/ * variable is out of scope for this ability -- a matching value is treated as a no-op elsewhere in * aafm_exec_wc_update_product(); this error is only for a genuine mismatch. * * @param string $current_type The product's actual current type. * @param string $requested_type The type the caller sent. * @return \WP_Error */ function aafm_wc_product_type_mismatch_error( string $current_type, string $requested_type ): \WP_Error { return new \WP_Error( 'aafm_wc_product_type_mismatch', sprintf( /* translators: 1: the product's actual current type. 2: the type the caller requested. */ __( 'This product is a %1$s product and cannot be changed to %2$s -- converting a product between types is not supported. Omit type, or send its current value, to leave it unchanged.', 'agent-abilities-for-mcp' ), $current_type, $requested_type ) ); } /** * Args for aafm/wc-delete-product. * * @return array */ function aafm_args_wc_delete_product(): array { return array( 'label' => aafm_ability_label( 'aafm/wc-delete-product' ), 'description' => aafm_ability_description( 'aafm/wc-delete-product' ), 'category' => 'aafm-writes', 'input_schema' => array( 'type' => 'object', 'properties' => array( 'product_id' => array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'The WooCommerce product id to permanently delete.', 'agent-abilities-for-mcp' ), ), ), 'required' => array( 'product_id' ), 'additionalProperties' => false, ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'id' => array( 'type' => 'integer' ), 'deleted' => array( 'type' => 'boolean' ), ), ), 'execute_callback' => 'aafm_exec_wc_delete_product', 'permission_callback' => 'aafm_perm_wc_delete_product', 'meta' => array( 'annotations' => array( 'readonly' => false, 'destructive' => true, ), ), ); } /** * Whether the current user may delete this specific product object. * * Mirrors the per-object pattern the post abilities use for delete * (aafm_can_delete_post_object() in includes/helpers.php): gate on the object's * own relationship to the caller via the post type's meta capability, not only * a capability floor. WooCommerce registers 'product' with map_meta_cap => true * and its own capability_type ('product'), so current_user_can() resolves * delete_products (own) vs delete_others_products the same way core resolves * delete_posts vs delete_others_posts. * * @param WP_Post $product The product's backing post object. * @return bool */ function aafm_wc_can_delete_product_object( WP_Post $product ): bool { $type = get_post_type_object( $product->post_type ); if ( ! $type instanceof WP_Post_Type || ! $type->map_meta_cap ) { return false; } return aafm_user_can_checked( $type->cap->delete_post, $product->ID ); } /** * Permission for aafm/wc-delete-product: the capability floor (manage_woocommerce) AND * the caller's own relationship to the specific product, not the floor alone. * * A nonexistent id keeps the floor already checked, and execute() reports "not found". While the * product store is exactly WC_Product_Data_Store_CPT, a product whose post does not load exactly * keeps the floor only when a failure-aware query finds its row absent, and is refused otherwise. * An id whose post loads but is not a product keeps the floor, as in 1.7.5. * * Under any store the product is read through WooCommerce inside a checked-read scope, and a * failed metadata load there refuses. WooCommerce's read loads the product's post meta, and core * decides whether a trashed product may be deleted from its `_wp_trash_meta_status` row. * * When the product loads but its backing post does not, the post store refuses; any other store * keeps the capability floor, since it has no post to authorize against. * * @param array $input Ability input. * @return bool */ function aafm_perm_wc_delete_product( array $input ): bool { if ( ! aafm_wc_perm() ) { return false; } $id = isset( $input['product_id'] ) ? absint( $input['product_id'] ) : 0; if ( $id && false !== aafm_wc_store_is_core( 'product' ) && ! aafm_exact_object( 'post', $id ) instanceof WP_Post ) { return aafm_object_absent( 'post', $id ); } $read = aafm_with_checked_reads( static fn(): array => array( 'product' => $id ? aafm_wc_get_product( $id ) : null ), aafm_generic_error() ); if ( is_wp_error( $read ) ) { return false; } $product = $read['product'] ?? null; if ( ! $product instanceof \WC_Product ) { return true; } $post = aafm_exact_object( 'post', $product->get_id() ); if ( ! $post instanceof WP_Post ) { return ! is_a( (string) $product->get_data_store()->get_current_class_name(), 'WC_Product_Data_Store_CPT', true ); } return aafm_wc_can_delete_product_object( $post ); } /** * Execute aafm/wc-delete-product. * * Permanent removal through WooCommerce's own data store: $product->delete( true ). The force flag is * WC's permanent-delete semantics (a product has no recoverable WC trash for this surface). This is * the WooCommerce object's own delete method, NOT the core post force-delete primitive, so it never * touches that governed call site or the source-scan that bans it. * * @param array $input Validated input. * @return array|WP_Error */ function aafm_exec_wc_delete_product( array $input ) { $id = (int) ( $input['product_id'] ?? 0 ); $product = aafm_wc_get_product( $id ); if ( null === $product ) { return aafm_generic_error(); } aafm_wc_write( 'delete', array( 'object' => $product, 'force_delete' => true, 'entity' => 'product', ) ); // WC_Data::delete() returns true whenever a data store exists, and a loaded product always has // one, so its return never signals a store-level failure. Check that the row is really gone. // // Under WooCommerce's own product store the row is the product's post, which wp_delete_post() // inside delete() removes and clears from the cache. A re-read that does not load exactly proves // nothing, so the row counts as deleted only when a failure-aware query finds it absent. // // Any other store is asked through WooCommerce again. WC_Product_Data_Store_CPT::delete() never // calls clear_caches(), so a stale product-instance-cache read is possible in principle. On // WooCommerce 11.0.1 it does not happen: ProductCacheController hooks core's clean_post_cache // action and drops the product-instance cache there (live-probed, twice, on a throwaway product). // That hook is a version-dependent internal, not a documented guarantee, so if a later // WooCommerce ever serves a stale read here, switch this branch to the post-row check above. // A store the registry cannot name certifies nothing. $core = aafm_wc_store_is_core( 'product' ); if ( null === $core ) { return aafm_generic_error(); } if ( $core ? ( aafm_exact_object( 'post', $id ) instanceof WP_Post || ! aafm_object_absent( 'post', $id ) ) : null !== aafm_wc_get_product( $id ) ) { return aafm_generic_error(); } return array( 'id' => $id, 'deleted' => true, ); }