Bez popisu

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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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\RestApi
  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. if ( ! apply_filters( 'woocommerce_api_jsonp_enabled', true ) ) {
  46. WC()->api->server->send_status( 400 );
  47. return wp_json_encode( array( array( 'code' => 'woocommerce_api_jsonp_disabled', 'message' => __( 'JSONP support is disabled on this site', 'woocommerce' ) ) ) );
  48. }
  49. $jsonp_callback = $_GET['_jsonp'];
  50. if ( ! wp_check_jsonp_callback( $jsonp_callback ) ) {
  51. WC()->api->server->send_status( 400 );
  52. return wp_json_encode( array( array( 'code' => 'woocommerce_api_jsonp_callback_invalid', __( 'The JSONP callback function is invalid', 'woocommerce' ) ) ) );
  53. }
  54. WC()->api->server->header( 'X-Content-Type-Options', 'nosniff' );
  55. // Prepend '/**/' to mitigate possible JSONP Flash attacks.
  56. // https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
  57. return '/**/' . $jsonp_callback . '(' . wp_json_encode( $data ) . ')';
  58. }
  59. return wp_json_encode( $data );
  60. }
  61. }