| 1 |
<?php |
| 2 |
|
| 3 |
class berqReverseProxyCache |
| 4 |
{ |
| 5 |
public static function bypass() |
| 6 |
{ |
| 7 |
add_action('send_headers', [self::class, 'handle_bypass']); |
| 8 |
} |
| 9 |
|
| 10 |
public static function handle_bypass() |
| 11 |
{ |
| 12 |
header('Cache-Control: no-cache, no-store, must-revalidate'); |
| 13 |
header('Pragma: no-cache'); |
| 14 |
header('Expires: 0'); |
| 15 |
header('X-Bypass-Cache: ' . time()); |
| 16 |
header('Vary: X-Bypass-Cache'); |
| 17 |
} |
| 18 |
|
| 19 |
public static function is_reverse_proxy_cache_enabled() |
| 20 |
{ |
| 21 |
$custom_cache_header = get_option('berqwp_custom_cache_header'); |
| 22 |
return isset($_SERVER['HTTP_X_CACHE']) || |
| 23 |
isset($_SERVER['HTTP_X_VARNISH']) || |
| 24 |
isset($_SERVER['HTTP_CF_CACHE_STATUS']) || |
| 25 |
isset($_SERVER['HTTP_X_CACHE_STATUS']) || |
| 26 |
isset($_SERVER['HTTP_X_FASTCGI_CACHE']) || |
| 27 |
($custom_cache_header && isset($_SERVER[$custom_cache_header])); |
| 28 |
} |
| 29 |
|
| 30 |
public static function purge_varnish_cache($url) { |
| 31 |
|
| 32 |
// Parse the URL to extract the host for the Host header |
| 33 |
$parse_url = parse_url($url); |
| 34 |
$host = $parse_url['host']; |
| 35 |
|
| 36 |
$headers = [ |
| 37 |
"Host: $host" |
| 38 |
]; |
| 39 |
|
| 40 |
// Purge varnish cache for whole website |
| 41 |
if (strpos($url, '.*') !== false) { |
| 42 |
$headers['X-Ban-Url'] = '.*'; |
| 43 |
$url = home_url(); |
| 44 |
} |
| 45 |
|
| 46 |
$ch = curl_init(); |
| 47 |
curl_setopt($ch, CURLOPT_URL, $url); |
| 48 |
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'BAN'); |
| 49 |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); |
| 50 |
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); |
| 51 |
|
| 52 |
$response = curl_exec($ch); |
| 53 |
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); |
| 54 |
curl_close($ch); |
| 55 |
|
| 56 |
return $httpCode === 200; |
| 57 |
} |
| 58 |
|
| 59 |
public static function purge_cache($url) |
| 60 |
{ |
| 61 |
if (!self::is_reverse_proxy_cache_enabled()) { |
| 62 |
return false; |
| 63 |
} |
| 64 |
|
| 65 |
$parsed_url = parse_url($url); |
| 66 |
$host = $parsed_url['host']; |
| 67 |
|
| 68 |
wp_remote_request($url, array( |
| 69 |
'method' => 'PURGE', |
| 70 |
'headers' => array( |
| 71 |
'Host' => $host |
| 72 |
) |
| 73 |
) |
| 74 |
); |
| 75 |
|
| 76 |
self::purge_varnish_cache($url); |
| 77 |
} |
| 78 |
} |