['label' => string, 'value' => mixed, 'type' => string] * @param array|null $allowlist null = all non-sensitive fields; array = only these names. * @return array name => ['label' => string, 'value' => string] */ public static function build( array $fields, $allowlist ): array { $out = array(); foreach ( $fields as $name => $field ) { $name = (string) $name; $type = strtolower( (string) ( $field['type'] ?? 'text' ) ); $label = (string) ( $field['label'] ?? $name ); if ( in_array( $type, self::SKIP_TYPES, true ) ) { continue; } if ( is_array( $allowlist ) && ! in_array( $name, $allowlist, true ) ) { continue; } if ( self::is_sensitive( $name ) || self::is_sensitive( $label ) ) { continue; } $out[ $name ] = array( 'label' => wp_strip_all_tags( $label ), 'value' => self::normalise_value( $field['value'] ?? '' ), ); } /** * Last chance to change what gets stored. * * @param array $out Snapshot about to be stored. * @param array $fields Raw normalised fields from the adapter. */ return (array) apply_filters( 'actr_snapshot', $out, $fields ); } public static function is_sensitive( string $text ): bool { return (bool) preg_match( self::BLOCKED_PATTERN, $text ); } /** * JSON exactly as stored. Field order follows the form; the hash is taken * over this exact string, so no re-sorting is needed to verify it. */ public static function canonical( array $snapshot ): string { return (string) wp_json_encode( $snapshot, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ); } public static function hash( string $reference, string $created_at, string $canonical ): string { return hash( 'sha256', strtoupper( $reference ) . "\n" . $created_at . "\n" . $canonical ); } /** * True when the stored snapshot still matches the hash taken at submission. */ public static function verify( array $receipt ): bool { $expected = self::hash( $receipt['reference'], $receipt['created_at'], (string) $receipt['snapshot'] ); return hash_equals( (string) $receipt['snapshot_hash'], $expected ); } public static function decode( array $receipt ): array { $data = json_decode( (string) $receipt['snapshot'], true ); return is_array( $data ) ? $data : array(); } private static function normalise_value( $value ): string { if ( is_array( $value ) ) { $value = implode( ', ', array_filter( array_map( static function ( $v ) { return is_scalar( $v ) ? trim( (string) $v ) : ''; }, $value ), 'strlen' ) ); } $value = is_scalar( $value ) ? trim( (string) $value ) : ''; if ( function_exists( 'mb_substr' ) ) { return mb_substr( $value, 0, self::MAX_VALUE_LENGTH ); } return substr( $value, 0, self::MAX_VALUE_LENGTH ); } }