Logging: Handle multibyte characters and slashes in context data (#48341)

The json_encode function encodes multibyte characters literally by
default, which makes them unreadable in the log files. This change
ensures those characters remain intact, rather than encoded. It also
adds better handling for characters that get escaped with slashes.

Fixes #44743
This commit is contained in:
Corey McKrill 2024-06-12 10:14:55 -07:00 committed by GitHub
parent ed310fede4
commit 4b40a3170c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 21 additions and 5 deletions

View File

@ -0,0 +1,4 @@
Significance: minor
Type: fix
Ensure that data containing multibyte characters and/or slashes that is appended to log entries gets encoded and rendered correctly

View File

@ -88,8 +88,8 @@ class LogHandlerFileV2 extends WC_Log_Handler {
unset( $context_for_entry['source'] );
if ( ! empty( $context_for_entry ) ) {
$formatted_context = wp_json_encode( $context_for_entry );
$message .= " CONTEXT: $formatted_context";
$formatted_context = wp_json_encode( $context_for_entry, JSON_UNESCAPED_UNICODE );
$message .= stripslashes( " CONTEXT: $formatted_context" );
}
$entry = "$time_string $level_string $message";

View File

@ -715,13 +715,18 @@ class PageController {
$message_chunks = explode( 'CONTEXT:', $segments[2], 2 );
if ( isset( $message_chunks[1] ) ) {
try {
$maybe_json = stripslashes( html_entity_decode( trim( $message_chunks[1] ) ) );
$maybe_json = html_entity_decode( addslashes( trim( $message_chunks[1] ) ) );
// Decode for validation.
$context = json_decode( $maybe_json, false, 512, JSON_THROW_ON_ERROR );
// Re-encode to make it pretty.
$context = wp_json_encode( $context, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );
$message_chunks[1] = sprintf(
'<details><summary>%1$s</summary>%2$s</details>',
esc_html__( 'Additional context', 'woocommerce' ),
wp_json_encode( $context, JSON_PRETTY_PRINT )
stripslashes( $context )
);
$segments[2] = implode( ' ', $message_chunks );

View File

@ -187,6 +187,13 @@ MESSAGE;
),
$context_delineator . '{"yin":"yang","apple":"orange"}',
);
yield 'custom keys with multibyte and slashed values' => array(
array(
'multibyte' => '中文字',
'backslashes' => 'C:\MS-DOS\\',
),
$context_delineator . '{"multibyte":"中文字","backslashes":"C:\MS-DOS\"}',
);
yield 'backtrace boolean only' => array(
array( 'backtrace' => true ),
$context_delineator . wp_json_encode( array( 'backtrace' => $this->get_mock_backtrace() ) ),