sourceContent = $sourceContent; $this->decisions = $decisions; $this->conflictDetector = $conflictDetector ?? new ConflictDetector(); $this->entitlementPolicy = $entitlementPolicy ?? new EntitlementPolicy(); } /** * @param array{type:string,id:int,productId?:int} $subject Subject. * @param int|null $actor_user_id Acting user id to check instead of the * current user — Automation's only, since * WP-Cron has no logged-in user for * current_user_can() to consult. Every * request-driven path (REST, Abilities, the * product screen) leaves this null and keeps * checking the current user exactly as before. * @return WP_Error|null */ public function checkObjectPermission( array $subject, ?int $actor_user_id = null ): ?WP_Error { $type = (string) ( $subject['type'] ?? '' ); $id = (int) ( $subject['id'] ?? 0 ); $capability = 'term' === $type ? 'edit_term' : 'edit_post'; $allowed = null !== $actor_user_id ? user_can( $actor_user_id, $capability, $id ) : current_user_can( $capability, $id ); if ( $allowed ) { return null; } if ( null !== $actor_user_id ) { $message = 'term' === $type ? __( "This job's creator does not have permission to edit this category.", 'ai-product-tools' ) : __( "This job's creator does not have permission to edit this product.", 'ai-product-tools' ); } else { $message = 'term' === $type ? __( 'You do not have permission to edit this category.', 'ai-product-tools' ) : __( 'You do not have permission to edit this product.', 'ai-product-tools' ); } return new WP_Error( 'aipt_blueprint_forbidden', $message, array( 'status' => 403 ) ); } /** * @param array{type:string,id:int,productId?:int} $subject Subject. * @return array|WP_Error {product:?object,term:?object,images:array,meta:array{type:string,id:int,label:string,editUrl:string}}. */ public function loadSubject( array $subject ) { $type = (string) $subject['type']; $id = (int) $subject['id']; if ( 'term' === $type ) { return $this->loadTermSubject( $id ); } if ( 'attachment' === $type ) { return $this->loadAttachmentSubject( $subject, $id ); } return $this->loadProductSubject( $id ); } /** * @param int $id Term id. * @return array|WP_Error */ private function loadTermSubject( int $id ) { $term = function_exists( 'get_term' ) ? get_term( $id ) : null; if ( ! ( $term instanceof \WP_Term ) ) { return new WP_Error( 'aipt_blueprint_subject_not_found', __( 'This category could not be found.', 'ai-product-tools' ), array( 'status' => 404 ) ); } return array( 'product' => null, 'term' => $term, 'images' => array(), 'meta' => array( 'type' => 'term', 'id' => $id, 'label' => (string) $term->name, 'editUrl' => function_exists( 'admin_url' ) ? admin_url( 'term.php?taxonomy=' . $term->taxonomy . '&tag_ID=' . $id . '&post_type=product' ) : '', ), ); } /** * @param int $id Product id. * @return array|WP_Error */ private function loadProductSubject( int $id ) { $product = $this->resolveProduct( $id ); if ( is_wp_error( $product ) ) { return $product; } return array( 'product' => $product, 'term' => null, 'images' => array(), 'meta' => array( 'type' => 'product', 'id' => $id, 'label' => (string) $product->get_name(), 'editUrl' => function_exists( 'admin_url' ) ? admin_url( 'post.php?post=' . $id . '&action=edit' ) : '', ), ); } /** * @param array{productId?:int} $subject Subject (for an explicit productId). * @param int $id Attachment id. * @return array|WP_Error */ private function loadAttachmentSubject( array $subject, int $id ) { $product_id = isset( $subject['productId'] ) ? (int) $subject['productId'] : 0; if ( $product_id <= 0 && function_exists( 'get_post' ) ) { $post = get_post( $id ); $product_id = ( $post instanceof \WP_Post ) ? (int) $post->post_parent : 0; } $product = $this->resolveProduct( $product_id ); if ( is_wp_error( $product ) ) { return $product; } $all_images = ( new AttachmentContextBuilder() )->imagesForProduct( $product ); $matched = null; foreach ( $all_images as $image ) { if ( (int) $image['attachmentId'] === $id ) { $matched = $image; break; } } if ( null === $matched ) { $matched = array( 'attachmentId' => $id, 'position' => 0, 'isFeatured' => false ); } $label = function_exists( 'get_the_title' ) ? (string) get_the_title( $id ) : ''; if ( '' === $label ) { /* translators: %d: attachment id. */ $label = sprintf( __( 'Image #%d', 'ai-product-tools' ), $id ); } return array( 'product' => $product, 'term' => null, 'images' => array( $matched ), 'meta' => array( 'type' => 'attachment', 'id' => $id, 'label' => $label, 'editUrl' => function_exists( 'admin_url' ) ? admin_url( 'post.php?post=' . $product_id . '&action=edit' ) : '', ), ); } /** * @param int $product_id Product id. * @return \WC_Product|WP_Error */ private function resolveProduct( int $product_id ) { $product = function_exists( 'wc_get_product' ) ? wc_get_product( $product_id ) : false; if ( ! ( $product instanceof \WC_Product ) ) { return new WP_Error( 'aipt_blueprint_subject_not_found', __( 'This product could not be found.', 'ai-product-tools' ), array( 'status' => 404 ) ); } return $product; } /** * @param array $definition Normalized BlueprintDefinition. * @param string $subject_type 'product' | 'term' | 'attachment'. * @param int $subject_id Subject id. * @param float $deadline Unix timestamp deadline. * @param int $blueprint_id Current blueprint id, 0 for an unsaved draft/built-in default. * @return array{sources:array,decisions:array} */ public function buildSourcesAndDecisions( array $definition, string $subject_type, int $subject_id, float $deadline, int $blueprint_id ): array { $items = isset( $definition['sources']['items'] ) && is_array( $definition['sources']['items'] ) ? $definition['sources']['items'] : array(); $source_ids = array(); foreach ( $items as $item ) { $ref = is_array( $item ) ? (string) ( $item['ref'] ?? '' ) : ''; if ( empty( $item['enabled'] ) || 1 !== preg_match( '/^src:(\d+)$/', $ref, $match ) ) { continue; } $source_ids[] = (int) $match[1]; } $sources = array(); if ( ! empty( $source_ids ) && null !== $this->sourceContent ) { $sources = $this->sourceContent->contentForSubject( $source_ids, $subject_type, $subject_id, array( 'deadline' => $deadline, 'allowedDomains' => isset( $definition['sources']['allowedDomains'] ) && is_array( $definition['sources']['allowedDomains'] ) ? $definition['sources']['allowedDomains'] : array(), 'blueprintId' => $blueprint_id, ) ); } $decisions = ( null !== $this->decisions ) ? $this->decisions->listForSubject( $subject_type, $subject_id ) : array(); return array( 'sources' => $sources, 'decisions' => $decisions ); } /** * @param string $generator Generator key. * @param array $definition Normalized BlueprintDefinition (runtime copy). * @param array|null $brand_profile Compiled BrandProfileData, or null. * @param array $subject_data loadSubject()'s result. * @param array $source_bundle buildSourcesAndDecisions()'s result. * @param array $run_options ExecutionRequest run options. * @param float $deadline Unix timestamp deadline. * @param int $max_calls Provider-call budget. * @return array GeneratorInterface context. */ public function buildCtx( string $generator, array $definition, ?array $brand_profile, array $subject_data, array $source_bundle, array $run_options, float $deadline, int $max_calls ): array { $images_result = $this->imagesFor( $generator, $subject_data, $run_options ); $ai_note_result = $this->resolveAiNote( $generator, $subject_data ); return array( 'generator' => $generator, 'definition' => $definition, 'brandProfile' => $brand_profile, 'subject' => $subject_data['meta'], 'product' => $subject_data['product'], 'term' => $subject_data['term'], 'images' => $images_result['images'], 'imageAltGalleryDropped' => $images_result['galleryDropped'], 'aiNote' => $ai_note_result['note'], 'aiNoteDropped' => $ai_note_result['dropped'], 'sources' => $source_bundle['sources'], 'decisions' => $source_bundle['decisions'], 'runOptions' => $run_options, 'conflictDetector' => array( $this->conflictDetector, 'detect' ), 'deadline' => $deadline, 'maxCalls' => $max_calls, ); } /** * Resolve `$ctx['aiNote']`: the product's own {@see MetaKeys::AI_NOTE} * note as the Business build reads it ({@see AI_NOTE_FILTER}), when * `EntitlementPolicy::instructionsAllowed()` allows this generator to * read it - the note reuses that exact per-generator gate, it is never a * second, separate filter. This class only checks whether a note exists, * so a withheld one can be reported. * * A term subject (`$subject_data['product']` is null for Taxonomy, see * `Generators\Support\SubjectContextResolver`) has no product and so * never has a note. An attachment subject's `$subject_data['product']` * is already its PARENT product ({@see loadAttachmentSubject()}), so it * reads that product's note the same way a direct product subject would, * with no special case needed here. * * @param string $generator Generator key. * @param array $subject_data loadSubject()'s result. * @return array{note:string,dropped:bool} `dropped` is true only when a * real, non-empty note existed and the gate withheld it - * never true merely because there was no note to begin with. */ private function resolveAiNote( string $generator, array $subject_data ): array { $product = $subject_data['product'] ?? null; if ( ! ( $product instanceof \WC_Product ) ) { return array( 'note' => '', 'dropped' => false ); } $raw = get_post_meta( $product->get_id(), MetaKeys::AI_NOTE, true ); if ( ! is_string( $raw ) || '' === trim( sanitize_textarea_field( $raw ) ) ) { return array( 'note' => '', 'dropped' => false ); } if ( ! $this->entitlementPolicy->instructionsAllowed( $generator ) ) { return array( 'note' => '', 'dropped' => true ); } $note = apply_filters( 'aipt_content_structure_ai_note', '', $product ); return array( 'note' => is_string( $note ) ? $note : '', 'dropped' => false ); } /** * Images an image_alt run works on. * * An attachment subject is exactly that one image - already an explicit, * single-image selection, so it is never capped by the gallery * entitlement below: the legacy path never re-checks `includeGallery` * for an explicit per-image selection either, only for a product-level * request that must still decide which images to include (see * `Service::bulk_generate_by_selections()` vs `collect_image_ids()`). * * A product subject means every image of the product (featured first, * then gallery) when this site may use gallery images * ({@see EntitlementPolicy::imageAltGalleryAllowed()}), or only its * featured image otherwise - mirroring the legacy free default * `Service::collect_image_ids()` applies before ever reaching the * engine. Either way, `runOptions.attachmentIds` further narrows the * result when the caller selected some; ids that are not in the * (possibly already capped) pool are ignored, so a request can never * reach another product's attachments, and a non-entitled site can * never reach a gallery image this way either. Other generators get no * images. * * @param string $generator Generator key. * @param array $subject_data loadSubject()'s result. * @param array $run_options ExecutionRequest run options. * @return array{images:array,galleryDropped:bool} */ private function imagesFor( string $generator, array $subject_data, array $run_options ): array { if ( Generators::IMAGE_ALT !== $generator ) { return array( 'images' => array(), 'galleryDropped' => false ); } $type = (string) ( $subject_data['meta']['type'] ?? '' ); if ( 'product' !== $type ) { $images = is_array( $subject_data['images'] ?? null ) ? $subject_data['images'] : array(); return array( 'images' => $images, 'galleryDropped' => false ); } $product = $subject_data['product'] ?? null; if ( ! ( $product instanceof \WC_Product ) ) { return array( 'images' => array(), 'galleryDropped' => false ); } $all = ( new AttachmentContextBuilder() )->imagesForProduct( $product ); $gallery_dropped = false; if ( ! $this->entitlementPolicy->imageAltGalleryAllowed() ) { $featured_only = array_values( array_filter( $all, static function ( $image ) { return ! empty( $image['isFeatured'] ); } ) ); $gallery_dropped = count( $featured_only ) < count( $all ); $all = $featured_only; } $selected = isset( $run_options['attachmentIds'] ) && is_array( $run_options['attachmentIds'] ) ? array_map( 'intval', $run_options['attachmentIds'] ) : array(); if ( empty( $selected ) ) { return array( 'images' => $all, 'galleryDropped' => $gallery_dropped ); } $all = array_values( array_filter( $all, static function ( $image ) use ( $selected ) { return in_array( (int) $image['attachmentId'], $selected, true ); } ) ); return array( 'images' => $all, 'galleryDropped' => $gallery_dropped ); } /** * `runOptions.allowExistingDescription` allows the model to read the * subject's own current long description for this run only, without * persisting the change to the saved Blueprint. * * @param string $generator Generator key. * @param array $run_options Run options. * @param array $definition Normalized BlueprintDefinition. * @return array A definition copy, unchanged unless this applies. */ public function applyAllowExistingDescription( string $generator, array $run_options, array $definition ): array { if ( Generators::DESCRIPTION !== $generator || empty( $run_options['allowExistingDescription'] ) ) { return $definition; } $fields = isset( $definition['sources']['productFields'] ) && is_array( $definition['sources']['productFields'] ) ? $definition['sources']['productFields'] : array(); if ( in_array( 'core:description', $fields, true ) ) { return $definition; } $fields[] = 'core:description'; $definition['sources']['productFields'] = $fields; return $definition; } /** * `runOptions.preserveContentImages`: when the Blueprint output replaces * a description that contains ``/`
` elements, those * elements are appended unchanged after the rendered sections * (deterministic, visible in the preview). * * @param string $generator Generator key. * @param array $run_options Run options. * @param mixed $product Resolved subject product, or null. * @param array $slice Generator-specific GenerationResult slice. * @return array The slice, with `outputs.description` extended when applicable. */ public function applyPreserveContentImages( string $generator, array $run_options, $product, array $slice ): array { if ( Generators::DESCRIPTION !== $generator || empty( $run_options['preserveContentImages'] ) ) { return $slice; } if ( ! ( $product instanceof \WC_Product ) || ! isset( $slice['outputs']['description'] ) ) { return $slice; } $preserved = $this->extractImagesAndFigures( (string) $product->get_description() ); if ( '' === $preserved ) { return $slice; } $slice['outputs']['description'] .= $preserved; $slice['findings'][] = ( new OutputValidator() )->finding( 'preserved_existing_images', 'info', __( 'Images from the existing description were kept and appended after the generated sections.', 'ai-product-tools' ) ); return $slice; } /** * Extract `` and `
` elements from already-saved HTML via * DOMDocument (no network, no script execution), then sanitize the * result through the same allowlist {@see Renderer::preserveContentImages()} * uses for its own, regex-based extraction of the same elements: this * runs AFTER {@see Renderer::finalizeHtml()}'s own `wp_kses()` pass has * already finished for the rendered sections, so an existing `` * carrying a live event-handler attribute (e.g. `onerror`) must be * sanitized here — appending its raw outerHTML would otherwise bypass * that pass entirely. * * @param string $html Existing description HTML. * @return string Sanitized, concatenated outerHTML of every matched element, or ''. */ private function extractImagesAndFigures( string $html ): string { if ( '' === trim( $html ) ) { return ''; } if ( false === stripos( $html, 'loadHTML( '' . $html . '', LIBXML_NOERROR | LIBXML_NOWARNING ); libxml_clear_errors(); libxml_use_internal_errors( $previous_internal ); if ( ! $loaded ) { return ''; } $parts = array(); foreach ( array( 'figure', 'img' ) as $tag ) { foreach ( $doc->getElementsByTagName( $tag ) as $node ) { if ( 'img' === $tag && self::hasFigureAncestor( $node ) ) { continue; } $html_part = $doc->saveHTML( $node ); if ( is_string( $html_part ) ) { $parts[] = $html_part; } } } return wp_kses( implode( '', $parts ), Renderer::preservedImageAllowedHtml() ); } /** * Whether $node has a `
` among its ancestors, not only as its * direct parent. WordPress's Image block renders a linked image as * `
`, and a `` wrapper has * the same shape, so a direct-parent check alone misses both. * * @param \DOMNode $node Candidate `` node. * @return bool */ private static function hasFigureAncestor( \DOMNode $node ): bool { for ( $parent = $node->parentNode; null !== $parent; $parent = $parent->parentNode ) { if ( 'figure' === $parent->nodeName ) { return true; } } return false; } /** * @param array $ctx GeneratorInterface context. * @param array $sources_used GenerationResult.sourcesUsed. * @return string sha256 hex digest. */ public function computeContextHash( array $ctx, array $sources_used ): string { $product = $ctx['product'] ?? null; $concurrency_component = ''; if ( $product instanceof \WC_Product && class_exists( '\\AIPT\\Api\\ProductEditor\\ProductEditorConcurrencyToken' ) ) { try { $concurrency_component = \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::for_product( $product ); } catch ( \Throwable $e ) { $concurrency_component = ''; } } $version_parts = array(); foreach ( $sources_used as $source ) { $version_parts[] = (string) ( $source['ref'] ?? '' ) . ':' . (string) ( $source['contentVersion'] ?? 0 ); } sort( $version_parts ); $payload = wp_json_encode( array( 'concurrency' => $concurrency_component, 'sources' => $version_parts, 'subject' => $ctx['subject'] ?? array(), ) ); return hash( 'sha256', false !== $payload ? $payload : '' ); } }