jetpack-server-sandbox.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /**
  3. * This feature is only useful for Automattic developers.
  4. * It configures Jetpack to talk to staging/sandbox servers
  5. * on WordPress.com instead of production servers.
  6. */
  7. /**
  8. * @param string $sandbox Sandbox domain
  9. * @param string $url URL of request about to be made
  10. * @param array $headers Headers of request about to be made
  11. * @return array [ 'url' => new URL, 'host' => new Host ]
  12. */
  13. function jetpack_server_sandbox_request_parameters( $sandbox, $url, $headers ) {
  14. $host = '';
  15. $url_host = parse_url( $url, PHP_URL_HOST );
  16. switch ( $url_host ) {
  17. case 'public-api.wordpress.com' :
  18. case 'jetpack.wordpress.com' :
  19. case 'dashboard.wordpress.com' :
  20. $host = isset( $headers['Host'] ) ? $headers['Host'] : $url_host;
  21. $url = preg_replace(
  22. '@^(https?://)' . preg_quote( $url_host, '@' ) . '(?=[/?#].*|$)@',
  23. '\\1' . $sandbox,
  24. $url,
  25. 1
  26. );
  27. }
  28. return compact( 'url', 'host' );
  29. }
  30. /**
  31. * Modifies parameters of request in order to send the request to the
  32. * server specified by `JETPACK__SANDBOX_DOMAIN`.
  33. *
  34. * Attached to the `requests-requests.before_request` filter.
  35. * @param string &$url URL of request about to be made
  36. * @param array &$headers Headers of request about to be made
  37. * @return void
  38. */
  39. function jetpack_server_sandbox( &$url, &$headers ) {
  40. if ( ! JETPACK__SANDBOX_DOMAIN ) {
  41. return;
  42. }
  43. $original_url = $url;
  44. $request_parameters = jetpack_server_sandbox_request_parameters( JETPACK__SANDBOX_DOMAIN, $url, $headers );
  45. $url = $request_parameters['url'];
  46. if ( $request_parameters['host'] ) {
  47. $headers['Host'] = $request_parameters['host'];
  48. if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
  49. error_log( sprintf( "SANDBOXING via '%s': '%s'", JETPACK__SANDBOX_DOMAIN, $original_url ) );
  50. }
  51. }
  52. }
  53. add_action( 'requests-requests.before_request', 'jetpack_server_sandbox', 10, 2 );