$liveAltByAttachment Current alt text, keyed by attachment id. * @return int[] */ public static function attachmentIdsWorthTriggering( array $decodedMap, array $liveAltByAttachment ): array { $ids = array(); foreach ( $decodedMap as $attachmentId => $alt ) { $attachmentId = (int) $attachmentId; if ( ! array_key_exists( $attachmentId, $liveAltByAttachment ) || ! current_user_can( 'edit_post', $attachmentId ) ) { continue; } if ( sanitize_text_field( (string) $alt ) === (string) $liveAltByAttachment[ $attachmentId ] ) { continue; } $ids[] = $attachmentId; } return $ids; } /** * The three-way rule, decided from hashes only (the caller computes each * with {@see ProductCsvToken::hash()}). * * @param string|null $hashE Exported hash for this field, or null when the * token is missing, tampered with, or belongs to * another product/site. * @param string $hashI Hash of the imported cell's value. * @param string $hashC Hash of the value currently in the store. * @return string One of {@see WRITE}, {@see KEEP}, {@see CONFLICT}. */ public static function decide( ?string $hashE, string $hashI, string $hashC ): string { if ( null === $hashE ) { return $hashI === $hashC ? self::KEEP : self::WRITE; } if ( $hashI === $hashE ) { return self::KEEP; } if ( $hashC === $hashE ) { return self::WRITE; } return self::CONFLICT; } /** * Resolves product_tag term ids to their current names, skipping any id * that no longer resolves to a term. * * @param int[] $termIds Term ids. * @return string[] */ public static function tagNames( array $termIds ): array { $names = array(); foreach ( $termIds as $termId ) { $term = get_term( (int) $termId, 'product_tag' ); if ( $term && ! is_wp_error( $term ) && isset( $term->name ) ) { $names[] = (string) $term->name; } } return $names; } /** * Decodes and sanitizes an `aipt_faq` cell. * * @param string $raw Raw cell value (already escape-quote stripped). * @return array|null Sanitized * entries, or null when $raw is not valid JSON. An empty/blank * cell decodes to an empty list, matching the `[]` the exporter writes. */ public static function decodeFaqEntries( string $raw ): ?array { $trimmed = trim( $raw ); $decoded = ( '' === $trimmed ) ? array() : json_decode( $raw, true ); if ( ! is_array( $decoded ) ) { return null; } $entries = array(); foreach ( $decoded as $entry ) { if ( ! is_array( $entry ) ) { continue; } $question = sanitize_text_field( (string) ( $entry['question'] ?? '' ) ); $answer = wp_kses_post( (string) ( $entry['answer'] ?? '' ) ); if ( '' === trim( $question ) && '' === trim( wp_strip_all_tags( $answer ) ) ) { continue; } $entries[] = array( 'question' => $question, 'answer' => $answer, ); } return $entries; } /** * @param \WC_Product $object Product to write to. * @param array $entries Sanitized entries from {@see decodeFaqEntries()}. * @return bool True when the write landed (or was already the stored value). */ public static function writeFaq( \WC_Product $object, array $entries ): bool { $result = ( new FaqFieldAdapter() )->write( $object, 'faq', $entries ); return ! empty( $result['saved'] ); } /** * The active SEO plugin's slug, or '' when none is active - the shared * "no SEO plugin" gate for all three `aipt_seo_*` columns. * * @return string */ public static function activeSeoPluginSlug(): string { $config = SeoPluginDetector::detect(); return ( is_array( $config ) && ! empty( $config['plugin_slug'] ) ) ? (string) $config['plugin_slug'] : ''; } /** * @param string $pluginSlug Active SEO plugin slug. * @param string $metaType 'title'|'description'|'focus_keyword'. * @return bool Whether this plugin exposes a meta key for $metaType * (false for TSF's focus keyword, for example). */ public static function seoFieldSupported( string $pluginSlug, string $metaType ): bool { $metaKeys = SeoPluginDetector::get_meta_keys( $pluginSlug ); return is_array( $metaKeys ) && ! empty( $metaKeys[ $metaType . '_key' ] ); } /** * @param int $productId Product id. * @param string $metaType 'title'|'description'|'focus_keyword'. * @param string $sanitized Sanitized content. * @param string $pluginSlug Active SEO plugin slug. * @return bool Write outcome. Never marks AI provenance: uses * {@see SeoMetaWriter::write()}, never `bulkWrite()`. */ public static function writeSeo( int $productId, string $metaType, string $sanitized, string $pluginSlug ): bool { return ( new SeoMetaWriter() )->write( $productId, $metaType, $sanitized, $pluginSlug ); } /** * Dispatches one `aipt_*` column's decided write to the right mechanics, * reporting a skip through {@see ProductCsvReport} for every reason the * value could not be written. * * @param \WC_Product $object Product to write to. * @param int $productId Product id. * @param string $columnId One of {@see ProductCsvColumns}'s `COL_*` constants. * @param string $rawValue Raw cell value (already escape-quote stripped by the formatting callback). * @param string $pluginSlug Active SEO plugin slug, or ''. * @return array{written:bool,subjects?:array} Whether the field * was actually written and, for `aipt_image_alt` only, every * attachment id the cell named mapped to its OWN write outcome - * the per-subject detail {@see \AIPT\Core\ContentSnapshots\SnapshotStore::finalizeStagedByField()} * needs to finalize one attachment's snapshot without the others. */ public static function attemptWrite( \WC_Product $object, int $productId, string $columnId, string $rawValue, string $pluginSlug ): array { switch ( $columnId ) { case ProductCsvColumns::COL_FAQ: $entries = self::decodeFaqEntries( $rawValue ); if ( null === $entries ) { ProductCsvReport::addSkipped( $productId, $columnId, 'invalid_json' ); return array( 'written' => false ); } return array( 'written' => self::writeFaq( $object, $entries ) ); case ProductCsvColumns::COL_SEO_TITLE: return array( 'written' => self::attemptSeoWrite( $productId, 'title', $columnId, $rawValue, $pluginSlug ) ); case ProductCsvColumns::COL_SEO_DESCRIPTION: return array( 'written' => self::attemptSeoWrite( $productId, 'description', $columnId, $rawValue, $pluginSlug ) ); case ProductCsvColumns::COL_SEO_FOCUS_KEYWORD: return array( 'written' => self::attemptSeoWrite( $productId, 'focus_keyword', $columnId, $rawValue, $pluginSlug ) ); case ProductCsvColumns::COL_IMAGE_ALT: $decoded = self::decodeAltMap( $rawValue ); if ( null === $decoded ) { ProductCsvReport::addSkipped( $productId, $columnId, 'invalid_json' ); return array( 'written' => false ); } $live = ProductCsvColumns::currentFieldValues( $object )[ ProductCsvColumns::COL_IMAGE_ALT ]; $result = self::writeAlt( $object, $decoded, $live ); foreach ( $result['skipped'] as $reason ) { ProductCsvReport::addSkipped( $productId, $columnId, (string) $reason ); } $subjects = array(); foreach ( array_keys( $decoded ) as $attachmentId ) { $attachmentId = (int) $attachmentId; $subjects[ $attachmentId ] = in_array( $attachmentId, $result['saved'], true ); } return array( 'written' => $result['written'], 'subjects' => $subjects, ); default: $textColumns = ProductCsvColumns::textColumns(); if ( isset( $textColumns[ $columnId ] ) ) { return array( 'written' => (bool) call_user_func( $textColumns[ $columnId ]['write'], $productId, $rawValue ) ); } return array( 'written' => false ); } } /** * @param int $productId Product id. * @param string $metaType 'title'|'description'|'focus_keyword'. * @param string $columnId Column id, for the skip report. * @param string $rawValue Raw cell value. * @param string $pluginSlug Active SEO plugin slug, or '' when none is active. * @return bool */ private static function attemptSeoWrite( int $productId, string $metaType, string $columnId, string $rawValue, string $pluginSlug ): bool { if ( '' === $pluginSlug ) { ProductCsvReport::addSkipped( $productId, $columnId, 'no_seo_plugin' ); return false; } if ( ! self::seoFieldSupported( $pluginSlug, $metaType ) ) { ProductCsvReport::addSkipped( $productId, $columnId, 'seo_field_unsupported' ); return false; } $ok = self::writeSeo( $productId, $metaType, sanitize_text_field( $rawValue ), $pluginSlug ); if ( ! $ok ) { ProductCsvReport::addSkipped( $productId, $columnId, 'seo_write_failed' ); } return $ok; } /** * Decodes an `aipt_image_alt` cell. * * @param string $raw Raw cell value (already escape-quote stripped). * @return array|null Attachment id => alt text, or * null when $raw is not valid JSON. An empty/blank cell decodes * to an empty map, matching the `{}` the exporter writes. */ public static function decodeAltMap( string $raw ): ?array { $trimmed = trim( $raw ); $decoded = ( '' === $trimmed ) ? array() : json_decode( $raw, true ); return is_array( $decoded ) ? $decoded : null; } /** * Writes every attachment entry in $decodedMap that belongs to this * product and that the current user may edit, using * {@see AltTextFieldAdapter}'s own compare-and-swap (the previous value * is the attachment's CURRENT alt text - correct here because the field * is only ever reached once the caller's three-way decision already * found the current value unchanged since export). * * @param \WC_Product $object Product the attachments belong to. * @param array $decodedMap From {@see decodeAltMap()}. * @param array $liveAltByAttachment Current alt text, keyed by attachment id, * for every attachment the product has. * @return array{written:bool,saved:int[],skipped:array} Whether * at least one attachment was actually written, the attachment ids * the adapter saved (a no-op is not saved), and a map of attachment * id to skip reason for every entry that was not written. */ public static function writeAlt( \WC_Product $object, array $decodedMap, array $liveAltByAttachment ): array { $allowed = array_keys( $liveAltByAttachment ); $entries = array(); $skipped = array(); foreach ( $decodedMap as $attachmentId => $alt ) { $attachmentId = (int) $attachmentId; if ( ! in_array( $attachmentId, $allowed, true ) ) { $skipped[ $attachmentId ] = 'unknown_attachment'; continue; } if ( ! current_user_can( 'edit_post', $attachmentId ) ) { $skipped[ $attachmentId ] = 'permission_denied'; continue; } $entries[] = array( 'attachmentId' => $attachmentId, 'alt' => (string) $alt, 'previousAlt' => $liveAltByAttachment[ $attachmentId ], ); } if ( empty( $entries ) ) { return array( 'written' => false, 'saved' => array(), 'skipped' => $skipped, ); } $result = ( new AltTextFieldAdapter() )->write( $object, 'altText', $entries ); $saved = array(); foreach ( (array) ( $result['attachments'] ?? array() ) as $outcome ) { if ( ! is_array( $outcome ) || ! isset( $outcome['status'], $outcome['attachmentId'] ) ) { continue; } if ( 'saved' === $outcome['status'] ) { $saved[] = (int) $outcome['attachmentId']; } elseif ( 'noop' !== $outcome['status'] ) { $skipped[ (int) $outcome['attachmentId'] ] = (string) $outcome['status']; } } return array( 'written' => ! empty( $result['persisted'] ), 'saved' => $saved, 'skipped' => $skipped, ); } }