| 1 |
<?php |
| 2 |
if (!defined('ABSPATH')) exit; |
| 3 |
|
| 4 |
class Cloudways extends berqIntegrations { |
| 5 |
function __construct() { |
| 6 |
add_action('berqwp_stored_page_cache', [$this, 'flush_page_cache']); |
| 7 |
add_action('berqwp_flush_page_cache', [$this, 'flush_page_cache']); |
| 8 |
add_action('berqwp_flush_all_cache', [$this, 'flush_all_page_cache']); |
| 9 |
} |
| 10 |
|
| 11 |
function flush_page_cache($slug = '/') { |
| 12 |
if (empty($slug)) { |
| 13 |
$slug = '/'; |
| 14 |
} |
| 15 |
$page_url = home_url($slug); |
| 16 |
$this->flush_cloudways_varnish($page_url); |
| 17 |
} |
| 18 |
|
| 19 |
function flush_cloudways_varnish($url = '') { |
| 20 |
|
| 21 |
if (!$this->is_varnish_running()) { |
| 22 |
return; |
| 23 |
} |
| 24 |
|
| 25 |
if (!$this->is_cloudways_hosting()) { |
| 26 |
return; |
| 27 |
} |
| 28 |
|
| 29 |
if (empty($url)) { |
| 30 |
$url = home_url(); |
| 31 |
} |
| 32 |
|
| 33 |
$host = !empty($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : ''; |
| 34 |
berqReverseProxyCache::purge_varnish_cache($url, ['127.0.0.1', $host], 'URLPURGE'); |
| 35 |
return; |
| 36 |
|
| 37 |
$parse_url = parse_url($url); |
| 38 |
$host = $parse_url['host']; |
| 39 |
|
| 40 |
// Setup the request to purge Varnish cache |
| 41 |
$ch = curl_init(); |
| 42 |
curl_setopt($ch, CURLOPT_URL, $url); |
| 43 |
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PURGE'); |
| 44 |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); |
| 45 |
curl_setopt($ch, CURLOPT_HTTPHEADER, [ |
| 46 |
"Host: $host" |
| 47 |
]); |
| 48 |
|
| 49 |
$response = curl_exec($ch); |
| 50 |
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); |
| 51 |
curl_close($ch); |
| 52 |
|
| 53 |
return $httpCode === 200; |
| 54 |
} |
| 55 |
|
| 56 |
function flush_all_page_cache() { |
| 57 |
|
| 58 |
if (!$this->is_varnish_running()) { |
| 59 |
return; |
| 60 |
} |
| 61 |
|
| 62 |
if (!$this->is_cloudways_hosting()) { |
| 63 |
return; |
| 64 |
} |
| 65 |
|
| 66 |
$url = home_url('/.*'); |
| 67 |
$host = !empty($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : ''; |
| 68 |
berqReverseProxyCache::purge_varnish_cache($url, ['127.0.0.1', $host], 'PURGE'); |
| 69 |
return; |
| 70 |
|
| 71 |
} |
| 72 |
|
| 73 |
function is_varnish_running() { |
| 74 |
// Check if the 'X-Varnish' or 'X-Cache' headers are present in the response headers |
| 75 |
if (isset($_SERVER['HTTP_X_VARNISH']) || isset($_SERVER['HTTP_X_CACHE'])) { |
| 76 |
return true; |
| 77 |
} |
| 78 |
|
| 79 |
return false; |
| 80 |
} |
| 81 |
|
| 82 |
function is_cloudways_hosting() { |
| 83 |
if (isset($_SERVER['cw_allowed_ip']) || isset($_SERVER['HTTP_CF_IPCOUNTRY']) || strpos($_SERVER['DOCUMENT_ROOT'], '.cloudwaysapps.com') !== false) { |
| 84 |
return true; |
| 85 |
} |
| 86 |
|
| 87 |
return false; |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
new Cloudways(); |