self::VERSION, 'site' => self::siteId(), 'id' => $productId, 'at' => gmdate( 'Y-m-d\TH:i:s\Z' ), 'h' => $hashes, ); $json = (string) wp_json_encode( $payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ); return self::base64UrlEncode( $json ) . '.' . self::signatureFor( $json ); } /** * Verify a token's signature, site and product id. * * @param string $token Token exactly as read from the CSV cell. * @param int $expectedProductId Product id the CURRENT row targets. * @return array{v:int,site:string,id:int,at:string,h:array}|null * The decoded payload, or null when the token is missing a part, * the signature does not match (tampering), the site does not * match, or the embedded product id disagrees with * $expectedProductId (the token belongs to another product). */ public static function verify( string $token, int $expectedProductId ): ?array { $parts = explode( '.', $token, 2 ); if ( 2 !== count( $parts ) || '' === $parts[0] || '' === $parts[1] ) { return null; } list( $encoded, $signature ) = $parts; $json = self::base64UrlDecode( $encoded ); if ( null === $json ) { return null; } if ( ! hash_equals( self::signatureFor( $json ), $signature ) ) { return null; } $payload = json_decode( $json, true ); if ( ! is_array( $payload ) || ! isset( $payload['site'], $payload['id'], $payload['h'] ) || ! is_array( $payload['h'] ) ) { return null; } if ( (string) $payload['site'] !== self::siteId() ) { return null; } if ( (int) $payload['id'] !== $expectedProductId ) { return null; } return $payload; } /** * Hash one field's value using that field's own normalization, so the * SAME semantic value always hashes the same regardless of which side * (export or import) computed it. * * @param string $field One of {@see fields()}. * @param string|string[]|int $value Raw semantic value: a string for every * field except 'tag_ids', which takes a * list of tag names. * @return string Lowercase hex sha256. */ public static function hash( string $field, $value ): string { switch ( $field ) { case 'description': case 'short_description': $normalized = self::normalizeHtml( (string) $value ); break; case 'tag_ids': $normalized = self::normalizeTagNames( is_array( $value ) ? $value : array() ); break; case 'aipt_faq': $normalized = self::normalizeJson( $value ); break; case 'aipt_image_alt': $normalized = self::normalizeAltJson( $value ); break; default: $normalized = self::normalizeText( self::stripEscapeQuote( (string) $value ) ); break; } return hash( 'sha256', $normalized ); } /** * Site identity carried in a token's payload: never the raw home URL, so * a token never leaks the install's address to anyone who only has the * exported CSV. * * @return string */ public static function siteId(): string { return hash( 'sha256', (string) home_url() ); } /** * CRLF/CR to LF, trimmed. The first normalization pass every text-ish * field goes through, so a Windows-edited cell still matches. * * @param string $value Raw value. * @return string */ public static function normalizeText( string $value ): string { return trim( (string) preg_replace( '/\r\n?/', "\n", $value ) ); } /** * HTML field normalization: undo the exporter's defensive leading quote, * canonicalize through wp_kses_post() (the same filter WordPress applies * when the value is actually saved), then the shared text normalization. * * @param string $value Raw value (already newline-restored by WooCommerce's * own parse_description_field() for native columns). * @return string */ public static function normalizeHtml( string $value ): string { $value = self::stripEscapeQuote( $value ); $value = (string) wp_kses_post( $value ); return self::normalizeText( $value ); } /** * Tag names, sorted and joined - order-independent and case-exact, matching * what a merchant sees as "the tags" regardless of assignment order. * * @param string[] $names Tag names. * @return string */ public static function normalizeTagNames( array $names ): string { $names = array_map( static function ( $name ): string { return self::normalizeText( (string) $name ); }, $names ); sort( $names, SORT_STRING ); return implode( ',', $names ); } /** * Canonical JSON for the FAQ column: entry order is preserved (it is * meaningful), but re-encoding removes any incidental whitespace/escaping * differences between two byte-different CSV cells that decode to the * same structure. * * @param string|array $value JSON string or an already-decoded array. * @return string */ public static function normalizeJson( $value ): string { $decoded = self::decodeForHashing( $value ); return (string) wp_json_encode( $decoded, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ); } /** * Canonical JSON for the image-alt column: an object keyed by attachment * id, so (unlike the FAQ list) key ORDER carries no meaning and must be * sorted before hashing. * * @param string|array $value JSON string or an already-decoded array. * @return string */ public static function normalizeAltJson( $value ): string { $decoded = self::decodeForHashing( $value ); if ( ! is_array( $decoded ) ) { $decoded = array(); } ksort( $decoded ); return (string) wp_json_encode( $decoded, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_FORCE_OBJECT ); } /** * Mirrors the importer's protected `WC_Abstract_Product_Importer::unescape_data()`: * strip a single leading `'` when it precedes `=`, `+`, `-` or `@` - the exact * trigger set `WC_CSV_Exporter::escape_data()` prefixes on export. That method is * protected on WooCommerce's importer, so our own formatting callbacks and this * shared normalizer re-implement the same one-character rule instead of calling it. * * @param string $value Possibly-escaped value. * @return string */ public static function stripEscapeQuote( string $value ): string { $triggers = array( "'=", "'+", "'-", "'@" ); return in_array( mb_substr( $value, 0, 2 ), $triggers, true ) ? mb_substr( $value, 1 ) : $value; } /** * @param string|array $value JSON string or an already-decoded array. * @return array */ private static function decodeForHashing( $value ): array { if ( is_array( $value ) ) { return $value; } $decoded = json_decode( (string) $value, true ); return is_array( $decoded ) ? $decoded : array(); } /** * @param string $json Canonical JSON payload (without the trailing signature). * @return string Lowercase hex HMAC-SHA256. */ private static function signatureFor( string $json ): string { return hash_hmac( 'sha256', $json, (string) wp_salt( 'auth' ) ); } /** * @param string $data Raw bytes. * @return string */ private static function base64UrlEncode( string $data ): string { return rtrim( strtr( base64_encode( $data ), '+/', '-_' ), '=' ); } /** * @param string $data Base64url text. * @return string|null Decoded bytes, or null when $data is not valid base64url. */ private static function base64UrlDecode( string $data ): ?string { $remainder = strlen( $data ) % 4; if ( 0 !== $remainder ) { $data .= str_repeat( '=', 4 - $remainder ); } $decoded = base64_decode( strtr( $data, '-_', '+/' ), true ); return false === $decoded ? null : $decoded; } }