| | 2615 | * Encode a variable into JSON, with some sanity checks |
| | 2616 | * |
| | 2617 | * @since 4.0 |
| | 2618 | * |
| | 2619 | * @param mixed $data Variable (usually an array or object) to encode as JSON |
| | 2620 | * @param int $options Options to be passed to json_encode(). Default 0. |
| | 2621 | * @param int $depth Maximum depth to walk through $data. Must be greater than 0, default 512.t |
| | 2622 | * |
| | 2623 | * @return bool|string The JSON encoded string, or false if it cannot be encoded |
| | 2624 | */ |
| | 2625 | function wp_json_encode( $data, $options = 0, $depth = 512 ) { |
| | 2626 | // json_encode has had extra params added over the years. |
| | 2627 | // $options was added in 5.3, and $depth in 5.5. |
| | 2628 | // We need to make sure we call it with the correct arguments. |
| | 2629 | if ( version_compare( PHP_VERSION, '5.5', '>=' ) ) { |
| | 2630 | $args = array( $data, $options, $depth ); |
| | 2631 | } else if ( version_compare( PHP_VERSION, '5.3', '>=' ) ) { |
| | 2632 | $args = array( $data, $options ); |
| | 2633 | } else { |
| | 2634 | $args = array( $data ); |
| | 2635 | } |
| | 2636 | |
| | 2637 | $json = call_user_func_array( 'json_encode', $args ); |
| | 2638 | |
| | 2639 | if ( false !== $json ) { |
| | 2640 | // If json_encode was successful, no need to do more sanity checking |
| | 2641 | return $json; |
| | 2642 | } |
| | 2643 | |
| | 2644 | try { |
| | 2645 | $args[0] = _wp_json_sanity_check( $data, $depth ); |
| | 2646 | } catch ( Exception $e ) { |
| | 2647 | return false; |
| | 2648 | } |
| | 2649 | |
| | 2650 | return call_user_func_array( 'json_encode', $args ); |
| | 2651 | } |
| | 2652 | |
| | 2653 | function _wp_json_sanity_check( $data, $depth ) { |
| | 2654 | if ( $depth < 0 ) { |
| | 2655 | throw new Exception( 'Reached depth limit' ); |
| | 2656 | } |
| | 2657 | |
| | 2658 | if ( is_array( $data ) ) { |
| | 2659 | foreach ( $data as $id => $el ) { |
| | 2660 | if ( is_array( $el ) || is_object( $el ) || is_string( $el ) ) { |
| | 2661 | $data[ $id ] = _wp_json_sanity_check( $el, $depth - 1 ); |
| | 2662 | } |
| | 2663 | } |
| | 2664 | } else if ( is_object( $data ) ) { |
| | 2665 | foreach ( $data as $id => $el ) { |
| | 2666 | if ( is_array( $el ) || is_object( $el ) || is_string( $el ) ) { |
| | 2667 | $data->$id = _wp_json_sanity_check( $el, $depth - 1 ); |
| | 2668 | } |
| | 2669 | } |
| | 2670 | } else if ( is_string( $data ) ) { |
| | 2671 | if ( function_exists( 'mb_convert_encoding' ) ) { |
| | 2672 | $encoding = mb_detect_encoding( $data ); |
| | 2673 | if ( $encoding ) { |
| | 2674 | $data = mb_convert_encoding( $data, 'UTF-8', $encoding ); |
| | 2675 | } else { |
| | 2676 | $data = mb_convert_encoding( $data, 'UTF-8', 'UTF-8' ); |
| | 2677 | } |
| | 2678 | } else { |
| | 2679 | $data = wp_check_invalid_utf8( $data, true ); |
| | 2680 | } |
| | 2681 | } |
| | 2682 | |
| | 2683 | return $data; |
| | 2684 | } |
| | 2685 | |
| | 2686 | /** |