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

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