| 1 |
<?php |
| 2 |
namespace StreamCast; |
| 3 |
|
| 4 |
if ( ! defined( 'ABSPATH' ) ) exit; |
| 5 |
|
| 6 |
/** |
| 7 |
* Handle AJAX requests for StreamCast |
| 8 |
*/ |
| 9 |
class AJAX { |
| 10 |
public function __construct() { |
| 11 |
add_action( 'wp_ajax_streamcast_fetch_stream', array( $this, 'fetch_stream_data' ) ); |
| 12 |
add_action( 'wp_ajax_nopriv_streamcast_fetch_stream', array( $this, 'fetch_stream_data' ) ); |
| 13 |
} |
| 14 |
|
| 15 |
/** |
| 16 |
* Fetch stream data (proxy request to avoid CORS issues) |
| 17 |
*/ |
| 18 |
public function fetch_stream_data() { |
| 19 |
// Verify nonce |
| 20 |
$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : ''; |
| 21 |
if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'streamcast_fetch_nonce' ) ) { |
| 22 |
wp_send_json_error( 'Invalid nonce', 403 ); |
| 23 |
} |
| 24 |
|
| 25 |
// Get and validate URL |
| 26 |
$url = isset( $_POST['url'] ) ? esc_url_raw( wp_unslash( $_POST['url'] ) ) : ''; |
| 27 |
if ( empty( $url ) ) { |
| 28 |
wp_send_json_error( 'Invalid URL', 400 ); |
| 29 |
} |
| 30 |
|
| 31 |
// SSRF Protection: Validate the URL to prevent access to internal services |
| 32 |
$validated_url = wp_http_validate_url( $url ); |
| 33 |
if ( ! $validated_url ) { |
| 34 |
wp_send_json_error( 'Insecure or invalid URL detected', 400 ); |
| 35 |
} |
| 36 |
|
| 37 |
// Fetch the data |
| 38 |
$response = wp_remote_get( $validated_url, array( |
| 39 |
'timeout' => 5, |
| 40 |
) ); |
| 41 |
|
| 42 |
if ( is_wp_error( $response ) ) { |
| 43 |
wp_send_json_error( $response->get_error_message(), 500 ); |
| 44 |
} |
| 45 |
|
| 46 |
$body = wp_remote_retrieve_body( $response ); |
| 47 |
|
| 48 |
// Return the data |
| 49 |
wp_send_json_success( $body ); |
| 50 |
} |
| 51 |
} |
| 52 |
|