| 1 |
<?php |
| 2 |
|
| 3 |
namespace Hostinger\Cdn; |
| 4 |
|
| 5 |
use Hostinger\WpHelper\Config; |
| 6 |
use Hostinger\WpHelper\Requests\Client; |
| 7 |
use WP_Error; |
| 8 |
|
| 9 |
defined( 'ABSPATH' ) || exit; |
| 10 |
|
| 11 |
class CacheClient { |
| 12 |
private const DEFAULT_TIMEOUT = 5; |
| 13 |
private const MAX_RESPONSE_SIZE = 65536; |
| 14 |
|
| 15 |
private Client $client; |
| 16 |
|
| 17 |
public function __construct( Client $client ) { |
| 18 |
$this->client = $client; |
| 19 |
} |
| 20 |
|
| 21 |
public function delete( string $endpoint, ?string $domain = null, int $timeout = self::DEFAULT_TIMEOUT ): array|WP_Error { |
| 22 |
$url = $this->client->get_api_url() . $endpoint; |
| 23 |
|
| 24 |
if ( preg_match( '/[\s\x00-\x1f]/', $endpoint ) || ! $this->is_allowed_url( $url ) ) { |
| 25 |
return new WP_Error( |
| 26 |
'hostinger_cdn_unexpected_host', |
| 27 |
'Refusing to send an authenticated request to an unexpected host.' |
| 28 |
); |
| 29 |
} |
| 30 |
|
| 31 |
return wp_remote_request( |
| 32 |
$url, |
| 33 |
array( |
| 34 |
'method' => 'DELETE', |
| 35 |
'headers' => $this->request_headers( $domain ), |
| 36 |
'timeout' => $timeout, |
| 37 |
'redirection' => 0, |
| 38 |
'sslverify' => true, |
| 39 |
'reject_unsafe_urls' => true, |
| 40 |
'limit_response_size' => self::MAX_RESPONSE_SIZE, |
| 41 |
) |
| 42 |
); |
| 43 |
} |
| 44 |
|
| 45 |
private function request_headers( ?string $domain ): array { |
| 46 |
$headers = $this->client->get_default_headers(); |
| 47 |
|
| 48 |
if ( $domain !== null ) { |
| 49 |
$headers[ Config::DOMAIN_HEADER ] = $domain; |
| 50 |
} |
| 51 |
|
| 52 |
return $headers; |
| 53 |
} |
| 54 |
|
| 55 |
private function is_allowed_url( string $url ): bool { |
| 56 |
$parts = wp_parse_url( $url ); |
| 57 |
|
| 58 |
if ( empty( $parts['scheme'] ) || empty( $parts['host'] ) ) { |
| 59 |
return false; |
| 60 |
} |
| 61 |
|
| 62 |
return $parts['scheme'] === 'https' && $parts['host'] === HOSTINGER_PROXY_API_HOST; |
| 63 |
} |
| 64 |
} |
| 65 |
|