woocommerce/includes/legacy/api/v1/class-wc-api-json-handler.php

75 lines
1.9 KiB
PHP
Raw Normal View History

2014-07-12 21:49:43 +00:00
<?php
/**
* WooCommerce API
*
* Handles parsing JSON request bodies and generating JSON responses
*
* @author WooThemes
* @category API
2020-08-05 16:36:24 +00:00
* @package WooCommerce\API
2014-07-12 21:49:43 +00:00
* @since 2.1
* @version 2.1
*/
2014-09-20 19:27:54 +00:00
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
2014-07-12 21:49:43 +00:00
class WC_API_JSON_Handler implements WC_API_Handler {
/**
* Get the content type for the response
*
* @since 2.1
* @return string
*/
public function get_content_type() {
2014-08-30 18:00:50 +00:00
return sprintf( '%s; charset=%s', isset( $_GET['_jsonp'] ) ? 'application/javascript' : 'application/json', get_option( 'blog_charset' ) );
2014-07-12 21:49:43 +00:00
}
/**
* Parse the raw request body entity
*
* @since 2.1
* @param string $body the raw request body
* @return array|mixed
*/
public function parse_body( $body ) {
return json_decode( $body, true );
}
/**
* Generate a JSON response given an array of data
*
* @since 2.1
* @param array $data the response data
* @return string
*/
public function generate_response( $data ) {
if ( isset( $_GET['_jsonp'] ) ) {
if ( ! apply_filters( 'woocommerce_api_jsonp_enabled', true ) ) {
WC()->api->server->send_status( 400 );
2019-02-20 12:00:47 +00:00
return wp_json_encode( array( array( 'code' => 'woocommerce_api_jsonp_disabled', 'message' => __( 'JSONP support is disabled on this site', 'woocommerce' ) ) ) );
2014-07-12 21:49:43 +00:00
}
2019-02-20 12:00:47 +00:00
$jsonp_callback = $_GET['_jsonp'];
2014-07-12 21:49:43 +00:00
2019-02-20 12:00:47 +00:00
if ( ! wp_check_jsonp_callback( $jsonp_callback ) ) {
2014-07-12 21:49:43 +00:00
WC()->api->server->send_status( 400 );
2019-02-20 12:00:47 +00:00
return wp_json_encode( array( array( 'code' => 'woocommerce_api_jsonp_callback_invalid', __( 'The JSONP callback function is invalid', 'woocommerce' ) ) ) );
2014-07-12 21:49:43 +00:00
}
WC()->api->server->header( 'X-Content-Type-Options', 'nosniff' );
2019-02-20 12:00:47 +00:00
// Prepend '/**/' to mitigate possible JSONP Flash attacks.
// https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
return '/**/' . $jsonp_callback . '(' . wp_json_encode( $data ) . ')';
2014-07-12 21:49:43 +00:00
}
2019-02-20 12:00:47 +00:00
return wp_json_encode( $data );
2014-07-12 21:49:43 +00:00
}
}