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