class-rio-server-abstract.php
3 months ago
class-rio-server-premium.php
3 months ago
class-rio-server-robin.php
3 months ago
index.php
3 years ago
class-rio-server-robin.php
226 lines
| 1 | <?php |
| 2 | // Exit if accessed directly |
| 3 | if ( ! defined( 'ABSPATH' ) ) { |
| 4 | exit; |
| 5 | } |
| 6 | |
| 7 | /** |
| 8 | * Класс для оптимизации изображений через API Robin (beta). |
| 9 | */ |
| 10 | class WIO_Image_Processor_Robin extends WIO_Image_Processor_Abstract { |
| 11 | |
| 12 | /** |
| 13 | * @var string |
| 14 | */ |
| 15 | protected $api_url; |
| 16 | |
| 17 | /** |
| 18 | * @var string Имя сервера |
| 19 | */ |
| 20 | protected $server_name = 'server_2'; |
| 21 | |
| 22 | /** |
| 23 | * Инициализация |
| 24 | * |
| 25 | * @return void |
| 26 | */ |
| 27 | public function __construct() { |
| 28 | $this->api_url = $this->get_api_url(); |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * Оптимизация изображения |
| 33 | * |
| 34 | * @param array $params в� |
| 35 | одные параметры оптимизации изображения |
| 36 | * |
| 37 | * @return array|WP_Error { |
| 38 | * Результаты оптимизации |
| 39 | * |
| 40 | * {type} string $optimized_img_url УРЛ оптимизированного изображения на сервере оптимизации |
| 41 | * {type} int $src_size размер ис� |
| 42 | одного изображения в байта� |
| 43 | |
| 44 | * {type} int $optimized_size размер оптимизированного изображения в байта� |
| 45 | |
| 46 | * {type} int $optimized_percent На сколько процентов уменьшилось изображение |
| 47 | * } |
| 48 | */ |
| 49 | public function process( $settings ) { |
| 50 | |
| 51 | $settings = wp_parse_args( |
| 52 | $settings, |
| 53 | [ |
| 54 | 'image_url' => '', |
| 55 | 'quality' => 100, |
| 56 | 'save_exif' => false, |
| 57 | ] |
| 58 | ); |
| 59 | |
| 60 | $query_args = [ |
| 61 | 'quality' => $settings['quality'], |
| 62 | 'progressive' => true, |
| 63 | ]; |
| 64 | |
| 65 | if ( $settings['save_exif'] ) { |
| 66 | $query_args['strip-exif'] = true; |
| 67 | } |
| 68 | |
| 69 | if ( ! empty( $settings['image_url'] ) ) { |
| 70 | $query_args['image_url'] = wrio_encode_image_url( $settings['image_url'] ); |
| 71 | } |
| 72 | |
| 73 | $file = wp_normalize_path( $settings['image_path'] ); |
| 74 | |
| 75 | if ( ! file_exists( $file ) ) { |
| 76 | return new WP_Error( 'http_request_failed', sprintf( "File %s isn't exists.", $file ) ); |
| 77 | } |
| 78 | |
| 79 | WRIO_Plugin::app()->logger->info( sprintf( 'Preparing to upload a file (%s) to a remote server (%s).', $settings['image_path'], $this->api_url ) ); |
| 80 | |
| 81 | $max_size_in_bytes = 10 * 1024 * 1024; // 10MB |
| 82 | if ( filesize( $file ) > $max_size_in_bytes ) { |
| 83 | $error_message = sprintf( |
| 84 | // translators: %1$s: max size in MB, %2$s: option name. |
| 85 | __( 'Image exceeds the maximum allowed size of %1$sMB! Enable the \'%2$s\' option to reduce the image size or upgrade to a Pro plan.', 'robin-image-optimizer' ), |
| 86 | 10, |
| 87 | __( 'Resizing large images', 'robin-image-optimizer' ) |
| 88 | ); |
| 89 | WRIO_Plugin::app()->logger->error( $error_message ); |
| 90 | |
| 91 | return new WP_Error( 'image_size_limit_exceeded', $error_message ); |
| 92 | } |
| 93 | |
| 94 | $boundary = '--------------------------' . md5( microtime( true ) . wp_rand() ); |
| 95 | $host = get_option( 'siteurl' ); |
| 96 | $headers = [ |
| 97 | 'Authorization' => 'Bearer ' . base64_encode( $host ), |
| 98 | 'content-type' => 'multipart/form-data; boundary=' . $boundary, |
| 99 | ]; |
| 100 | |
| 101 | $payload = ''; |
| 102 | |
| 103 | // First, add the standard POST fields: |
| 104 | foreach ( $query_args as $name => $value ) { |
| 105 | $payload .= '--' . $boundary; |
| 106 | $payload .= "\r\n"; |
| 107 | $payload .= 'Content-Disposition: form-data; name="' . $name . '"' . "\r\n\r\n"; |
| 108 | $payload .= $value; |
| 109 | $payload .= "\r\n"; |
| 110 | } |
| 111 | |
| 112 | // Upload the file |
| 113 | if ( $file ) { |
| 114 | $payload .= '--' . $boundary; |
| 115 | $payload .= "\r\n"; |
| 116 | $payload .= 'Content-Disposition: form-data; name="file"; filename="' . basename( $file ) . '"' . "\r\n"; |
| 117 | // $payload .= 'Content-Type: image/jpeg' . "\r\n"; // If you know the mime-type |
| 118 | $payload .= "\r\n"; |
| 119 | $payload .= @file_get_contents( $file ); |
| 120 | $payload .= "\r\n"; |
| 121 | } |
| 122 | |
| 123 | $payload .= '--' . $boundary . '--'; |
| 124 | |
| 125 | $error_message = sprintf( 'Failed to get content of URL: %s as wp_remote_request()', $this->api_url ); |
| 126 | |
| 127 | wp_raise_memory_limit( 'image' ); |
| 128 | |
| 129 | $response = wp_remote_request( |
| 130 | $this->api_url, |
| 131 | [ |
| 132 | 'method' => 'POST', |
| 133 | 'headers' => $headers, |
| 134 | 'body' => $payload, |
| 135 | 'timeout' => 150, // it make take some time for large images and slow Internet connections |
| 136 | ] |
| 137 | ); |
| 138 | |
| 139 | if ( is_wp_error( $response ) ) { |
| 140 | $ss = $response->get_error_code(); |
| 141 | |
| 142 | WRIO_Plugin::app()->logger->error( sprintf( '%s returned error (%s).', $error_message, $response->get_error_message() ) ); |
| 143 | |
| 144 | return $response; |
| 145 | } |
| 146 | |
| 147 | $response_code = (int) wp_remote_retrieve_response_code( $response ); |
| 148 | |
| 149 | if ( 200 !== $response_code ) { |
| 150 | return $this->log_http_error_response( $error_message, $response_code, wp_remote_retrieve_body( $response ) ); |
| 151 | } |
| 152 | |
| 153 | $response_text = wp_remote_retrieve_body( $response ); |
| 154 | $data = @json_decode( $response_text ); |
| 155 | |
| 156 | if ( ! isset( $data->status ) ) { |
| 157 | WRIO_Plugin::app()->logger->error( sprintf( '%s responded an empty request body.', $error_message ) ); |
| 158 | |
| 159 | return new WP_Error( 'http_request_failed', 'Server responded an empty request body.' ); |
| 160 | } |
| 161 | |
| 162 | if ( $data->status != 'ok' ) { |
| 163 | WRIO_Plugin::app()->logger->error( sprintf( 'Pending status "ok", bot received "%s"', $data->status ) ); |
| 164 | |
| 165 | if ( isset( $data->error ) && is_string( $data->error ) ) { |
| 166 | return new WP_Error( 'http_request_failed', $this->append_status_code_to_message( $data->error, $response_code ) ); |
| 167 | } |
| 168 | |
| 169 | return new WP_Error( 'http_request_failed', $this->append_status_code_to_message( 'Server responded with an unexpected status.', $response_code ) ); |
| 170 | } |
| 171 | |
| 172 | if ( ! empty( $data->response->quota ) ) { |
| 173 | $this->set_quota_limit( $data->response->quota ); |
| 174 | WRIO_Plugin::app()->updatePopulateOption( 'quota_fetched', true ); |
| 175 | } |
| 176 | |
| 177 | return [ |
| 178 | 'optimized_img_url' => $data->response->dest, |
| 179 | 'src_size' => $data->response->src_size, |
| 180 | 'optimized_size' => $data->response->dest_size, |
| 181 | 'optimized_percent' => $data->response->percent, |
| 182 | 'not_need_download' => false, |
| 183 | ]; |
| 184 | } |
| 185 | |
| 186 | /** |
| 187 | * Качество изображения |
| 188 | * Метод конвертирует качество из настроек плагина в формат сервиса resmush |
| 189 | * |
| 190 | * @param mixed $quality качество |
| 191 | * |
| 192 | * @return int |
| 193 | */ |
| 194 | public function quality( $quality = 100 ) { |
| 195 | if ( is_numeric( $quality ) ) { |
| 196 | if ( $quality >= 1 && $quality <= 100 ) { |
| 197 | return $quality; |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | switch ( $quality ) { |
| 202 | case 'normal': |
| 203 | return 90; |
| 204 | |
| 205 | case 'aggresive': |
| 206 | return 75; |
| 207 | |
| 208 | case 'ultra': |
| 209 | case 'googlepage': |
| 210 | return 50; |
| 211 | |
| 212 | default: |
| 213 | return 100; |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | /** |
| 218 | * Проверяет, существует ли ограничение на квоту. |
| 219 | * |
| 220 | * @return bool Возвращает true, если ограничения. |
| 221 | */ |
| 222 | public function has_quota_limit() { |
| 223 | return true; |
| 224 | } |
| 225 | } |
| 226 |