WordPress.org

Make WordPress Core

Opened 3 months ago

Last modified 28 hours ago

#43977 new defect (bug)

Fix error-prone string to array parsing

Reported by: flixos90 Owned by:
Milestone: 5.0 Priority: normal
Severity: normal Version:
Component: General Keywords: needs-unit-tests
Focuses: rest-api Cc:

Description

In the REST API (and sometimes in other areas of core too) it's a common procedure to parse a string into an array, splitting at comma characters. I noticed an issue that can easily lead to unexpected behavior when an empty value is passed.

Several functions in core use this behavior: $list = preg_split( '/[\s,]+/', $list );

However, it causes empty strings to be parsed into an array containing an empty string, where I would expect it to just be an empty array. In the REST API, this can cause strange behavior:

  • If you call wp/v2/posts/?include=, WordPress will search for posts with ID 0 (which won't change the response, but is still somewhat clunky).
  • If you call wp/v2/posts/?slug=, WordPress will search for posts with an empty slug (which won't change the response, but is still somewhat clunky).
  • More importantly though: If you call wp/v2/posts/?status=, you will get a strange error saying "Status is forbidden". That is because it validates the empty string in the parsed array against the enum whitelist, with that check obviously failing. It's not a required parameter, so in this case, it should instead just be ignored.

We should look for functions that perform the above parsing procedure and fix them.

Attachments (1)

43977.diff (5.4 KB) - added by sstoqnov 28 hours ago.
Add PREG_SPLIT_NO_EMPTY flag to preg_split to avoid arrays with empty values

Download all attachments as: .zip

Change History (2)

@sstoqnov
28 hours ago

Add PREG_SPLIT_NO_EMPTY flag to preg_split to avoid arrays with empty values

#1 @sstoqnov
28 hours ago

  • Keywords needs-patch removed

If we pass PREG_SPLIT_NO_EMPTY to preg_split, it will remove the empty values. I ran few tests that confirmed that.

I will also try to provide unit tests soon.

Note: See TracTickets for help on using tickets.