Make WordPress Core

Opened 6 years ago

Last modified 2 years ago

#53023 new defect (bug)

_wp_json_convert_string type mismatch: returns string on success; false on failure

Reported by: hellofromTonya Owned by:
Priority: normal Milestone: Awaiting Review
Component: Formatting Version: 4.1.4
Severity: normal Keywords: has-patch
Cc: Focuses: docs

Description

The private function _wp_json_convert_string (which converts a string to UTF-8) also returns false, though its @return specifies only string.

How? ​`mb_convert_encoding` returns a string on success and a false on failure.

Is this a bug or docs fix? It's both.

Reviewing its context, it's used by _wp_json_sanity_check to convert IDs and data value. The IDs are the problem. How so? Each ID is used as either a key or project for referencing the data value.

What happens if the conversion to UTF-8 fails? The key or property would either be an empty string or false. That's problematic as it can cause unexpected JSON encoding results.

For example, this ​3v4l snippet simulates the convert encoding failure to view the results through the JSON encoding process. Notice how the returned JSON is invalid when it fails. (Note: This snippet is forcing a failure.)

Change History (2)

#1 @desrosj
2 years ago

#57172 was marked as a duplicate.

This ticket was mentioned in ​PR #7572 on ​WordPress/wordpress-develop by ​@debarghyabanerjee.


2 years ago
#2

  • Keywords has-patch added

Trac Ticket: Core-53023

## Summary

This pull request addresses a critical issue in the _wp_json_convert_string function, which is responsible for converting strings to UTF-8 for safe JSON encoding. The previous implementation did not handle conversion failures appropriately, potentially leading to invalid JSON output. This update ensures that the function consistently returns a string, mitigating unexpected behavior in subsequent JSON encoding processes.

## Changes Made

  • Error Handling Improvement: If mb_convert_encoding fails and returns false, the function now explicitly returns an empty string. This change prevents invalid keys or properties in JSON data.
  • Code Clarity: The logic for determining the string encoding has been streamlined to enhance readability and maintainability.
  • Documentation Update: The function's PHPDoc has been revised to clarify that the function will return an empty string if conversion fails, ensuring alignment between documentation and behavior.

## Implications:

  • This update enhances the robustness of the JSON encoding process by ensuring that all outputs from _wp_json_convert_string are valid strings.
  • Developers using this function can expect more predictable behavior, as the risk of generating invalid JSON due to conversion errors has been significantly reduced.
Note: See TracTickets for help on using tickets.