PluginProbe
Translation with DeepL API / 2.4.5
Translation with DeepL API v2.4.5
trunk 0.1.20180323 1.0 1.2.5.1 1.5.2.5 1.7.5 2.4.3.12 2.4.3.9 2.4.5
wpdeepl / client / deeplapi.class.php

deeplapi.class.php in Translation with DeepL API 2.4.5, at client/deeplapi.class.php

458 lines 11.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 abstract class DeepLApi extends DeepLData {
4 protected $endPoint = '';
5 protected $http_mode = '';
6 private $endPointURL = false;
7 protected $authKey = '';
8 protected $log = false;
9 protected $headers = array();
10
11 public $languages;
12 public $doing_cron;
13 public $instance;
14 public $result;
15 public $why_no_cache;
16 public $final_request;
17 public $format;
18
19 protected $cache_dir = false;
20
21 protected $request = array();
22 protected $uniqid = false;
23 protected $cache_file = false;
24 protected $response = false;
25 public $cache_prefix = false;
26 protected $cache_id = false;
27
28 public $allow_cache = true;
29 public $response_type = 'fresh';
30 public $request_cache_file = '';
31 public $response_cache_file = '';
32
33 public $start_microtime = 0;
34 public $end_microtime = 0;
35 public $request_microtime = 0;
36
37 const TIMEOUT = 15;
38
39 public function __construct( $languages = array(), $log = false ) {
40 $this->authKey = DeepLConfiguration::getAPIKey();
41 //$this->request['auth_key'] = $auth_key;
42 $this->log = $log;
43
44 $this->languages = DeepLConfiguration::DefaultsAllLanguages();
45
46 if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
47 $this->doing_cron = true;
48 }
49 else {
50 $this->doing_cron = false;
51 }
52
53 $this->instance = $this;
54
55 $this->cache_dir = $this->getCacheDirectory();
56 }
57
58 public function allowCache( $allow_cache ) {
59 $this->allow_cache = filter_var( $allow_cache, FILTER_VALIDATE_BOOLEAN );
60 }
61
62 public function wasItCached() {
63 return $this->response_type === 'cache';
64 }
65
66 public function getTimeElapsed() {
67 return $this->request_microtime;
68 }
69
70 abstract public function buildBody( $mode, $endPoint );
71
72 public function getRequestUniqueID() {
73 if ( $this->cache_id ) {
74 $this->uniqid = $this->cache_id;
75 }
76 elseif ( !$this->uniqid ) {
77 $this->uniqid = microtime();
78 }
79 return $this->uniqid;
80 }
81
82 public function isValidRequest() {
83 return true;
84 }
85
86 /*
87 protected function maybeLimitRequestSize() {
88 }
89 */
90 protected function saveRequest() {
91 if ( isset( $this->request_cache_file ) ) {
92 file_put_contents( $this->request_cache_file, json_encode( $this->final_request ) );
93 }
94 }
95
96 protected function addHeaders( $headers ) {
97 return $headers;
98 }
99
100 protected function doRequest( $mode = false ) {
101 if( !$mode )
102 $mode = $this->http_mode;
103
104
105 if ( $mode == 'GET' ) {
106 $response = $this->doGETRequest();
107 }
108 elseif( $mode == 'DELETE' ) {
109 $response = $this->doGETRequest( 'DELETE' );
110 }
111 elseif( $mode == 'PUT' ) {
112 $response = $this->doGETRequest( 'PUT' );
113 }
114 else {
115 $response = $this->doPOSTRequest();
116 }
117
118 return $response;
119 }
120
121 static function getInstance() {
122 return self::instance;
123 }
124
125 protected function setCacheID( $idstring ) {
126 $this->cache_id = $idstring;
127 }
128
129 public function setCachePrefix( $prefix = '' ) {
130 if ( !empty( $prefix ) ) {
131 $this->cache_prefix = $prefix;
132 }
133 else {
134 $this->cache_prefix = '';
135 }
136 }
137
138 public function getCacheFile( $type ) {
139 if ( $type == 'response' ) {
140 return $this->response_cache_file;
141 }
142 elseif ( $type == 'request' ) {
143 return $this->request_cache_file;
144 }
145 }
146
147 public function setCacheNames() {
148 $cache_name = '';
149 if ( !empty( $this->cache_prefix ) ) {
150 $cache_name .= $this->cache_prefix .'-';
151 }
152 $cache_name .= $this->cache_id;
153 $this->request_cache_file = trailingslashit( $this->cache_dir ) . $cache_name . '-request';
154 $this->response_cache_file = trailingslashit( $this->cache_dir ) . $cache_name . '-response';
155 }
156
157 public function request() {
158
159 $log_bits = array('class' => get_class($this));
160
161 if ( $this->allow_cache )
162 $this->uniqid = $this->getRequestUniqueID();
163
164 $log_bits['uniqid'] = $this->uniqid;
165
166 $this->setCacheNames();
167 $this->result = false;
168
169 if ( $this->isCacheValid( $this->response_cache_file ) ) {
170 $this->response_type = 'cache';
171 $this->why_no_cache = false;
172 $this->result = file_get_contents( $this->response_cache_file );
173 $log_bits['type'] = 'cached';
174
175 }
176 else {
177 $log_bits['type'] = 'fresh';
178 $log_bits['mode'] = $this->http_mode;
179 $this->start_microtime = microtime( true );
180 //echo "\nIS FRESH";
181 $this->response_type = 'fresh';
182
183
184 if ( $this->http_mode == 'GET' ) {
185 $response = $this->doRequest( 'GET' );
186 }
187 else {
188 $response = $this->doRequest( 'POST' );
189 }
190
191
192 $this->end_microtime = microtime( true );
193 $this->request_microtime = $this->end_microtime - $this->start_microtime;
194
195 if ( is_wp_error( $response ) ) {
196 return $response->get_error_message();
197 }
198
199 if ( $response['response']['code'] > 299 ) {
200 $log_bits['response_error'] = $response['response']['code'];
201 $log_bits['response'] = $response['response'];
202 if ( $response['response']['code'] == 429 ) {
203 $log_bits['error_cause'] = 'Excessive request size';
204 }
205 if ( DeepLConfiguration::getLogLevel() ) wpdeepl_log($log_bits, "operation");
206
207 $body = json_decode( $response['body'], true );
208 $message = isset( $body['message'] ) ? $body['message'] : false;
209 return new WP_Error( $message );
210 }
211
212 if ( array_key_exists( 'body', $response ) && strlen( $response['body'] ) )
213 $this->result = $response['body'];
214 else
215 $this->result = false;
216
217 if ( $this->result ) {
218 //echo " putting " . strlen( serialize( $this->result ) ) ." in "
219 try {
220 file_put_contents( $this->response_cache_file, $this->result );
221 } catch (Exception $e) {
222
223 }
224 }
225
226 $log_bits['request_microtime'] = $this->request_microtime;
227 }
228
229 if ( DeepLConfiguration::getLogLevel() ) {
230 if ( DeepLConfiguration::getLogLevel() > 1 ) {
231 foreach( $this->request as $key => $value ) {
232 if( is_string( $value ) && strlen( $value ) > 500 )
233 $log_bits['args'][$key] = "LEN=" . strlen( $value) .", string = " . substr( $value, 0, 100 );
234 else
235 $log_bits['args'][$key] = $value;
236
237 }
238 }
239 else {
240 foreach ( array ('source_lang', 'target_lang') as $key ) {
241 if ( isset( $this->request[$key] ) ) {
242 $log_bits[$key] = $this->request[$key];
243 }
244 }
245 }
246 if ( isset( $this->request['text'] ) ) {
247 $text_size = 0;
248 foreach ( $this->request['text'] as $i => $string ) {
249 $text_size += strlen($string);
250 }
251 $log_bits['text_size'] = $text_size;
252 }
253 }
254
255 if ($this->response_type == 'fresh') {
256 // test if JSON
257 json_decode($this->result);
258 if (json_last_error() == JSON_ERROR_NONE) {
259 $log_bits['response'] = json_decode($this->result, 1 );
260 if ( DeepLConfiguration::getLogLevel() ) {
261 if (isset( $log_bits['response']['translations'] ) ) {
262 $translated_text_size = 0;
263 foreach ( $log_bits['response']['translations'] as $i => $translation ) {
264 $translated_text_size += strlen( $translation['text'] );
265 }
266 $log_bits['translated_text_size'] = $translated_text_size;
267 }
268 }
269 }
270 else {
271 $log_bits['response'] = $this->result;
272 }
273
274 }
275 else {
276 $log_bits['response'] = '--hidden response because cached request--';
277
278 }
279 $log_bits['response_length'] = strlen($this->result);
280
281 if ( $this->result ) {
282 $this->result = json_decode( $this->result );
283
284 $this->result = ( array ) $this->result;
285 $this->result['response_type'] = $this->response_type;
286 if ( $this->why_no_cache ) {
287 $log_bits['why_no_cache'] = $this->why_no_cache;
288 $this->result['why_no_cache'] = $this->why_no_cache;
289 }
290 if ( DeepLConfiguration::getLogLevel() ) wpdeepl_log($log_bits, "operation");
291 return $this->result;
292 }
293 else {
294 if ( DeepLConfiguration::getLogLevel() ) wpdeepl_log($log_bits, "operation");
295 return $this->response['response']['message'];
296 }
297 }
298
299 public function getRequestTime( $result_in_milliseconds = false ) {
300 if ( !$this->request_microtime ) {
301 return false;
302 }
303
304 if ( $result_in_milliseconds ) {
305 return floatval( $this->request_microtime );
306 }
307 else {
308 return floatval( $this->request_microtime/1000 );
309 }
310 }
311
312 public function getEndPointURL( $add_auth_key = false ) {
313
314
315 $APIServer = DeeplConfiguration::getAPIServer();
316 if ( !$this->endPointURL ) {
317 if ( $this->endPoint === '' ) {
318 $this->endPointURL = $APIServer;
319 }
320 else {
321 $this->endPointURL = trailingslashit( $APIServer ) . $this->endPoint;
322 }
323 }
324
325 if ( $add_auth_key ) {
326 $this->endPointURL .= '?auth_key=' . $this->authKey;
327 }
328
329 return $this->endPointURL;
330 }
331 /*
332 * send a POST request
333 *
334 * @since 0.1
335 */
336 public function doPOSTRequest( $args = array() ) {
337
338
339 $args = array(
340 'method' => 'POST',
341 'timeout' => self::TIMEOUT,
342 );
343
344 $args['headers'] = array(
345 'Authorization' => 'DeepL-Auth-Key ' . $this->authKey
346 );
347
348 $args['headers'] = $this->addHeaders( $args['headers'] );
349 $args['body'] = $this->buildBody( 'POST', $this->endPoint );
350
351 //plouf( $args ,__METHOD__ . "args");
352
353 /*
354 $args['auth_key'] = $this->authKey;
355
356 $request = array();
357 if ( $this->request ) {
358 foreach ( $this->request as $key => $value ) {
359 $request[$key] = $value;
360 }
361 }
362 $args['query'] = http_build_query( $request );
363 $args['timeout'] =
364 */
365 //$args['headers']['Content-Type'] = 'application/x-www-form-urlencoded';
366 // $this->headers['Content-Length'] = strlen( $this->request['text'] );
367
368
369
370 $add_auth_key = false;
371 $remoteURL = $this->getEndPointURL( $add_auth_key );
372
373 $bits = array_merge( array( $remoteURL, 'POST' ), $args );
374 // unsafe
375 //wpdeepl_log( $bits, 'apiRequests');
376 // plouf( $args, "args" );
377 /*
378 $exec = "curl -X POST '$remoteURL' \\\n";
379 foreach( $args['headers'] as $key => $value ) {
380 $exec .= "-H '$key: $value' \\\n";
381 }
382 foreach( $args['body'] as $key => $value ) {
383 $exec .= "-d '$value' \\\n";
384 }
385
386 plouf( $exec );
387 $response = exec ( $exec );
388 plouf( $response );
389 die('okaz4a6e4a68e4a86e');
390 */
391
392 //plouf( $args, $remoteURL ); die('68z4e6z48a68ee8aok');
393
394 //$args['body'] = str_replace('target_lang=NO', 'target_lang=NB', $args['body'] );
395 $response = wp_remote_post( $remoteURL, $args );
396 //plouf( $args, $remoteURL, " post request"); plouf( $response ); die('okesoezporjkezor');
397
398 // plouf( $args, " args pour $remoteURL" ); plouf( $response, "zeirjzpeijrpizerjpirj" ); die('okaze6aze44e');
399 //plouf( $args, "args");
400
401 // plouf( $args, "POST request to $remoteURL ");die('okaz5ea5zea4e');
402
403 if ( is_wp_error( $response ) ) {
404 $this->response = $response->get_error_message();
405 plouf( $args, $this->getEndPointURL() );
406 die( __METHOD__ );
407 }
408 else {
409 $this->response = $response;
410 }
411 return $response;
412 }
413
414 /*
415 * send a GET request
416 *
417 * @since 0.1
418 */
419 public function doGETRequest( $alt_mode = false ) {
420
421 $method = 'GET';
422 if( in_array( $alt_mode, array('PUT', 'DELETE' ) ) )
423 $method = $alt_mode;
424 $args = array(
425 'method' => $method,
426 'timeout' => self::TIMEOUT,
427 );
428
429 $args['headers'] = array(
430 'Authorization' => 'DeepL-Auth-Key ' . $this->authKey
431 );
432 $args['headers'] = $this->addHeaders( $args['headers'] );
433
434 $remoteURL = $this->getEndPointURL();
435 //if( $args['query'] ) $remoteURL .= '?' . $args['query'];
436
437
438 $curl_string = 'curl -X ' . $args['method'] . " '$remoteURL'\n";
439 foreach( $args['headers'] as $key => $value ) {
440 $curl_string .= "$key: $value\n";
441 }
442 //echo "\n CURL = " . str_replace("\n", '<br />', $curl_string );
443 $bits = array_merge( array( $remoteURL, 'GET' ), $args );
444 // unsafe
445 //wpdeepl_log( $bits, 'apiRequests');
446
447 // plouf( $args, $remoteURL ); die('oazea4ze9684e84azek');
448
449 $response = wp_remote_get( $remoteURL, $args );
450 //plouf( $args, $remoteURL ); plouf( $response ); die('ok');
451 if ( is_wp_error( $response ) ) {
452 $this->response = $response->get_error_message();
453 } else {
454 $this->response = $response;
455 }
456 return $response;
457 }
458 }