save()`, while the database still holds every field's * pre-import value. Every field is DECIDED here: native fields * (name/description/short_description/tags) are applied directly to * $object (kept as the CSV value, or reverted to the current one), and a * decided-write `aipt_*` column is only remembered for the next hook - * actually writing it here, before `save()` is known to succeed, risks a * partial row (our columns changed, the native save then failed). * - `woocommerce_product_import_inserted_product_object` fires once * `$object->save()` has returned without throwing, with a real product id * even for a brand-new row. Every remembered `aipt_*` write happens here, * and this is also where {@see SnapshotStore::finalizeStagedByField()} * commits or rolls back each field staged in the first hook, per field. * * A new product (no existing id, OR an id that still carries WooCommerce's * own `importing` placeholder status - see `can_create_variation()` in * WooCommerce's own importer for the same distinction) skips the merge rule * and the token entirely: every supplied `aipt_*` column is written * unconditionally, with no snapshot, because there is no earlier value. A * variation row is ignored outright; our columns are left empty on export * and ignored on import for variations. * * @package AIPT\Core\ProductCsv * @since 2.8.0 */ namespace AIPT\Core\ProductCsv; use AIPT\Api\Rollback\ContentApplyDispatcher; use AIPT\Core\ContentSnapshots\SnapshotStore; defined( 'ABSPATH' ) || exit; final class ProductCsvImport { /** * Our `aipt_*` columns that take a formatting callback and are handled * by the merge rule (the content-source column is read-only and the row * token is verify-only, so neither needs an entry here). * {@see customColumns()} adds every extension text column. * * @var string[] */ private const CUSTOM_COLUMNS = array( ProductCsvColumns::COL_FAQ, ProductCsvColumns::COL_SEO_TITLE, ProductCsvColumns::COL_SEO_DESCRIPTION, ProductCsvColumns::COL_SEO_FOCUS_KEYWORD, ProductCsvColumns::COL_IMAGE_ALT, ); /** * Native WooCommerce fields the row token also tracks: `$data`/ * `$object->get_data()` key => {setter, ContentApplyDispatcher trigger * key, SnapshotStore::finalizeStagedByField() field_type}. `fieldType` * differs from `trigger` only for short_description (`before()`'s * payload key is `short_desc`; the snapshot field_type it stages under is * `short_description`). `tag_ids` is handled separately (array, * name-based comparison). * * @var array */ private const NATIVE_TEXT_FIELDS = array( 'name' => array( 'setter' => 'set_name', 'trigger' => 'title', 'fieldType' => 'title' ), 'description' => array( 'setter' => 'set_description', 'trigger' => 'description', 'fieldType' => 'description' ), 'short_description' => array( 'setter' => 'set_short_description', 'trigger' => 'short_desc', 'fieldType' => 'short_description' ), ); /** * Decisions made in {@see handlePreInsert()}, keyed by `spl_object_id()` * (no product id exists yet for a new row), consumed and removed by * {@see handleInserted()}. * * @var array */ private static array $stash = array(); /** * @return void */ public static function init(): void { add_filter( 'woocommerce_product_importer_formatting_callbacks', array( __CLASS__, 'addFormattingCallbacks' ), 10, 2 ); add_filter( 'woocommerce_product_import_pre_insert_product_object', array( __CLASS__, 'handlePreInsert' ), 10, 2 ); add_action( 'woocommerce_product_import_inserted_product_object', array( __CLASS__, 'handleInserted' ), 10, 2 ); } /** * `woocommerce_product_importer_formatting_callbacks` callback: registers * a raw passthrough for every one of our columns the file maps, so the * default `wc_clean` never strips HTML, JSON punctuation or newlines * from them. * * @param mixed $callbacks Positional callbacks, indexed like `$importer->get_mapped_keys()`. * @param mixed $importer The product importer instance. * @return mixed */ public static function addFormattingCallbacks( $callbacks, $importer ) { if ( ! is_array( $callbacks ) || ! is_object( $importer ) || ! is_callable( array( $importer, 'get_mapped_keys' ) ) ) { return $callbacks; } $mappedKeys = $importer->get_mapped_keys(); $ourColumns = array_merge( self::customColumns(), array( ProductCsvColumns::COL_ROW_TOKEN ) ); foreach ( $ourColumns as $columnId ) { $index = array_search( $columnId, $mappedKeys, true ); if ( false !== $index ) { $callbacks[ $index ] = array( __CLASS__, 'rawPassthrough' ); } } return $callbacks; } /** * Formatting callback for every one of our columns: strips the * exporter's defensive leading quote (mirroring the importer's own, * protected `unescape_data()`) and nothing else - never `wc_clean()`. * * @param mixed $value Raw CSV cell value. * @return string */ public static function rawPassthrough( $value ): string { return ProductCsvToken::stripEscapeQuote( (string) $value ); } /** * `woocommerce_product_import_pre_insert_product_object` callback. * * @param mixed $object Product object, not yet saved. * @param mixed $data Parsed row data. * @return mixed $object, with native fields decided. */ public static function handlePreInsert( $object, $data ) { if ( ! ( $object instanceof \WC_Product ) || ! is_array( $data ) ) { return $object; } if ( 'variation' === $object->get_type() ) { unset( self::$stash[ spl_object_id( $object ) ] ); return $object; } $productId = (int) $object->get_id(); if ( $productId <= 0 || 'importing' === $object->get_status() ) { self::$stash[ spl_object_id( $object ) ] = array( 'isNew' => true, 'data' => $data, ); return $object; } $hashes = self::verifiedHashes( $data, $productId ); ProductCsvColumns::invalidateMemo(); $current = ProductCsvColumns::currentFieldValues( $object ); $stored = $object->get_data(); $trigger = array(); $customPending = array(); $nativeWrittenCount = 0; $nativeFieldResults = array(); foreach ( self::NATIVE_TEXT_FIELDS as $field => $meta ) { if ( ! array_key_exists( $field, $data ) ) { continue; } $c = (string) ( $stored[ $field ] ?? '' ); $decision = ProductCsvFieldWriter::decide( $hashes[ $field ] ?? null, ProductCsvToken::hash( $field, (string) $data[ $field ] ), ProductCsvToken::hash( $field, $c ) ); if ( ProductCsvFieldWriter::WRITE === $decision ) { $trigger[ $meta['trigger'] ] = true; $nativeFieldResults[ $meta['fieldType'] ] = true; ++$nativeWrittenCount; } else { $object->{$meta['setter']}( $c ); if ( ProductCsvFieldWriter::CONFLICT === $decision ) { ProductCsvReport::addConflict( $productId, $field ); } } } if ( array_key_exists( 'tag_ids', $data ) ) { $tagsWritten = self::decideTags( $object, $data, $stored, $hashes, $productId, $trigger ); $nativeWrittenCount += $tagsWritten; if ( $tagsWritten > 0 ) { $nativeFieldResults['tags'] = true; } } foreach ( self::customColumns() as $columnId ) { if ( array_key_exists( $columnId, $data ) ) { self::decideCustomField( $columnId, (string) $data[ $columnId ], $current, $hashes, $productId, $trigger, $customPending ); } } self::$stash[ spl_object_id( $object ) ] = array( 'isNew' => false, 'productId' => $productId, 'customPending' => $customPending, 'nativeWrittenCount' => $nativeWrittenCount, 'nativeFieldResults' => $nativeFieldResults, ); if ( ! empty( $trigger ) ) { ContentApplyDispatcher::before( $productId, $trigger, 'csv_import' ); } return $object; } /** * `woocommerce_product_import_inserted_product_object` callback: performs * every write decided in {@see handlePreInsert()}, now that `save()` has * landed and a real product id exists. * * Finalizes snapshots PER FIELD ({@see SnapshotStore::finalizeStagedByField()}) * rather than the all-or-nothing {@see ContentApplyDispatcher::after()}: * several `aipt_*` columns can be staged together in one row (e.g. FAQ and * an SEO field), and {@see ProductCsvFieldWriter::attemptWrite()} can fail * for one of them (a transient SEO-plugin write failure, an image-alt * compare-and-swap conflict) while a sibling field's write lands - a field * whose write never happened must never be recorded as changed history, * and a field that DID land must keep its history even when a sibling * fails. Native fields need no such check here: by the time this hook * fires, `save()` has already confirmed them. * * @param mixed $object Saved product object. * @param mixed $data Parsed row data (same array {@see handlePreInsert()} received). * @return void */ public static function handleInserted( $object, $data ): void { if ( ! ( $object instanceof \WC_Product ) ) { return; } $key = spl_object_id( $object ); if ( ! isset( self::$stash[ $key ] ) ) { return; } $entry = self::$stash[ $key ]; unset( self::$stash[ $key ] ); $productId = $entry['isNew'] ? (int) $object->get_id() : (int) $entry['productId']; if ( $productId <= 0 || ( ! $entry['isNew'] && (int) $object->get_id() !== $productId ) ) { return; } $pluginSlug = ProductCsvFieldWriter::activeSeoPluginSlug(); $pending = $entry['isNew'] ? self::presentCustomColumns( (array) $data ) : (array) $entry['customPending']; $written = $entry['isNew'] ? 0 : (int) $entry['nativeWrittenCount']; $fieldResults = $entry['isNew'] ? array() : (array) $entry['nativeFieldResults']; foreach ( $pending as $columnId => $rawValue ) { $outcome = ProductCsvFieldWriter::attemptWrite( $object, $productId, (string) $columnId, (string) $rawValue, $pluginSlug ); if ( ! empty( $outcome['written'] ) ) { ++$written; } if ( ! $entry['isNew'] ) { $fieldType = ProductCsvFieldWriter::snapshotFieldType( (string) $columnId ); $fieldResults[ $fieldType ] = array_key_exists( 'subjects', $outcome ) ? $outcome['subjects'] : ! empty( $outcome['written'] ); } } if ( ! $entry['isNew'] ) { SnapshotStore::finalizeStagedByField( $productId, $fieldResults ); } if ( $written > 0 ) { ProductCsvReport::recordWrite( $productId, $written ); } } /** * @param array $data Parsed row data. * @param int $productId Product id this row targets. * @return array|null The verified token's field hashes, or * null when the token is missing, invalid, * or belongs to another product/site. */ private static function verifiedHashes( array $data, int $productId ): ?array { $token = isset( $data[ ProductCsvColumns::COL_ROW_TOKEN ] ) ? trim( (string) $data[ ProductCsvColumns::COL_ROW_TOKEN ] ) : ''; if ( '' === $token ) { return null; } $verified = ProductCsvToken::verify( $token, $productId ); return ( is_array( $verified ) && is_array( $verified['h'] ?? null ) ) ? $verified['h'] : null; } /** * Decides the `tag_ids` field (compared by name, not id) and applies the * outcome to $object. * * @param \WC_Product $object Product object, not yet saved. * @param array $data Parsed row data. * @param array $stored $object->get_data() (pre-import values). * @param array|null $hashes Verified token hashes, or null. * @param int $productId Product id. * @param array $trigger ContentApplyDispatcher trigger fields, by reference. * @return int 1 when decided WRITE, else 0. */ private static function decideTags( \WC_Product $object, array $data, array $stored, ?array $hashes, int $productId, array &$trigger ): int { $cIds = array_map( 'intval', (array) ( $stored['tag_ids'] ?? array() ) ); $iIds = array_map( 'intval', (array) $data['tag_ids'] ); $decision = ProductCsvFieldWriter::decide( $hashes['tag_ids'] ?? null, ProductCsvToken::hash( 'tag_ids', ProductCsvFieldWriter::tagNames( $iIds ) ), ProductCsvToken::hash( 'tag_ids', ProductCsvFieldWriter::tagNames( $cIds ) ) ); if ( ProductCsvFieldWriter::WRITE === $decision ) { $trigger['tags'] = array( true ); return 1; } $object->set_tag_ids( $cIds ); if ( ProductCsvFieldWriter::CONFLICT === $decision ) { ProductCsvReport::addConflict( $productId, 'tag_ids' ); } return 0; } /** * Decides one `aipt_*` column and, when the outcome is WRITE, records the * raw value to perform later and the field(s) to stage for snapshot. * * @param string $columnId Column id. * @param string $raw Raw cell value. * @param array $current {@see ProductCsvColumns::currentFieldValues()}. * @param array|null $hashes Verified token hashes, or null. * @param int $productId Product id. * @param array $trigger ContentApplyDispatcher trigger fields, by reference. * @param array $customPending Columns decided WRITE, by reference. * @return void */ private static function decideCustomField( string $columnId, string $raw, array $current, ?array $hashes, int $productId, array &$trigger, array &$customPending ): void { if ( ProductCsvColumns::COL_FAQ === $columnId ) { $decoded = ProductCsvFieldWriter::decodeFaqEntries( $raw ); } elseif ( ProductCsvColumns::COL_IMAGE_ALT === $columnId ) { $decoded = ProductCsvFieldWriter::decodeAltMap( $raw ); } else { $decoded = $raw; } if ( null === $decoded ) { ProductCsvReport::addSkipped( $productId, $columnId, 'invalid_json' ); return; } $decision = ProductCsvFieldWriter::decide( $hashes[ $columnId ] ?? null, ProductCsvToken::hash( $columnId, $decoded ), ProductCsvToken::hash( $columnId, $current[ $columnId ] ) ); if ( ProductCsvFieldWriter::CONFLICT === $decision ) { ProductCsvReport::addConflict( $productId, $columnId ); return; } if ( ProductCsvFieldWriter::KEEP === $decision ) { return; } $customPending[ $columnId ] = $raw; if ( ProductCsvColumns::COL_FAQ === $columnId ) { $trigger['faq'] = array( true ); } elseif ( ProductCsvColumns::COL_SEO_TITLE === $columnId ) { $trigger['seo_meta']['meta_title'] = true; } elseif ( ProductCsvColumns::COL_SEO_DESCRIPTION === $columnId ) { $trigger['seo_meta']['meta_description'] = true; } elseif ( ProductCsvColumns::COL_IMAGE_ALT === $columnId ) { $ids = ProductCsvFieldWriter::attachmentIdsWorthTriggering( (array) $decoded, (array) $current[ ProductCsvColumns::COL_IMAGE_ALT ] ); if ( ! empty( $ids ) ) { $trigger['image_alt'] = array_map( static function ( $id ): array { return array( 'attachment_id' => $id ); }, $ids ); } } } /** * @param array $data Parsed row data for a brand-new product. * @return array Our columns present in $data. */ private static function presentCustomColumns( array $data ): array { $present = array(); foreach ( self::customColumns() as $columnId ) { if ( array_key_exists( $columnId, $data ) ) { $present[ $columnId ] = (string) $data[ $columnId ]; } } return $present; } /** * @return string[] {@see CUSTOM_COLUMNS}, then every extension text * column ({@see ProductCsvColumns::textColumns()}). */ private static function customColumns(): array { return array_merge( self::CUSTOM_COLUMNS, array_keys( ProductCsvColumns::textColumns() ) ); } /** * Test seam: clears the pre_insert -> inserted_product_object stash. * * @return void */ public static function resetForTesting(): void { self::$stash = array(); } }