class-wc-api-json-handler.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * WooCommerce API
  4. *
  5. * Handles parsing JSON request bodies and generating JSON responses
  6. *
  7. * @author WooThemes
  8. * @category API
  9. * @package WooCommerce/API
  10. * @since 2.1
  11. */
  12. if ( ! defined( 'ABSPATH' ) ) {
  13. exit; // Exit if accessed directly
  14. }
  15. class WC_API_JSON_Handler implements WC_API_Handler {
  16. /**
  17. * Get the content type for the response
  18. *
  19. * @since 2.1
  20. * @return string
  21. */
  22. public function get_content_type() {
  23. return sprintf( '%s; charset=%s', isset( $_GET['_jsonp'] ) ? 'application/javascript' : 'application/json', get_option( 'blog_charset' ) );
  24. }
  25. /**
  26. * Parse the raw request body entity
  27. *
  28. * @since 2.1
  29. * @param string $body the raw request body
  30. * @return array|mixed
  31. */
  32. public function parse_body( $body ) {
  33. return json_decode( $body, true );
  34. }
  35. /**
  36. * Generate a JSON response given an array of data
  37. *
  38. * @since 2.1
  39. * @param array $data the response data
  40. * @return string
  41. */
  42. public function generate_response( $data ) {
  43. if ( isset( $_GET['_jsonp'] ) ) {
  44. // JSONP enabled by default
  45. if ( ! apply_filters( 'woocommerce_api_jsonp_enabled', true ) ) {
  46. WC()->api->server->send_status( 400 );
  47. $data = array( array( 'code' => 'woocommerce_api_jsonp_disabled', 'message' => __( 'JSONP support is disabled on this site', 'woocommerce' ) ) );
  48. }
  49. // Check for invalid characters (only alphanumeric allowed)
  50. if ( preg_match( '/\W/', $_GET['_jsonp'] ) ) {
  51. WC()->api->server->send_status( 400 );
  52. $data = array( array( 'code' => 'woocommerce_api_jsonp_callback_invalid', __( 'The JSONP callback function is invalid', 'woocommerce' ) ) );
  53. }
  54. // see http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
  55. WC()->api->server->header( 'X-Content-Type-Options', 'nosniff' );
  56. // Prepend '/**/' to mitigate possible JSONP Flash attacks
  57. return '/**/' . $_GET['_jsonp'] . '(' . json_encode( $data ) . ')';
  58. }
  59. return json_encode( $data );
  60. }
  61. }