Make WordPress Core


Ignore:
Timestamp:
10/27/2020 04:42:38 PM (4 years ago)
Author:
TimothyBlynJacobs
Message:

REST API: Support a broader range of JSON media types.

Previously, we only supported application/json which prevented using subtypes like application/activity+json. This allows for the REST API to json_decode the body of requests using a JSON subtype Content-Type. Additionally, wp_die() now properly sends the error as JSON when a JSON subtype is specified in the Accept header.

Props pfefferle.
Fixes #49404.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/load.php

    r49163 r49329  
    15961596function wp_is_json_request() {
    15971597
    1598     if ( isset( $_SERVER['HTTP_ACCEPT'] ) && false !== strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) ) {
     1598    if ( isset( $_SERVER['HTTP_ACCEPT'] ) && wp_is_json_media_type( $_SERVER['HTTP_ACCEPT'] ) ) {
    15991599        return true;
    16001600    }
    16011601
    1602     if ( isset( $_SERVER['CONTENT_TYPE'] ) && 'application/json' === $_SERVER['CONTENT_TYPE'] ) {
     1602    if ( isset( $_SERVER['CONTENT_TYPE'] ) && wp_is_json_media_type( $_SERVER['CONTENT_TYPE'] ) ) {
    16031603        return true;
    16041604    }
     
    16341634    return $jsonp_enabled;
    16351635
     1636}
     1637
     1638/**
     1639 * Checks whether a string is a valid JSON Media Type.
     1640 *
     1641 * @since 5.6.0
     1642 *
     1643 * @param string $media_type A Media Type string to check.
     1644 * @return bool True if string is a valid JSON Media Type.
     1645 */
     1646function wp_is_json_media_type( $media_type ) {
     1647    static $cache = array();
     1648
     1649    if ( ! isset( $cache[ $media_type ] ) ) {
     1650        $cache[ $media_type ] = (bool) preg_match( '/(^|\s|,)application\/([\w!#\$&-\^\.\+]+\+)?json(\+oembed)?($|\s|;|,)/i', $media_type );
     1651    }
     1652
     1653    return $cache[ $media_type ];
    16361654}
    16371655
Note: See TracChangeset for help on using the changeset viewer.