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-abstract.php
robin-image-optimizer / includes / classes / processors Last commit date
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-abstract.php
254 lines
1 <?php
2
3 // Exit if accessed directly
4 if ( ! defined( 'ABSPATH' ) ) {
5 exit;
6 }
7
8 /**
9 * Базовый класс для обработки изображений через API сторонни�
10 сервисов.
11 *
12 * todo: add usage example
13 *
14 * @version 1.0
15 */
16 abstract class WIO_Image_Processor_Abstract {
17
18 /**
19 * @var string Имя сервера
20 */
21 protected $server_name;
22
23 /**
24 * Оптимизация изображения
25 *
26 * @param array $params {
27 * Параметры оптимизации изображения. Разные сервера могут принимать разные наборы параметров. Ниже список все�
28 возможны�
29 .
30 *
31 * {type} string $image_url УРЛ изображения
32 * {type} string $image_path Путь к файлу изображения
33 * {type} string $quality Качество
34 * {type} string $save_exif Со�
35 ранять ли EXIF данные
36 * }
37 *
38 * @return array|WP_Error {
39 * Результаты оптимизации. Основные параметры. Другие параметры зависят от конкретной раелизации.
40 *
41 * {type} string $optimized_img_url УРЛ оптимизированного изображения на сервере оптимизации
42 * {type} int $src_size размер ис�
43 одного изображения в байта�
44
45 * {type} int $optimized_size размер оптимизированного изображения в байта�
46
47 * {type} int $optimized_percent На сколько процентов уменьшилось изображение
48 * {type} bool $not_need_replace Изображение не надо заменять.
49 * {type} bool $not_need_download Изображение не надо скачивать.
50 * }
51 */
52 abstract function process( $params );
53
54 /**
55 * Качество изображения
56 * Метод конвертирует качество из настроек плагина в формат сервиса оптимизации
57 *
58 * @param mixed $quality качество
59 */
60 abstract function quality( $quality );
61
62 /**
63 * Проверка наличия ограничения на квоту
64 *
65 * @return bool Возвращает true, если существует ограничение на квоту, иначе false
66 */
67 abstract public function has_quota_limit();
68
69 /**
70 * Возвращает URL API сервера
71 *
72 * @return string
73 */
74 public function get_api_url() {
75 return wrio_get_server_url( $this->server_name );
76 }
77
78 /**
79 * Установка лимита квоты
80 *
81 * @param mixed $value Новое значение лимита квоты
82 *
83 * @return void
84 */
85 public function set_quota_limit( $value ) {
86 WRIO_Plugin::app()->updatePopulateOption( $this->server_name . '_quota_limit', (int) $value );
87 }
88
89
90 /**
91 * Получает лимит квоты для текущего сервера.
92 *
93 * @return int Лимит квоты, установленный для сервера. Если лимит не задан, возвращается 0.
94 */
95 public function get_quota_limit() {
96 return WRIO_Plugin::app()->getPopulateOption( $this->server_name . '_quota_limit', 0 );
97 }
98
99 /**
100 * HTTP запрос к API стороннего сервиса.
101 *
102 * @param string $type POST|GET
103 * @param string $url URL для запроса
104 * @param array|string|null $body Параметры запроса. По умолчанию: false.
105 * @param array $headers Дополнительные заголовки. По умолчанию: false.
106 *
107 * @return string|WP_Error
108 */
109 protected function request( $type, $url, $body = null, array $headers = [] ) {
110
111 $args = [
112 'method' => $type,
113 'headers' => array_merge(
114 [
115 'User-Agent' => '',
116 ],
117 $headers
118 ),
119 'body' => $body,
120 'timeout' => 150, // it make take some time for large images and slow Internet connections
121 ];
122
123 $error_message = sprintf( 'Failed to get content of URL: %s as wp_remote_request()', $url );
124
125 wp_raise_memory_limit( 'image' );
126 $response = wp_remote_request( $url, $args );
127
128 if ( is_wp_error( $response ) ) {
129 WRIO_Plugin::app()->logger->error( sprintf( '%s returned error (%s).', $error_message, $response->get_error_message() ) );
130
131 return $response;
132 }
133
134 $response_body = wp_remote_retrieve_body( $response );
135 $response_code = (int) wp_remote_retrieve_response_code( $response );
136
137 if ( 200 !== $response_code ) {
138 return $this->log_http_error_response( $error_message, $response_code, $response_body );
139 }
140
141 if ( empty( $response_body ) ) {
142 WRIO_Plugin::app()->logger->error( sprintf( '%s responded an empty request body.', $error_message ) );
143
144 return new WP_Error( 'http_request_failed', 'Server responded an empty request body.' );
145 }
146
147 return $response_body;
148 }
149
150 /**
151 * Log a non-200 response and preserve the raw response body when available.
152 *
153 * @param string $error_message Base error message for the request.
154 * @param int $response_code HTTP response code.
155 * @param string $response_body Raw HTTP response body.
156 *
157 * @return WP_Error
158 */
159 protected function log_http_error_response( $error_message, $response_code, $response_body ) {
160 if ( ! empty( $response_body ) ) {
161 WRIO_Plugin::app()->logger->error( sprintf( '%s responded Http error (%d).', $error_message, $response_code ) );
162 WRIO_Plugin::app()->logger->debug( sprintf( '%s response body: %s', $error_message, $this->prepare_response_body_for_log( $response_body ) ) );
163
164 return new WP_Error( 'http_request_failed', $this->append_status_code_to_message( 'Server responded with HTTP error.', $response_code ) );
165 }
166
167 WRIO_Plugin::app()->logger->error( sprintf( '%s responded Http error (%d).', $error_message, $response_code ) );
168
169 return new WP_Error( 'http_request_failed', $this->append_status_code_to_message( 'Server responded with HTTP error.', $response_code ) );
170 }
171
172 /**
173 * Append an HTTP status code to a user-facing error message.
174 *
175 * @param string $message Base error message.
176 * @param int $response_code HTTP response code.
177 *
178 * @return string
179 */
180 protected function append_status_code_to_message( $message, $response_code ) {
181 $message = trim( (string) $message );
182
183 if ( empty( $response_code ) ) {
184 return $message;
185 }
186
187 if ( false !== stripos( $message, 'HTTP ' . $response_code ) ) {
188 return $message;
189 }
190
191 return sprintf( '%1$s (HTTP %2$d)', rtrim( $message, '.' ), (int) $response_code );
192 }
193
194 /**
195 * Prepare an HTTP response body for debug logging.
196 *
197 * @param string $response_body Raw HTTP response body.
198 *
199 * @return string
200 */
201 protected function prepare_response_body_for_log( $response_body ) {
202 $response_body = wp_check_invalid_utf8( (string) $response_body );
203 $response_body = trim( wp_strip_all_tags( $response_body ) );
204
205 if ( '' === $response_body ) {
206 return '[empty after sanitization]';
207 }
208
209 $max_length = 500;
210
211 if ( strlen( $response_body ) > $max_length ) {
212 $response_body = substr( $response_body, 0, $max_length ) . '...';
213 }
214
215 return $response_body;
216 }
217
218 /**
219 * Использует ли сервер отложенную оптимизацию
220 *
221 * @return bool
222 */
223 public function isDeferred() {
224 return false;
225 }
226
227 /**
228 * Проверка отложенной оптимизации изображения
229 *
230 * @param array $optimized_data Параметры отложенной оптимизации. Набор параметров зависит от конкретной реализации
231 *
232 * @return bool|array
233 */
234 public function checkDeferredOptimization( $optimized_data ) {
235 return false;
236 }
237
238 /**
239 * Проверка данны�
240 для отложенной оптимизации.
241 *
242 * Проверяет наличие необ�
243 одимы�
244 параметров и соответствие серверу.
245 *
246 * @param array $optimized_data Параметры отложенной оптимизации. Набор параметров зависит от конкретной реализации
247 *
248 * @return bool
249 */
250 public function validateDeferredData( $optimized_data ) {
251 return false;
252 }
253 }
254