Açıklama Yok

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

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