'GET', 'callback' => array( __CLASS__, 'get_assignments' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => array( 'generator' => array( 'sanitize_callback' => 'sanitize_key' ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/assignments/explain', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'explain' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => array( 'generator' => array( 'sanitize_callback' => 'sanitize_key' ), 'subjectType' => array( 'required' => true, 'sanitize_callback' => 'sanitize_key' ), 'subjectId' => array( 'required' => true, 'sanitize_callback' => 'absint' ), 'blueprintId' => array( 'sanitize_callback' => 'absint' ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/assignments/resolve-batch', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'resolve_batch' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/check', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'check' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); } /** * GET /content-structure/assignments?generator= * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function get_assignments( WP_REST_Request $request ) { $generator = (string) $request->get_param( 'generator' ); if ( ! Generators::isValid( $generator ) ) { return self::invalidGeneratorError(); } return self::success( self::assignmentsState( $generator ) ); } /** * GET /content-structure/assignments/explain * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function explain( WP_REST_Request $request ) { $generator = (string) $request->get_param( 'generator' ); $subject_type = (string) $request->get_param( 'subjectType' ); $subject_id = (int) $request->get_param( 'subjectId' ); $manual_id = (int) $request->get_param( 'blueprintId' ); if ( ! Generators::isValid( $generator ) ) { return self::invalidGeneratorError(); } $object_check = self::objectReadCheck( $subject_type, $subject_id ); if ( is_wp_error( $object_check ) ) { return $object_check; } $resolution = static::resolver()->resolve( $generator, array( 'type' => $subject_type, 'id' => $subject_id ), $manual_id > 0 ? $manual_id : null ); return is_wp_error( $resolution ) ? $resolution : self::success( $resolution ); } /** * POST /content-structure/assignments/resolve-batch * * Resolves the effective Blueprint for many products at once, grouped by * outcome — the data behind `GenerationSummary` for a bulk selection. * Uses the same read capability as {@see explain()}: this is * a read-only resolution, not a write. Every id the caller cannot * `edit_post` is dropped before resolution, exactly like {@see explain()}'s * {@see objectReadCheck()} and {@see check()}'s `skipped` list — the * response's `total`/`groups` only ever describe the remaining, * readable ids, and `forbidden` reports how many were dropped. The * {@see AssignmentScope::RESOLVE_BATCH_HARD_CAP} bound is applied here, * ahead of the per-id permission check, so that check runs on at most * the capped id count rather than on the full raw selection — the same * order {@see check()}'s pair cap already enforces ahead of its own * per-id check. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function resolve_batch( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $generator = isset( $body['generator'] ) ? sanitize_key( (string) $body['generator'] ) : ''; if ( ! Generators::isValid( $generator ) ) { return self::invalidGeneratorError(); } $product_ids = self::sanitizeProductIds( $body['productIds'] ?? array() ); if ( empty( $product_ids ) ) { return self::error( 'aipt_blueprint_invalid_product_ids', __( 'At least one product id is required.', 'ai-product-tools' ), 400 ); } $truncated = count( $product_ids ) > AssignmentScope::RESOLVE_BATCH_HARD_CAP; if ( $truncated ) { $product_ids = array_slice( $product_ids, 0, AssignmentScope::RESOLVE_BATCH_HARD_CAP ); } list( $readable_ids, $forbidden ) = self::partitionReadableProducts( $product_ids ); $result = static::scope()->resolveForProducts( $generator, $readable_ids ); $result['forbidden'] = $forbidden; $result['truncated'] = $truncated || $result['truncated']; $result['historyEnabled'] = SnapshotStore::historyCaptureEnabled(); return self::success( $result ); } /** * Drop ids the current user cannot `edit_post`, using the same * per-subject check {@see explain()} applies via {@see objectReadCheck()}. * * @since 2.8.0 * @param int[] $product_ids Candidate product ids. * @return array{0:int[],1:int} Readable ids, in their original order, and how many were dropped. */ private static function partitionReadableProducts( array $product_ids ): array { $readable = array(); $forbidden = 0; foreach ( $product_ids as $product_id ) { if ( true === self::objectReadCheck( 'product', $product_id ) ) { $readable[] = $product_id; } else { ++$forbidden; } } return array( $readable, $forbidden ); } /** * POST /content-structure/check * * The AI-free Blueprint check: measures a page of products' CURRENT * content against their governing Blueprint, for one to five generators * at once. Read-only, like {@see resolve_batch()}: no provider call, no * snapshot write, no result row. Permission is the same USE capability * and nonce as every other read route here, plus a per-product * `edit_post` check — like {@see explain()} — except a forbidden or * missing product is reported in the response's `skipped` list rather * than failing the whole request. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function check( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $generators = self::sanitizeCheckGenerators( $body['generators'] ?? array() ); if ( is_wp_error( $generators ) ) { return $generators; } $product_ids = self::sanitizeProductIds( $body['productIds'] ?? array() ); if ( empty( $product_ids ) ) { return self::error( 'aipt_blueprint_invalid_product_ids', __( 'At least one product id is required.', 'ai-product-tools' ), 400 ); } if ( count( $generators ) * count( $product_ids ) > BlueprintCheckService::MAX_PAIRS ) { return self::error( 'aipt_blueprint_check_too_many', __( 'Check fewer generators or products at once; this request would check too many combinations.', 'ai-product-tools' ), 400 ); } return self::success( static::checkService()->check( $generators, $product_ids ) ); } /** * @param string $generator Generator key. * @return array AssignmentsState. */ private static function assignmentsState( string $generator ): array { $rows = static::assignmentStore()->listForGenerator( $generator ); $store_default = null; $categories = array(); $products = array(); $terms = array(); foreach ( $rows as $row ) { switch ( $row['targetType'] ?? '' ) { case 'store': $store_default = self::assignmentShape( $row, __( 'Store default', 'ai-product-tools' ), null ); break; case 'category': $info = self::termLabelAndCount( (int) $row['targetId'], 'product_cat', ! empty( $row['includeChildren'] ) ); $categories[] = self::assignmentShape( $row, $info['label'], $info['count'] ); break; case 'product': $products[] = self::assignmentShape( $row, self::productLabel( (int) $row['targetId'] ), null ); break; case 'term': $info = self::termLabelAndCount( (int) $row['targetId'], (string) ( $row['taxonomy'] ?? '' ), ! empty( $row['includeChildren'] ) ); $terms[] = self::assignmentShape( $row, $info['label'], $info['count'] ); break; } } $template_key = TemplateCatalog::defaultKey( $generator ); $template = TemplateCatalog::get( $generator, $template_key ); return array( 'generator' => $generator, 'storeDefault' => $store_default, 'builtinDefault' => array( 'templateKey' => $template_key, 'name' => null !== $template ? (string) $template['name'] : $template_key, ), 'categories' => $categories, 'products' => $products, 'terms' => $terms, ); } /** * @param array $row Raw AssignmentStore row. * @param string $target_label Resolved target label. * @param int|null $product_count Product count, when meaningful for this target type. * @return array Assignment. */ private static function assignmentShape( array $row, string $target_label, ?int $product_count ): array { $blueprint = static::blueprintStore()->get( (int) $row['blueprintId'] ); $shape = array( 'id' => (int) $row['id'], 'generator' => (string) $row['generator'], 'blueprintId' => (int) $row['blueprintId'], 'blueprintName' => null !== $blueprint ? (string) $blueprint['name'] : '', 'targetType' => (string) $row['targetType'], 'taxonomy' => (string) $row['taxonomy'], 'targetId' => (int) $row['targetId'], 'targetLabel' => $target_label, 'includeChildren' => (bool) $row['includeChildren'], 'priority' => (int) $row['priority'], 'version' => (int) $row['version'], ); if ( null !== $product_count ) { $shape['productCount'] = $product_count; } return $shape; } /** * @param int $term_id Term id. * @param string $taxonomy Taxonomy name. * @param bool $include_children Whether to sum descendant counts too (best-effort — a product in two descendant categories is counted twice). * @return array{label:string,count:int} */ private static function termLabelAndCount( int $term_id, string $taxonomy, bool $include_children ): array { if ( '' === $taxonomy || ! function_exists( 'get_term' ) ) { /* translators: %d: category (term) id. */ return array( 'label' => sprintf( __( 'Category #%d', 'ai-product-tools' ), $term_id ), 'count' => 0 ); } $term = get_term( $term_id, $taxonomy ); if ( ! $term instanceof \WP_Term ) { /* translators: %d: category (term) id. */ return array( 'label' => sprintf( __( 'Category #%d', 'ai-product-tools' ), $term_id ), 'count' => 0 ); } $count = (int) $term->count; if ( $include_children && function_exists( 'get_term_children' ) ) { $children = get_term_children( $term_id, $taxonomy ); if ( is_array( $children ) ) { foreach ( $children as $child_id ) { $child = get_term( (int) $child_id, $taxonomy ); if ( $child instanceof \WP_Term ) { $count += (int) $child->count; } } } } return array( 'label' => (string) $term->name, 'count' => $count ); } /** * @param int $product_id Product id. * @return string */ private static function productLabel( int $product_id ): string { if ( ! function_exists( 'wc_get_product' ) ) { /* translators: %d: product id. */ return sprintf( __( 'Product #%d', 'ai-product-tools' ), $product_id ); } $product = wc_get_product( $product_id ); if ( $product instanceof \WC_Product ) { return (string) $product->get_name(); } /* translators: %d: product id. */ return sprintf( __( 'Product #%d', 'ai-product-tools' ), $product_id ); } /** * @param string $subject_type 'product'|'term'|'attachment'. * @param int $subject_id Subject id. * @return true|WP_Error */ private static function objectReadCheck( string $subject_type, int $subject_id ) { if ( 'term' === $subject_type ) { if ( ! current_user_can( 'edit_term', $subject_id ) ) { return self::error( 'rest_forbidden', __( 'You do not have permission to view this subject.', 'ai-product-tools' ), 403 ); } return true; } $product_id = $subject_id; if ( 'attachment' === $subject_type && function_exists( 'get_post' ) ) { $post = get_post( $subject_id ); $product_id = ( $post instanceof \WP_Post ) ? (int) $post->post_parent : $subject_id; } if ( ! current_user_can( 'edit_post', $product_id ) ) { return self::error( 'rest_forbidden', __( 'You do not have permission to view this subject.', 'ai-product-tools' ), 403 ); } return true; } /** * Sanitize a request's raw `productIds` value into a distinct list of * positive ids, in the order first seen. The raw input is capped at * {@see self::MAX_RAW_PRODUCT_IDS} entries before dedup even starts, so * an oversized request body cannot force an unbounded loop here. * * @param mixed $raw_ids Raw `productIds` request value. * @return int[] */ private static function sanitizeProductIds( $raw_ids ): array { if ( ! is_array( $raw_ids ) ) { return array(); } if ( count( $raw_ids ) > self::MAX_RAW_PRODUCT_IDS ) { $raw_ids = array_slice( $raw_ids, 0, self::MAX_RAW_PRODUCT_IDS ); } $ids = array(); foreach ( $raw_ids as $raw_id ) { $id = absint( $raw_id ); if ( $id > 0 ) { $ids[ $id ] = true; } } return array_keys( $ids ); } /** * Sanitize and validate a check() request's raw `generators` value: 1 * to {@see BlueprintCheckService::MAX_GENERATORS} unique entries, every * one a {@see BlueprintCheckService::CHECK_GENERATORS} member. * * @param mixed $raw_generators Raw `generators` request value. * @return string[]|WP_Error Deduped generator keys, in first-seen order. */ private static function sanitizeCheckGenerators( $raw_generators ) { $generators = array(); foreach ( (array) $raw_generators as $raw_generator ) { $generator = sanitize_key( (string) $raw_generator ); if ( '' !== $generator && ! in_array( $generator, $generators, true ) ) { $generators[] = $generator; } } $invalid = empty( $generators ) || count( $generators ) > BlueprintCheckService::MAX_GENERATORS || ! empty( array_diff( $generators, BlueprintCheckService::CHECK_GENERATORS ) ); if ( $invalid ) { return self::error( 'aipt_blueprint_invalid_generators', __( 'Choose 1 to 5 content types to check.', 'ai-product-tools' ), 400 ); } return $generators; } /** * @return WP_Error */ private static function invalidGeneratorError(): WP_Error { return self::error( 'aipt_blueprint_invalid_generator', __( 'Unknown content type.', 'ai-product-tools' ), 400 ); } /** * @return AssignmentStore */ protected static function assignmentStore(): AssignmentStore { return new AssignmentStore(); } /** * @return BlueprintStore */ protected static function blueprintStore(): BlueprintStore { return new BlueprintStore(); } /** * @return AssignmentResolver */ protected static function resolver(): AssignmentResolver { return new AssignmentResolver(); } /** * @return AssignmentScope */ protected static function scope(): AssignmentScope { return new AssignmentScope(); } /** * @return BlueprintCheckService */ protected static function checkService(): BlueprintCheckService { return new BlueprintCheckService(); } }