reason = $reason; } /** * Stable machine-readable code for the refusal, or '' when none was given. * * @return string */ public function reason(): string { return $this->reason; } } /** * An applier that can apply a stored option only in its Free form reports it. * * A review approval that appended instead of the staged replace must say so * with the reason, never report a plain success. */ interface ReportsAppliedFreeDefaults { /** * Options the last apply() replaced with their Free default. * * @return array Option key => PlanDenial reason. */ public function appliedFreeDefaults(): array; } /** * Shared "overwrite: 'empty_only'" read for every per-tool applier. * * Mirrors the identical option on the content structure direct apply * adapters (`AIPT\Api\ContentStructure\Apply\ApplyAdapterInterface`): read * from the row's OWN stored `apply_context` — the policy requested when * THIS row was staged — never from a caller-supplied runtime option, so a * stale pending row is still decided by the policy it was staged with. * Default 'replace' (unchanged behavior) when the row carries no * `overwrite` key at all, including every row staged before this option * existed. * * @package AIPT\Core\ContentReview * @since 2.8.0 */ trait EmptyOnlyOverwriteTrait { /** * @param array $row Review row (`apply_context` is a JSON string or null). * @return bool */ private function isEmptyOnlyOverwrite( array $row ): bool { $ctx = $row['apply_context'] ?? null; if ( ! is_string( $ctx ) || '' === $ctx ) { return false; } $decoded = json_decode( $ctx, true ); return is_array( $decoded ) && 'empty_only' === ( $decoded['overwrite'] ?? 'replace' ); } } /** * Shared "fold this row's denormalized blueprint attribution into a * ContentApplyDispatcher::before() payload" helper for every per-tool * applier. `$row` is either a real `aipt_content_review` row (carrying the * columns {@see \AIPT\Core\ContentReview\ContentReviewStore::stage()} * persisted) or a synthetic row built by a content structure apply adapter * (e.g. {@see \AIPT\Api\ContentStructure\Apply\TitleApplyAdapter}) — both * shapes use the same flat `blueprint_id`/`blueprint_name`/ * `blueprint_revision`/`blueprint_builtin` keys, so this helper treats them * identically. Absent for a custom-prompts row, which leaves every value at * its zero/empty default — exactly the shape the snapshot store already * treats as "no blueprint recorded". * * @since 2.8.0 */ trait BlueprintSnapshotFieldsTrait { /** * @param array $row Review row (real or synthetic). * @return array{blueprint_id:int,blueprint_name:string,blueprint_revision:int,blueprint_builtin:bool} */ private function blueprintSnapshotFields( array $row ): array { return array( 'blueprint_id' => isset( $row['blueprint_id'] ) ? (int) $row['blueprint_id'] : 0, 'blueprint_name' => isset( $row['blueprint_name'] ) ? (string) $row['blueprint_name'] : '', 'blueprint_revision' => isset( $row['blueprint_revision'] ) ? (int) $row['blueprint_revision'] : 0, 'blueprint_builtin' => ! empty( $row['blueprint_builtin'] ), ); } } /** * Applies a stored review row to the real product field. * * The applier does NOT change the row's status and does NOT delete it — * ContentReviewStore owns the entire lifecycle. */ interface ContentReviewApplier { /** * Apply a review row to the real product. * * @param array $row The review row from the database. * @return bool True on successful write, false when a write was * attempted but did not land (row stays in_progress). * @throws ContentReviewApplyRefusedException When refused BEFORE any * write is attempted — the row is released back to * pending instead of staying stuck. */ public function apply( array $row ): bool; } /** * Applies a generated description to the product. * * generated_value is a JSON string with keys: description, short_description, tags. * apply_context (JSON) carries options: keepExistingDescription, keepExistingTags, * existingDescriptionPosition, beforeContentText, afterContentText. */ final class DescriptionApplier implements ContentReviewApplier { use EmptyOnlyOverwriteTrait; use BlueprintSnapshotFieldsTrait; /** * @param array $row * @return bool */ public function apply( array $row ): bool { $product_id = (int) ( $row['product_id'] ?? 0 ); if ( ! current_user_can( 'edit_post', $product_id ) ) { throw new ContentReviewApplyRefusedException( __( 'Permission denied.', 'ai-product-tools' ), 'permission_denied' ); } $product = wc_get_product( $product_id ); if ( ! $product ) { throw new ContentReviewApplyRefusedException( __( 'Product not found.', 'ai-product-tools' ), 'product_not_found' ); } $options = $this->parseOptions( $row ); $content = $this->parseContent( $row ); $blocked_by_overwrite = array(); if ( $this->isEmptyOnlyOverwrite( $row ) ) { $content = $this->filterEmptyOnlyContent( $content, $product, $product_id, $blocked_by_overwrite ); } $has_writable_field = false; foreach ( $content as $type => $text ) { if ( empty( $text ) || ! is_string( $text ) || 'tags' === $type ) { continue; } if ( 'description' === $type || 'short_description' === $type ) { $has_writable_field = true; break; } } $has_tags = isset( $content['tags'] ) && ! empty( $content['tags'] ) && is_string( $content['tags'] ); if ( ! $has_writable_field && ! $has_tags ) { if ( ! empty( $blocked_by_overwrite ) ) { throw new ContentReviewApplyRefusedException( __( 'The existing content is no longer empty. Nothing was changed.', 'ai-product-tools' ), 'not_empty' ); } throw new ContentReviewApplyRefusedException( __( 'No applicable content.', 'ai-product-tools' ), 'no_applicable_content' ); } $snapshot_fields = array(); if ( isset( $content['description'] ) && ! empty( $content['description'] ) && is_string( $content['description'] ) ) { $snapshot_fields['description'] = true; } if ( isset( $content['short_description'] ) && ! empty( $content['short_description'] ) && is_string( $content['short_description'] ) ) { $snapshot_fields['short_desc'] = true; } if ( $has_tags ) { $snapshot_fields['tags'] = array( true ); } if ( ! empty( $snapshot_fields ) ) { ContentApplyDispatcher::before( $product_id, array_merge( $snapshot_fields, $this->blueprintSnapshotFields( $row ) ), 'description' ); } $applied_any = false; $description_applied = false; $keep_existing = ! empty( $options['keepExistingDescription'] ); $position = (string) ( $options['existingDescriptionPosition'] ?? 'after' ); $before_text = (string) ( $options['beforeContentText'] ?? '' ); $after_text = (string) ( $options['afterContentText'] ?? '' ); foreach ( $content as $type => $text ) { if ( empty( $text ) || ! is_string( $text ) || 'tags' === $type ) { continue; } $final_content = $text; if ( ! empty( $before_text ) || ! empty( $after_text ) ) { $final_content = $before_text . $final_content . $after_text; } $final_content = \AIPT\Utils\DescriptionSanitizer::clean( $final_content ); if ( $keep_existing ) { $existing = 'short_description' === $type ? $product->get_short_description() : $product->get_description(); if ( ! empty( $existing ) ) { $final_content = 'before' === $position ? $final_content . "\n\n" . $existing : $existing . "\n\n" . $final_content; } } if ( 'short_description' === $type ) { $product->set_short_description( $final_content ); $applied_any = true; $description_applied = true; } elseif ( 'description' === $type ) { $product->set_description( $final_content ); $applied_any = true; $description_applied = true; } } $field_results = array(); if ( $applied_any ) { $save_result = \AIPT\Api\Helpers\ProductSaveVerifier::save( $product ); if ( ! $save_result['landed'] ) { ContentApplyDispatcher::after( $product_id, false ); return false; } if ( isset( $content['description'] ) && ! empty( $content['description'] ) ) { $field_results['description'] = true; } if ( isset( $content['short_description'] ) && ! empty( $content['short_description'] ) ) { $field_results['short_description'] = true; } } if ( $has_tags ) { $field_results['tags'] = $this->applyTags( $product_id, $content['tags'], $options, $this->isBlueprintAttributed( $row ) ); } \AIPT\Core\ContentSnapshots\SnapshotStore::finalizeStagedByField( $product_id, $field_results ); if ( ! in_array( true, $field_results, true ) ) { return false; } if ( ! $applied_any && ! empty( $field_results['tags'] ) ) { SnapshotSubject::fromRow( $row )->bump(); } if ( $description_applied ) { ContentMarkService::mark( $product_id, 'description', array( 'gen' => MetaKeys::GEN_BULK_ADVANCED, 'model' => (string) ( $options['model'] ?? '' ), ) ); } return true; } /** * Parse apply_context JSON into an options array. * * @param array $row * @return array */ private function parseOptions( array $row ): array { $ctx = $row['apply_context'] ?? null; if ( ! is_string( $ctx ) || '' === $ctx ) { return array(); } $decoded = json_decode( $ctx, true ); return is_array( $decoded ) ? $decoded : array(); } /** * Drop fields from `$content` whose LIVE value is already non-empty * (overwrite 'empty_only'). Mirrors * `AIPT\Api\ContentStructure\Apply\DescriptionApplyAdapter`'s identical * per-field skip on the Blueprint direct apply path. * * @param array $content Parsed content, keyed by field. * @param \WC_Product|object $product Live product (duck-typed, matching this class's other product reads). * @param int $product_id Product id. * @param array &$blocked Field names dropped for being non-empty, appended in place. * @return array */ private function filterEmptyOnlyContent( array $content, $product, int $product_id, array &$blocked ): array { foreach ( $content as $type => $text ) { if ( 'description' === $type && '' !== trim( wp_strip_all_tags( (string) $product->get_description() ) ) ) { unset( $content[ $type ] ); $blocked[] = $type; } elseif ( 'short_description' === $type && '' !== trim( wp_strip_all_tags( (string) $product->get_short_description() ) ) ) { unset( $content[ $type ] ); $blocked[] = $type; } elseif ( 'tags' === $type && $this->hasExistingTags( $product_id ) ) { unset( $content[ $type ] ); $blocked[] = $type; } } return $content; } /** * @param int $product_id Product id. * @return bool */ private function hasExistingTags( int $product_id ): bool { $existing = function_exists( 'wp_get_post_terms' ) ? wp_get_post_terms( $product_id, 'product_tag', array( 'fields' => 'ids' ) ) : array(); return is_array( $existing ) && ! empty( $existing ); } /** * Parse generated_value into a content array keyed by target field. * * A row whose generated_value is a JSON object with string keys is * trusted as-is (a multi-field payload). Every other row — in practice * every row ContentGenerator::stageReview() actually stages, which * always writes ONE field's plain-text content per row — is routed by * the row's own canonical `field_type` column instead of being assumed * to be 'description'. Approving a staged short_description or tags row * must update THAT field, never silently overwrite the full description. * * @param array $row * @return array */ private function parseContent( array $row ): array { $raw = (string) ( $row['generated_value'] ?? '' ); if ( '' === $raw ) { return array(); } $decoded = json_decode( $raw, true ); if ( is_array( $decoded ) && ! empty( $decoded ) ) { $keys = array_keys( $decoded ); if ( is_string( reset( $keys ) ) ) { return $decoded; } } $field_type = isset( $row['field_type'] ) ? (string) $row['field_type'] : 'description'; $key = in_array( $field_type, array( 'description', 'short_description', 'tags' ), true ) ? $field_type : 'description'; return array( $key => $raw ); } /** * Whether this row's content came from the Blueprint (content-template) * execution path, from its OWN denormalized blueprint attribution — * set only for a Blueprint-produced row (stageReview()'s "Denormalized * blueprint attribution" comment); a custom-prompts (Advanced) row * carries none of it. * * @param array $row Review row. * @return bool */ private function isBlueprintAttributed( array $row ): bool { return ! empty( $row['blueprint_builtin'] ) || '' !== trim( (string) ( $row['blueprint_name'] ?? '' ) ) || ( (int) ( $row['blueprint_id'] ?? 0 ) ) > 0; } /** * Apply tags to the product. * * @param int $product_id * @param string $tags_string Comma-separated tag names. * @param array $options * @param bool $is_blueprint Whether this row's content came from the Blueprint execution path. * @return bool */ private function applyTags( int $product_id, string $tags_string, array $options, bool $is_blueprint = false ): bool { $tag_names = array_map( 'trim', explode( ',', $tags_string ) ); $tag_names = array_values( array_filter( $tag_names ) ); if ( empty( $tag_names ) ) { return false; } if ( ! $is_blueprint ) { $max_tags = max( 0, (int) get_option( 'aipt_max_tags_count', 3 ) ); $tag_names = array_slice( $tag_names, 0, $max_tags ); } if ( empty( $tag_names ) ) { return false; } $append = ! empty( $options['keepExistingTags'] ); $term_result = wp_set_object_terms( $product_id, array_values( $tag_names ), 'product_tag', $append ); clean_object_term_cache( $product_id, 'product' ); if ( is_wp_error( $term_result ) ) { return false; } if ( ! empty( $term_result ) ) { ContentMarkService::mark( $product_id, 'tags', array( 'gen' => MetaKeys::GEN_BULK_ADVANCED ) ); } return true; } } /** * Applies a generated title to the product. */ final class TitleApplier implements ContentReviewApplier { use EmptyOnlyOverwriteTrait; use BlueprintSnapshotFieldsTrait; /** * @param array $row * @return bool */ public function apply( array $row ): bool { $product_id = (int) ( $row['product_id'] ?? 0 ); if ( ! current_user_can( 'edit_post', $product_id ) ) { throw new ContentReviewApplyRefusedException( __( 'Permission denied.', 'ai-product-tools' ), 'permission_denied' ); } $product = wc_get_product( $product_id ); if ( ! $product ) { throw new ContentReviewApplyRefusedException( __( 'Product not found.', 'ai-product-tools' ), 'product_not_found' ); } $new_title = sanitize_text_field( (string) ( $row['generated_value'] ?? '' ) ); if ( '' === $new_title ) { throw new ContentReviewApplyRefusedException( __( 'No applicable content.', 'ai-product-tools' ), 'no_applicable_content' ); } if ( $this->isEmptyOnlyOverwrite( $row ) && '' !== trim( (string) $product->get_name() ) ) { throw new ContentReviewApplyRefusedException( __( 'The title is not empty.', 'ai-product-tools' ), 'not_empty' ); } $update_slug = false; $ctx = $row['apply_context'] ?? null; if ( is_string( $ctx ) && '' !== $ctx ) { $decoded = json_decode( $ctx, true ); $update_slug = is_array( $decoded ) && ! empty( $decoded['update_slug'] ); } if ( ! $update_slug && $new_title === (string) $product->get_name() ) { return true; } $snapshot_fields = array( 'title' => true ); if ( $update_slug ) { $snapshot_fields['slug'] = true; } ContentApplyDispatcher::before( $product_id, array_merge( $snapshot_fields, $this->blueprintSnapshotFields( $row ) ), 'title' ); $product->set_name( $new_title ); if ( $update_slug ) { $product->set_slug( sanitize_title( $new_title ) ); } $save_result = \AIPT\Api\Helpers\ProductSaveVerifier::save( $product ); if ( ! $save_result['landed'] ) { ContentApplyDispatcher::after( $product_id, false ); return false; } ContentApplyDispatcher::after( $product_id, true ); ContentMarkService::mark( $product_id, 'title', array( 'gen' => MetaKeys::GEN_BULK_ADVANCED ) ); return true; } } /** * Applies generated FAQ content to the product. * * generated_value is a JSON array of FAQ objects [{question, answer}, …]. * apply_context carries writeMode ('append'|'replace'). 'replace' is * premium-gated via apply_filters('aipt_faq_replace_enabled', false) at apply * time. While the license cannot be verified a stored 'replace' is refused * before any write (appending would duplicate the product's FAQs); after a * definitive denial it is applied as 'append' and reported through * appliedFreeDefaults(). */ final class FaqApplier implements ContentReviewApplier, ReportsAppliedFreeDefaults { use EmptyOnlyOverwriteTrait; use BlueprintSnapshotFieldsTrait; /** * Options the last apply() replaced with their Free default. * * @var array */ private $applied_free_defaults = array(); /** * @return array */ public function appliedFreeDefaults(): array { return $this->applied_free_defaults; } /** * @param array $row * @return bool */ public function apply( array $row ): bool { $this->applied_free_defaults = array(); $product_id = (int) ( $row['product_id'] ?? 0 ); if ( ! current_user_can( 'edit_post', $product_id ) ) { throw new ContentReviewApplyRefusedException( __( 'Permission denied.', 'ai-product-tools' ), 'permission_denied' ); } $product = wc_get_product( $product_id ); if ( ! $product ) { throw new ContentReviewApplyRefusedException( __( 'Product not found.', 'ai-product-tools' ), 'product_not_found' ); } $raw = (string) ( $row['generated_value'] ?? '' ); $decoded = json_decode( $raw, true ); if ( ! is_array( $decoded ) ) { throw new ContentReviewApplyRefusedException( __( 'Invalid stored content.', 'ai-product-tools' ), 'invalid_stored_content' ); } $faqs = array(); foreach ( $decoded as $faq ) { if ( ! is_array( $faq ) ) { continue; } $question = sanitize_text_field( (string) ( $faq['question'] ?? '' ) ); $answer = wp_kses_post( (string) ( $faq['answer'] ?? '' ) ); if ( '' !== $question || '' !== $answer ) { $faqs[] = array( 'question' => $question, 'answer' => $answer, ); } } if ( empty( $faqs ) ) { throw new ContentReviewApplyRefusedException( __( 'No applicable content.', 'ai-product-tools' ), 'no_applicable_content' ); } if ( $this->isEmptyOnlyOverwrite( $row ) && $this->hasExistingFaq( $product_id ) ) { throw new ContentReviewApplyRefusedException( __( 'FAQ content is not empty.', 'ai-product-tools' ), 'not_empty' ); } $ctx = $this->parseContext( $row ); $write_mode = (string) ( $ctx['writeMode'] ?? 'append' ); if ( 'replace' !== $write_mode ) { $write_mode = 'append'; } if ( 'replace' === $write_mode && ! apply_filters( 'aipt_faq_replace_enabled', false ) ) { $reason = \AIPT\Core\Licensing\PlanDenial::reason( 'faqReplaceMode', \AIPT\Core\Licensing\PlanDenial::PLAN_PAID ); if ( \AIPT\Core\Licensing\PlanDenial::isVerificationUnavailable( $reason ) ) { throw new ContentReviewApplyRefusedException( \AIPT\Core\Licensing\PlanDenial::message( $reason, '' ), $reason ); } $write_mode = 'append'; $this->applied_free_defaults['writeMode'] = $reason; } $release = \AIPT\Api\Helpers\ProductWriteLock::acquire( $product_id ); if ( ! is_callable( $release ) ) { throw new ContentReviewApplyRefusedException( __( 'Product save lock is unavailable. Please retry.', 'ai-product-tools' ), 'lock_unavailable' ); } try { wp_cache_delete( $product_id, 'post_meta' ); ContentApplyDispatcher::before( $product_id, array_merge( array( 'faq' => $faqs ), $this->blueprintSnapshotFields( $row ) ), 'faq' ); if ( 'append' === $write_mode ) { $existing_json = get_post_meta( $product_id, '_aipt_faq_data', true ); $existing_faqs = ( is_string( $existing_json ) && '' !== $existing_json ) ? json_decode( $existing_json, true ) : array(); if ( is_array( $existing_faqs ) ) { $faqs = FaqList::append( $existing_faqs, $faqs ); } } $json = wp_json_encode( $faqs ); if ( false === $json ) { ContentApplyDispatcher::after( $product_id, false ); return false; } $current = (string) get_post_meta( $product_id, '_aipt_faq_data', true ); $updated = false; if ( $current !== $json ) { $updated = update_post_meta( $product_id, '_aipt_faq_data', wp_slash( $json ) ); } if ( false !== $updated || ContentMarkService::wroteLiveValue( $product_id, '_aipt_faq_data', $json ) ) { ContentApplyDispatcher::after( $product_id, true ); ContentMarkService::mark( $product_id, 'faq', array( 'gen' => MetaKeys::GEN_BULK_ADVANCED ) ); SnapshotSubject::fromRow( $row )->bump(); return true; } ContentApplyDispatcher::after( $product_id, false ); return false; } finally { $release(); } } /** * Parse apply_context JSON. * * @param array $row * @return array */ private function parseContext( array $row ): array { $ctx = $row['apply_context'] ?? null; if ( ! is_string( $ctx ) || '' === $ctx ) { return array(); } $decoded = json_decode( $ctx, true ); return is_array( $decoded ) ? $decoded : array(); } /** * @param int $product_id Product id. * @return bool */ private function hasExistingFaq( int $product_id ): bool { $raw = function_exists( 'get_post_meta' ) ? get_post_meta( $product_id, '_aipt_faq_data', true ) : ''; if ( ! is_string( $raw ) || '' === $raw ) { return false; } $decoded = json_decode( $raw, true ); return is_array( $decoded ) && ! empty( $decoded ); } } /** * Applies generated SEO meta to the product. * * Uses the row's stored plugin_slug, never re-detects at apply time. * generated_value is the plain value of the row's field_type * (seo_meta_title, seo_meta_description or seo_focus_keyword), or a JSON * object with keys meta_title, meta_description, focus_keyword. */ final class SeoMetaApplier implements ContentReviewApplier { use EmptyOnlyOverwriteTrait; use BlueprintSnapshotFieldsTrait; /** * @param array $row * @return bool */ public function apply( array $row ): bool { $product_id = (int) ( $row['product_id'] ?? 0 ); if ( ! current_user_can( 'edit_post', $product_id ) ) { throw new ContentReviewApplyRefusedException( __( 'Permission denied.', 'ai-product-tools' ), 'permission_denied' ); } $product = wc_get_product( $product_id ); if ( ! $product ) { throw new ContentReviewApplyRefusedException( __( 'Product not found.', 'ai-product-tools' ), 'product_not_found' ); } $plugin_slug = (string) ( $row['plugin_slug'] ?? '' ); if ( '' === $plugin_slug ) { throw new ContentReviewApplyRefusedException( __( 'No SEO plugin recorded for this row.', 'ai-product-tools' ), 'no_seo_plugin_recorded' ); } $field_type = (string) ( $row['field_type'] ?? '' ); $raw = (string) ( $row['generated_value'] ?? '' ); $decoded = json_decode( $raw, true ); $decoded_keys = is_array( $decoded ) ? array_keys( $decoded ) : array(); if ( is_array( $decoded ) && ! empty( $decoded ) && is_string( reset( $decoded_keys ) ) ) { $seo_fields = $decoded; } elseif ( 'seo_meta_title' === $field_type ) { $seo_fields = array( 'meta_title' => $raw ); } elseif ( 'seo_meta_description' === $field_type ) { $seo_fields = array( 'meta_description' => $raw ); } elseif ( 'seo_focus_keyword' === $field_type ) { $seo_fields = array( 'focus_keyword' => $raw ); } else { throw new ContentReviewApplyRefusedException( __( 'Invalid stored content.', 'ai-product-tools' ), 'invalid_stored_content' ); } if ( $this->isEmptyOnlyOverwrite( $row ) ) { $blocked_seo_fields = array(); $seo_fields = $this->filterEmptyOnlySeoFields( $seo_fields, $product_id, $plugin_slug, $blocked_seo_fields ); if ( empty( $seo_fields ) ) { throw new ContentReviewApplyRefusedException( $this->emptyOnlySeoMessage( $blocked_seo_fields ), 'not_empty' ); } } $write_data = SeoMetaWriter::buildWriteData( $seo_fields, $plugin_slug ); if ( empty( $write_data ) ) { throw new ContentReviewApplyRefusedException( __( 'No applicable content.', 'ai-product-tools' ), 'no_applicable_content' ); } $seo_meta_payload = array(); if ( isset( $seo_fields['meta_title'] ) ) { $seo_meta_payload['meta_title'] = true; } if ( isset( $seo_fields['meta_description'] ) ) { $seo_meta_payload['meta_description'] = true; } if ( ! empty( $seo_meta_payload ) ) { ContentApplyDispatcher::before( $product_id, array_merge( array( 'seo_meta' => $seo_meta_payload, 'plugin_slug' => $plugin_slug, ), $this->blueprintSnapshotFields( $row ) ), 'seo_meta' ); } $writer = new SeoMetaWriter(); $results = $writer->bulkWrite( $product_id, $write_data, $plugin_slug, MetaKeys::GEN_BULK_ADVANCED ); $seo_field_results = array(); if ( array_key_exists( 'title', $write_data ) ) { $seo_field_results['seo_meta_title'] = ! empty( $results['title'] ); } if ( array_key_exists( 'description', $write_data ) ) { $seo_field_results['seo_meta_description'] = ! empty( $results['description'] ); } if ( ! empty( $seo_meta_payload ) ) { \AIPT\Core\ContentSnapshots\SnapshotStore::finalizeStagedByField( $product_id, $seo_field_results ); } $landed = $seo_field_results; if ( array_key_exists( 'focus_keyword', $write_data ) ) { $landed['seo_focus_keyword'] = ! empty( $results['focus_keyword'] ); } $all_landed = ! empty( $landed ) && count( array_filter( $landed ) ) === count( $landed ); if ( ! $all_landed ) { return false; } if ( ! empty( $results ) && count( array_filter( $results ) ) === count( $results ) ) { ContentMarkService::mark( $product_id, 'seo_meta', array( 'gen' => MetaKeys::GEN_BULK_ADVANCED ) ); } SnapshotSubject::fromRow( $row )->bump(); return true; } /** * Drop SEO fields from `$seo_fields` whose LIVE value (for the row's OWN * stored plugin_slug — never re-detected) is already non-empty. Mirrors * `AIPT\Api\ContentStructure\Apply\SeoMetaApplyAdapter`'s identical * per-field skip. * * @param array $seo_fields writerKey => value ('meta_title'|'meta_description'|'focus_keyword'). * @param int $product_id Product id. * @param string $plugin_slug Stored plugin slug. * @param array &$blocked Writer keys dropped for being non-empty, appended in place. * @return array */ private function filterEmptyOnlySeoFields( array $seo_fields, int $product_id, string $plugin_slug, array &$blocked ): array { $meta_keys = SeoPluginDetector::get_meta_keys( $plugin_slug ); $plugin_config = array( 'plugin_slug' => $plugin_slug, 'plugin_name' => null, 'meta_keys' => $meta_keys ?? array( 'title_key' => null, 'description_key' => null, 'focus_keyword_key' => null, 'score_key' => null, 'score_type' => null, ), ); $current = SeoPluginDetector::get_seo_info( $product_id, $plugin_config, false ); $current_map = array( 'meta_title' => (string) ( $current['meta_title'] ?? '' ), 'meta_description' => (string) ( $current['meta_description'] ?? '' ), 'focus_keyword' => SeoFieldValueNormalizer::flatten( $current['focus_keyword'] ?? '' ), ); foreach ( $seo_fields as $key => $value ) { if ( '' !== trim( (string) ( $current_map[ $key ] ?? '' ) ) ) { unset( $seo_fields[ $key ] ); $blocked[] = $key; } } return $seo_fields; } /** * @param array $blocked Writer keys blocked for being non-empty. * @return string */ private function emptyOnlySeoMessage( array $blocked ): string { if ( 1 === count( $blocked ) ) { switch ( reset( $blocked ) ) { case 'meta_title': return __( 'The SEO meta title is not empty.', 'ai-product-tools' ); case 'meta_description': return __( 'The SEO meta description is not empty.', 'ai-product-tools' ); case 'focus_keyword': return __( 'The focus keyword is not empty.', 'ai-product-tools' ); } } return __( 'The existing content is no longer empty. Nothing was changed.', 'ai-product-tools' ); } } /** * Applies generated image alt text to product attachments. * * Re-verifies attachment→product ownership before every write. * generated_value is a JSON array of [{attachment_id, alt_text}, …]. */ final class ImageAltApplier implements ContentReviewApplier { use EmptyOnlyOverwriteTrait; use BlueprintSnapshotFieldsTrait; /** * @param array $row * @return bool */ public function apply( array $row ): bool { $product_id = (int) ( $row['product_id'] ?? 0 ); if ( ! current_user_can( 'edit_post', $product_id ) ) { throw new ContentReviewApplyRefusedException( __( 'Permission denied.', 'ai-product-tools' ), 'permission_denied' ); } $product = wc_get_product( $product_id ); if ( ! $product ) { throw new ContentReviewApplyRefusedException( __( 'Product not found.', 'ai-product-tools' ), 'product_not_found' ); } $raw = (string) ( $row['generated_value'] ?? '' ); $decoded = json_decode( $raw, true ); if ( ! is_array( $decoded ) ) { throw new ContentReviewApplyRefusedException( __( 'Invalid stored content.', 'ai-product-tools' ), 'invalid_stored_content' ); } if ( $this->isEmptyOnlyOverwrite( $row ) ) { $blocked_by_overwrite = false; $decoded = $this->filterEmptyOnlyAltItems( $decoded, $blocked_by_overwrite ); if ( empty( $decoded ) && $blocked_by_overwrite ) { throw new ContentReviewApplyRefusedException( __( 'The image alt text is not empty.', 'ai-product-tools' ), 'not_empty' ); } } $staged_items = array(); foreach ( $decoded as $item ) { if ( ! is_array( $item ) ) { continue; } $attachment_id = absint( $item['attachment_id'] ?? 0 ); if ( $attachment_id <= 0 || ! \AIPT\Api\BulkGenerator\ImageAlt\ImageAltController::can_update_attachment_alt( $attachment_id, $product_id ) ) { continue; } $alt_text = sanitize_text_field( (string) ( $item['alt_text'] ?? '' ) ); $current_alt = (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ); if ( $current_alt === $alt_text ) { continue; } $staged_items[] = $item; } if ( ! empty( $staged_items ) ) { ContentApplyDispatcher::before( $product_id, array_merge( array( 'image_alt' => $staged_items ), $this->blueprintSnapshotFields( $row ) ), 'image_alt' ); } $updated = false; $alt_changed = false; $outcomes = array(); $any_writable = false; $any_failed = false; foreach ( $decoded as $item ) { if ( ! is_array( $item ) ) { continue; } $attachment_id = absint( $item['attachment_id'] ?? 0 ); if ( $attachment_id <= 0 ) { continue; } if ( ! \AIPT\Api\BulkGenerator\ImageAlt\ImageAltController::can_update_attachment_alt( $attachment_id, $product_id ) ) { $any_failed = true; continue; } $any_writable = true; $alt_text = sanitize_text_field( (string) ( $item['alt_text'] ?? '' ) ); $current_alt = (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ); if ( $current_alt === $alt_text ) { $updated = true; continue; } $outcomes[ $attachment_id ] = false; if ( ! empty( update_post_meta( $attachment_id, '_wp_attachment_image_alt', wp_slash( $alt_text ) ) ) ) { $updated = true; $alt_changed = true; $outcomes[ $attachment_id ] = true; \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision( $attachment_id ); } else { $any_failed = true; } } if ( ! $any_writable ) { \AIPT\Core\ContentSnapshots\SnapshotStore::finalizeStagedByField( $product_id, array() ); throw new ContentReviewApplyRefusedException( __( 'No attachment in this proposal is currently writable.', 'ai-product-tools' ), 'no_writable_attachment' ); } if ( ! $updated ) { \AIPT\Core\ContentSnapshots\SnapshotStore::finalizeStagedByField( $product_id, array() ); return false; } \AIPT\Core\ContentSnapshots\SnapshotStore::finalizeStagedByField( $product_id, array( 'image_alt' => $outcomes ) ); if ( $alt_changed ) { ContentMarkService::mark( $product_id, 'image_alt', array( 'gen' => MetaKeys::GEN_BULK_ADVANCED ) ); \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision( $product_id ); } if ( $any_failed ) { return false; } return true; } /** * Drop attachment items whose LIVE alt text is already non-empty. * Mirrors `AIPT\Api\ContentStructure\Apply\ImageAltApplyAdapter`'s * identical per-attachment skip. * * @param array $items Decoded [{attachment_id, alt_text}, ...]. * @param bool &$blocked Set true when at least one item was dropped for being non-empty. * @return array */ private function filterEmptyOnlyAltItems( array $items, bool &$blocked ): array { $blocked = false; $kept = array(); foreach ( $items as $item ) { if ( ! is_array( $item ) ) { $kept[] = $item; continue; } $attachment_id = absint( $item['attachment_id'] ?? 0 ); $current = $attachment_id > 0 && function_exists( 'get_post_meta' ) ? (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) : ''; if ( $attachment_id > 0 && '' !== trim( $current ) ) { $blocked = true; continue; } $kept[] = $item; } return $kept; } } /** * No-op applier returned for unknown tools — always refuses. */ final class NoopApplier implements ContentReviewApplier { /** * @param array $row * @return bool * @throws ContentReviewApplyRefusedException Always — an unrecognized * tool never attempts a write. */ public function apply( array $row ): bool { throw new ContentReviewApplyRefusedException( __( 'Unrecognized tool.', 'ai-product-tools' ), 'unrecognized_tool' ); } }