| 1 |
<?php |
| 2 |
|
| 3 |
if (!defined('WPO_VERSION')) die('No direct access allowed'); |
| 4 |
|
| 5 |
if (!class_exists('WPO_WebP_Self_Test')) : |
| 6 |
|
| 7 |
class WPO_WebP_Self_Test { |
| 8 |
|
| 9 |
/** |
| 10 |
* Determines whether content type header has webp mime or not |
| 11 |
* |
| 12 |
* @param array $headers An array of headers |
| 13 |
* |
| 14 |
* @return bool |
| 15 |
*/ |
| 16 |
private function has_webp_mime($headers) { |
| 17 |
return isset($headers['content-type']) && 0 === strcasecmp('image/webp', $headers['content-type']); |
| 18 |
} |
| 19 |
|
| 20 |
/** |
| 21 |
* Determines whether headers has `vary` header or not |
| 22 |
* |
| 23 |
* @param array $headers An array of headers |
| 24 |
* |
| 25 |
* @return bool |
| 26 |
*/ |
| 27 |
private function has_vary($headers) { |
| 28 |
return isset($headers['vary']) && preg_match('/accept/i', $headers['vary']); |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* Decided whether webp version is served or not |
| 33 |
* |
| 34 |
* @return bool |
| 35 |
*/ |
| 36 |
public function is_webp_served() { |
| 37 |
$args = array( |
| 38 |
'headers' => array( |
| 39 |
'accept' => 'image/webp' |
| 40 |
) |
| 41 |
); |
| 42 |
|
| 43 |
$upload_dir = wp_upload_dir(); |
| 44 |
$url = $upload_dir['baseurl']. '/wpo/images/wpo_logo_small.png'; |
| 45 |
|
| 46 |
$response = wp_remote_head($url, $args); |
| 47 |
|
| 48 |
if (is_wp_error($response)) return false; |
| 49 |
if (200 != $response['response']['code']) return false; |
| 50 |
|
| 51 |
$headers = wp_remote_retrieve_headers($response); |
| 52 |
if (method_exists($headers, 'getAll')) { |
| 53 |
$headers = $headers->getAll(); |
| 54 |
if ($this->has_webp_mime($headers) && $this->has_vary($headers)) { |
| 55 |
return true; |
| 56 |
} |
| 57 |
} |
| 58 |
return false; |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Returns singleton instance |
| 63 |
* |
| 64 |
* @return WPO_WebP_Self_Test |
| 65 |
*/ |
| 66 |
public static function get_instance() { |
| 67 |
static $_instance = null; |
| 68 |
if (null === $_instance) { |
| 69 |
$_instance = new self(); |
| 70 |
} |
| 71 |
return $_instance; |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
endif; |
| 76 |
|