| 1 |
<?php |
| 2 |
namespace Upress\EzCache; |
| 3 |
|
| 4 |
use ErrorException; |
| 5 |
use ParagonIE\Sodium\Core\Poly1305\State; |
| 6 |
use WP_Error; |
| 7 |
|
| 8 |
class WebpApi { |
| 9 |
protected $domain; |
| 10 |
protected $license_key; |
| 11 |
protected $api_url = 'https://api.ezcache.app'; |
| 12 |
|
| 13 |
function __construct( $key ) { |
| 14 |
$this->domain = str_replace( [ 'https://', 'http://' ], '', get_bloginfo( 'wpurl' ) ); |
| 15 |
$this->license_key = $key; |
| 16 |
} |
| 17 |
|
| 18 |
public function convert( $image_path ) { |
| 19 |
wp_raise_memory_limit( 'image' ); |
| 20 |
|
| 21 |
$url = $this->api_url . '?' . http_build_query( [ 'licence_key' => $this->license_key, 'domain' => $this->domain ] ); |
| 22 |
|
| 23 |
$file = @fopen( $image_path, 'r' ); |
| 24 |
$file_size = filesize( $image_path ); |
| 25 |
$file_data = fread( $file, $file_size ); |
| 26 |
|
| 27 |
if ( false === $file_data ) { |
| 28 |
return new WP_Error( 'invalid_input_file', 'Unable to read source image file' ); |
| 29 |
} |
| 30 |
|
| 31 |
$response = wp_remote_post( $url, [ |
| 32 |
'headers' => [ |
| 33 |
'content-type' => 'application/binary', |
| 34 |
'X-Requested-By' => 'wp_remote_request' |
| 35 |
], |
| 36 |
'body' => $file_data, |
| 37 |
'timeout' => 900, |
| 38 |
'user-agent' => 'ezCache WebP Converter', |
| 39 |
] ); |
| 40 |
|
| 41 |
@fclose( $file ); |
| 42 |
|
| 43 |
if ( is_wp_error( $response ) ) { |
| 44 |
error_log( 'ezCache API Error: ' . $response->get_error_message() ); |
| 45 |
return $response; |
| 46 |
} |
| 47 |
|
| 48 |
$info = wp_remote_retrieve_headers( $response ); |
| 49 |
$result = wp_remote_retrieve_body( $response ); |
| 50 |
|
| 51 |
return [ 'info' => $info, 'data' => $result ]; |
| 52 |
} |
| 53 |
} |
| 54 |
|