array{ * label:string, englishLabel:string, read:callable(int):string, * write:callable(int,string):bool }. `read` returns a product's current * value; `write` sanitizes and saves an imported cell. Applied by its * literal name, which Plugin Check reads. */ public const TEXT_COLUMNS_FILTER = 'aipt_product_csv_text_columns'; /** * Single-product memo for {@see currentFieldValues()}: WooCommerce calls * our per-column filters once per column for the SAME product in * sequence, so caching the one most-recently-computed product avoids * re-detecting the SEO plugin and re-reading meta for every column. * * This memo is static for the lifetime of the PHP process, not scoped to * one product: {@see \AIPT\Core\ProductCsv\ProductCsvImport} calls * {@see invalidateMemo()} before reading a row's "current" value for * exactly this reason - without it, a second row targeting the SAME * product id later in one import batch would silently reuse the FIRST * row's pre-write snapshot instead of re-reading the store. * * @var int|null */ private static ?int $memoProductId = null; /** @var array */ private static array $memoValues = array(); /** * @return void */ public static function init(): void { add_filter( 'woocommerce_product_export_column_names', array( __CLASS__, 'addColumns' ) ); add_filter( 'woocommerce_product_export_product_default_columns', array( __CLASS__, 'addColumns' ) ); add_filter( 'woocommerce_csv_product_import_mapping_options', array( __CLASS__, 'mappingOptions' ) ); add_filter( 'woocommerce_csv_product_import_mapping_default_columns', array( __CLASS__, 'mappingDefaultColumns' ) ); add_filter( 'woocommerce_product_export_product_query_args', array( ProductCsvProvenance::class, 'primeFromQueryArgs' ) ); add_filter( 'woocommerce_product_export_row_data', array( __CLASS__, 'fillTextColumns' ), 10, 2 ); add_filter( 'woocommerce_product_export_product_column_' . self::COL_FAQ, array( __CLASS__, 'columnFaq' ), 10, 2 ); add_filter( 'woocommerce_product_export_product_column_' . self::COL_SEO_TITLE, array( __CLASS__, 'columnSeoTitle' ), 10, 2 ); add_filter( 'woocommerce_product_export_product_column_' . self::COL_SEO_DESCRIPTION, array( __CLASS__, 'columnSeoDescription' ), 10, 2 ); add_filter( 'woocommerce_product_export_product_column_' . self::COL_SEO_FOCUS_KEYWORD, array( __CLASS__, 'columnSeoFocusKeyword' ), 10, 2 ); add_filter( 'woocommerce_product_export_product_column_' . self::COL_IMAGE_ALT, array( __CLASS__, 'columnImageAlt' ), 10, 2 ); add_filter( 'woocommerce_product_export_product_column_' . self::COL_CONTENT_SOURCE, array( __CLASS__, 'columnContentSource' ), 10, 2 ); add_filter( 'woocommerce_product_export_product_column_' . self::COL_ROW_TOKEN, array( __CLASS__, 'columnRowToken' ), 10, 2 ); } /** * English label for every column, kept apart from {@see translatedLabels()} * so both spellings can be registered for import auto-mapping. * * @return array */ public static function englishLabels(): array { return self::withTextColumns( array( self::COL_FAQ => 'AI Product Tools FAQ', self::COL_SEO_TITLE => 'AI Product Tools SEO title', self::COL_SEO_DESCRIPTION => 'AI Product Tools SEO description', self::COL_SEO_FOCUS_KEYWORD => 'AI Product Tools focus keyword', self::COL_IMAGE_ALT => 'AI Product Tools image alt text', ), 'englishLabel', array( self::COL_CONTENT_SOURCE => 'AI Product Tools content source', self::COL_ROW_TOKEN => 'AI Product Tools row token', ) ); } /** * @return array Column id => translated label. */ public static function translatedLabels(): array { return self::withTextColumns( array( self::COL_FAQ => __( 'AI Product Tools FAQ', 'ai-product-tools' ), self::COL_SEO_TITLE => __( 'AI Product Tools SEO title', 'ai-product-tools' ), self::COL_SEO_DESCRIPTION => __( 'AI Product Tools SEO description', 'ai-product-tools' ), self::COL_SEO_FOCUS_KEYWORD => __( 'AI Product Tools focus keyword', 'ai-product-tools' ), self::COL_IMAGE_ALT => __( 'AI Product Tools image alt text', 'ai-product-tools' ), ), 'label', array( self::COL_CONTENT_SOURCE => __( 'AI Product Tools content source', 'ai-product-tools' ), self::COL_ROW_TOKEN => __( 'AI Product Tools row token', 'ai-product-tools' ), ) ); } /** * The plain-text columns an extension registered on * {@see TEXT_COLUMNS_FILTER}, keeping only well-formed entries whose id * is a new `aipt_*` column (never one of ours or a native field). * * @return array */ public static function textColumns(): array { $registered = apply_filters( 'aipt_product_csv_text_columns', array() ); if ( ! is_array( $registered ) ) { return array(); } $reserved = array_merge( ProductCsvToken::HASH_FIELDS, array( self::COL_CONTENT_SOURCE, self::COL_ROW_TOKEN ) ); $columns = array(); foreach ( $registered as $id => $column ) { if ( ! is_string( $id ) || 0 !== strpos( $id, 'aipt_' ) || in_array( $id, $reserved, true ) || ! is_array( $column ) ) { continue; } if ( ! is_string( $column['label'] ?? null ) || ! is_string( $column['englishLabel'] ?? null ) ) { continue; } if ( ! is_callable( $column['read'] ?? null ) || ! is_callable( $column['write'] ?? null ) ) { continue; } $columns[ $id ] = $column; } return $columns; } /** * @param array $content Our content columns' labels. * @param string $labelKey 'label' or 'englishLabel'. * @param array $trailing The provenance and token columns' labels. * @return array Content columns, extension text columns, then the trailing two. */ private static function withTextColumns( array $content, string $labelKey, array $trailing ): array { foreach ( self::textColumns() as $id => $column ) { $content[ $id ] = (string) $column[ $labelKey ]; } return array_merge( $content, $trailing ); } /** * `woocommerce_product_export_column_names` / * `woocommerce_product_export_product_default_columns` callback. * * @param mixed $columns Existing id => label map. * @return array */ public static function addColumns( $columns ): array { $existing = is_array( $columns ) ? $columns : array(); return array_merge( $existing, self::translatedLabels() ); } /** * `woocommerce_csv_product_import_mapping_options` callback: the manual * mapping dropdown's options. * * @param mixed $options Existing id => label map. * @return array */ public static function mappingOptions( $options ): array { $existing = is_array( $options ) ? $options : array(); return array_merge( $existing, self::translatedLabels() ); } /** * `woocommerce_csv_product_import_mapping_default_columns` callback: * auto-match a raw CSV header to our column id. Both the translated and * the plain English label are registered, so a file exported in one * language still auto-maps on a site running another. * * @param mixed $mappings Existing label => id map. * @return array */ public static function mappingDefaultColumns( $mappings ): array { $existing = is_array( $mappings ) ? $mappings : array(); foreach ( self::translatedLabels() as $id => $label ) { $existing[ $label ] = $id; } foreach ( self::englishLabels() as $id => $label ) { $existing[ $label ] = $id; } return $existing; } /** * @param mixed $value Unused; WooCommerce always passes ''. * @param mixed $product Product being exported. * @return string */ public static function columnFaq( $value, $product ): string { $product = self::asExportableProduct( $product ); if ( null === $product ) { return ''; } return (string) wp_json_encode( self::currentFieldValues( $product )[ self::COL_FAQ ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ); } /** * `woocommerce_product_export_row_data` callback: fills every extension * text column ({@see textColumns()}) the export includes. WooCommerce * leaves such a column empty, since no `get_column_value_*` method or * per-column filter answers it. * * @param mixed $row Row data keyed by column id. * @param mixed $product Product being exported. * @return mixed */ public static function fillTextColumns( $row, $product ) { if ( ! is_array( $row ) ) { return $row; } $columns = array_intersect_key( self::textColumns(), $row ); if ( empty( $columns ) ) { return $row; } $product = self::asExportableProduct( $product ); $values = null === $product ? array() : self::currentFieldValues( $product ); foreach ( array_keys( $columns ) as $id ) { $row[ $id ] = (string) ( $values[ $id ] ?? '' ); } return $row; } /** * @param mixed $value Unused; WooCommerce always passes ''. * @param mixed $product Product being exported. * @return string */ public static function columnSeoTitle( $value, $product ): string { $product = self::asExportableProduct( $product ); return null === $product ? '' : (string) self::currentFieldValues( $product )[ self::COL_SEO_TITLE ]; } /** * @param mixed $value Unused; WooCommerce always passes ''. * @param mixed $product Product being exported. * @return string */ public static function columnSeoDescription( $value, $product ): string { $product = self::asExportableProduct( $product ); return null === $product ? '' : (string) self::currentFieldValues( $product )[ self::COL_SEO_DESCRIPTION ]; } /** * @param mixed $value Unused; WooCommerce always passes ''. * @param mixed $product Product being exported. * @return string */ public static function columnSeoFocusKeyword( $value, $product ): string { $product = self::asExportableProduct( $product ); return null === $product ? '' : (string) self::currentFieldValues( $product )[ self::COL_SEO_FOCUS_KEYWORD ]; } /** * @param mixed $value Unused; WooCommerce always passes ''. * @param mixed $product Product being exported. * @return string */ public static function columnImageAlt( $value, $product ): string { $product = self::asExportableProduct( $product ); if ( null === $product ) { return ''; } return (string) wp_json_encode( self::currentFieldValues( $product )[ self::COL_IMAGE_ALT ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_FORCE_OBJECT ); } /** * @param mixed $value Unused; WooCommerce always passes ''. * @param mixed $product Product being exported. * @return string */ public static function columnContentSource( $value, $product ): string { $product = self::asExportableProduct( $product ); return null === $product ? '' : ProductCsvProvenance::readable( (int) $product->get_id() ); } /** * @param mixed $value Unused; WooCommerce always passes ''. * @param mixed $product Product being exported. * @return string */ public static function columnRowToken( $value, $product ): string { $product = self::asExportableProduct( $product ); if ( null === $product ) { return ''; } return ProductCsvToken::sign( (int) $product->get_id(), self::currentFieldValues( $product ) ); } /** * Every tracked field's CURRENT semantic value for one product, memoized * for the lifetime of processing THIS product (see {@see $memoProductId}). * Reused by {@see \AIPT\Core\ProductCsv\ProductCsvImport} to read the * store's current value for the aipt_* columns during import - which * calls {@see invalidateMemo()} first on every row, since this memo does * not know "this is a new row" on its own. * * @param \WC_Product $product Product to read. * @return array Map of {@see ProductCsvToken::fields()} key * to its current value. */ public static function currentFieldValues( \WC_Product $product ): array { $productId = (int) $product->get_id(); if ( self::$memoProductId === $productId ) { return self::$memoValues; } $values = array( 'name' => (string) $product->get_name(), 'description' => (string) $product->get_description(), 'short_description' => (string) $product->get_short_description(), 'tag_ids' => self::currentTagNames( $productId ), self::COL_FAQ => self::currentFaqEntries( $productId ), self::COL_SEO_TITLE => '', self::COL_SEO_DESCRIPTION => '', self::COL_SEO_FOCUS_KEYWORD => '', self::COL_IMAGE_ALT => self::currentAltMap( $product ), ); if ( null !== SeoPluginDetector::detect() ) { $adapter = new SeoFieldAdapter(); $values[ self::COL_SEO_TITLE ] = (string) ( $adapter->read( $product, 'seoTitle' ) ?? '' ); $values[ self::COL_SEO_DESCRIPTION ] = (string) ( $adapter->read( $product, 'metaDescription' ) ?? '' ); $values[ self::COL_SEO_FOCUS_KEYWORD ] = (string) ( $adapter->read( $product, 'focusKeyword' ) ?? '' ); } foreach ( self::textColumns() as $id => $column ) { $values[ $id ] = (string) call_user_func( $column['read'], $productId ); } self::$memoProductId = $productId; self::$memoValues = $values; return $values; } /** * @param int $productId Product id. * @return string[] Current product_tag names. */ private static function currentTagNames( int $productId ): array { if ( ! function_exists( 'wp_get_post_terms' ) ) { return array(); } $terms = wp_get_post_terms( $productId, 'product_tag', array( 'fields' => 'names' ) ); return is_array( $terms ) ? array_values( array_map( 'strval', $terms ) ) : array(); } /** * The stored FAQ in the same canonical shape an imported cell decodes to * ({@see ProductCsvFieldWriter::decodeFaqEntries()}: question and answer * only, empty pairs dropped). Exporting and hashing that shape means a * cell nobody edited always matches its token, even for a stored entry * carrying extra keys, so an untouched FAQ is never rewritten on import. * * @param int $productId Product id. * @return array */ private static function currentFaqEntries( int $productId ): array { $raw = get_post_meta( $productId, '_aipt_faq_data', true ); return ( is_string( $raw ) ? ProductCsvFieldWriter::decodeFaqEntries( $raw ) : null ) ?? array(); } /** * @param \WC_Product $product Product to read. * @return array Attachment id => alt text, for the featured * image and every gallery image. */ private static function currentAltMap( \WC_Product $product ): array { $map = array(); foreach ( self::productAttachmentIds( $product ) as $attachmentId ) { $map[ $attachmentId ] = (string) get_post_meta( $attachmentId, '_wp_attachment_image_alt', true ); } return $map; } /** * @param \WC_Product $product Product to read. * @return int[] Featured image id (when set) followed by gallery image ids, deduplicated. */ public static function productAttachmentIds( \WC_Product $product ): array { $ids = array(); $featured_id = (int) $product->get_image_id(); if ( $featured_id > 0 ) { $ids[] = $featured_id; } foreach ( (array) $product->get_gallery_image_ids() as $attachmentId ) { $attachmentId = (int) $attachmentId; if ( $attachmentId > 0 ) { $ids[] = $attachmentId; } } return array_values( array_unique( $ids ) ); } /** * @param mixed $product Value WooCommerce passed as the row's product. * @return \WC_Product|null The product, or null for a variation (our * columns are left empty on export) or a * non-product value. */ private static function asExportableProduct( $product ): ?\WC_Product { if ( ! ( $product instanceof \WC_Product ) ) { return null; } return 'variation' === $product->get_type() ? null : $product; } /** * Clears the per-product memo so the next {@see currentFieldValues()} call * re-reads from the store instead of returning a cached product's values. * * Production use: {@see \AIPT\Core\ProductCsv\ProductCsvImport} calls this * before computing the "current" value for EVERY import row of an * existing product, so a duplicate-id row later in the same batch (the * memo is keyed on a single product id, not a per-row token) re-reads * postmeta instead of returning an earlier row's pre-write snapshot of * the same product. * * @return void */ public static function invalidateMemo(): void { self::$memoProductId = null; self::$memoValues = array(); } /** * Test seam: clears every static cache so one test cannot leak state into another. * * @return void */ public static function resetForTesting(): void { self::invalidateMemo(); } }