class-wpml-tm-ate-api.php
18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
<?php
use WPML\TM\ATE\API\FingerprintGenerator;
use WPML\TM\ATE\Log\Entry;
use WPML\TM\ATE\Log\EventsTypes;
use WPML\TM\ATE\ClonedSites\ApiCommunication as ClonedSitesHandler;
use WPML\FP\Obj;
use WPML\FP\Fns;
use WPML\FP\Either;
use WPML\FP\Lst;
use WPML\FP\Logic;
use WPML\FP\Str;
use WPML\Element\API\Entity\LanguageMapping;
use WPML\LIB\WP\WordPress;
use WPML\TM\Editor\ATEDetailedErrorMessage;
use function WPML\FP\invoke;
use function WPML\FP\pipe;
use WPML\Element\API\Languages;
use WPML\FP\Relation;
use WPML\FP\Maybe;
use WPML\TM\ATE\API\RequestException;
/**
* @author OnTheGo Systems
*/
class WPML_TM_ATE_API {
const TRANSLATED = 6;
const DELIVERING = 7;
const NOT_ENOUGH_CREDIT_STATUS = 31;
const CANCELLED_STATUS = 20;
const SHOULD_HIDE_STATUS = 42;
private $wp_http;
private $auth;
private $endpoints;
/**
* @var ClonedSitesHandler
*/
private $clonedSitesHandler;
/**
* @var FingerprintGenerator
*/
private $fingerprintGenerator;
/**
* WPML_TM_ATE_API constructor.
*
* @param WP_Http $wp_http
* @param WPML_TM_ATE_Authentication $auth
* @param WPML_TM_ATE_AMS_Endpoints $endpoints
* @param ClonedSitesHandler $clonedSitesHandler
* @param FingerprintGenerator $fingerprintGenerator
*/
public function __construct(
WP_Http $wp_http,
WPML_TM_ATE_Authentication $auth,
WPML_TM_ATE_AMS_Endpoints $endpoints,
ClonedSitesHandler $clonedSitesHandler,
FingerprintGenerator $fingerprintGenerator
) {
$this->wp_http = $wp_http;
$this->auth = $auth;
$this->endpoints = $endpoints;
$this->clonedSitesHandler = $clonedSitesHandler;
$this->fingerprintGenerator = $fingerprintGenerator;
}
/**
* On success, it returns the map: wpmlJobId => ateJobId inside the 'jobs' key.
*
* @param array $params
* @see https://bitbucket.org/emartini_crossover/ate/wiki/API/V1/jobs/create
*
* @return array{
* code: int,
* status: string,
* message: string,
* jobs: array{
* int: int
* }
* } | WP_Error
*
* @throws \InvalidArgumentException
*/
public function create_jobs( array $params ) {
return $this->requestWithLog(
$this->endpoints->get_ate_jobs(),
[
'method' => 'POST',
'body' => $params,
]
);
}
/**
* @param int|string|array $ate_job_id
*
* @return array|WP_Error
* @throws \InvalidArgumentException
*/
public function confirm_received_job( $ate_job_id ) {
return $this->requestWithLog( $this->endpoints->get_ate_confirm_job( $ate_job_id ) );
}
/**
* @param array|int $jobIds
* @param bool $onlyFailed
*
* @return array|mixed|object|string|\WP_Error|null
*/
public function cancelJobs( $jobIds, $onlyFailed = false ) {
return $this->requestWithLog(
$this->endpoints->getAteCancelJobs(),
[
'method' => 'POST',
'body' => [
'id' => (array) $jobIds,
'only_failed' => $onlyFailed
]
]
);
}
/**
* @param array|int $jobIds
* @param bool $force
*
* @return array|mixed|object|string|\WP_Error|null
*/
public function hideJobs( $jobIds, $force = false ) {
return $this->requestWithLog(
$this->endpoints->getAteHideJobs(),
[
'method' => 'POST',
'body' => [
'id' => (array) $jobIds,
'force' => $force
]
]
);
}
/**
* @param int $job_id
* @param string $return_url
*
* @return string|WP_Error
* @throws \InvalidArgumentException
*/
public function get_editor_url( $job_id, $return_url ) {
$lock = $this->clonedSitesHandler->checkCloneSiteLock();
if ( $lock ) {
return new WP_Error( 'communication_error', 'ATE communication is locked, please update configuration' );
}
$translator_email = filter_var( wp_get_current_user()->user_email, FILTER_SANITIZE_URL );
$return_url = filter_var( $return_url, FILTER_SANITIZE_URL );
$url = $this->endpoints->get_ate_editor();
$url = str_replace(
[
'{job_id}',
'{translator_email}',
'{return_url}',
],
[
$job_id,
$translator_email ? urlencode( $translator_email ) : '',
$return_url ? urlencode( $return_url ) : '',
],
$url
);
return $this->auth->get_signed_url_with_parameters( 'GET', $url, null );
}
/**
* @param int $ate_job_id
* @param WPML_Element_Translation_Job $job_object
* @param int|null $sentFrom
*
* @return array
*/
public function clone_job( $ate_job_id, WPML_Element_Translation_Job $job_object, $sentFrom = null ) {
$url = $this->endpoints->get_clone_job( $ate_job_id );
$params = [
'id' => $ate_job_id,
'notify_url' =>
\WPML\TM\ATE\REST\PublicReceive::get_receive_ate_job_url( $job_object->get_id() ),
'site_identifier' => wpml_get_site_id( WPML_TM_ATE::SITE_ID_SCOPE ),
'source_id' => wpml_tm_get_records()
->icl_translate_job_by_job_id( $job_object->get_id() )
->rid(),
'permalink' => $job_object->get_url( true ),
'ate_ams_console_url' => wpml_tm_get_ams_ate_console_url(),
];
if ( $sentFrom ) {
$params['job_type'] = $sentFrom;
}
$result = $this->requestWithLog( $url, [ 'method' => 'POST', 'body' => $params ] );
if ( ! is_object( $result ) || ! property_exists( $result, 'job_id' ) ) {
return false;
}
return [
'id' => $result->job_id,
'ate_status' => Obj::propOr( WPML_TM_ATE_AMS_Endpoints::ATE_JOB_STATUS_CREATED, 'status', $result ),
];
}
/**
* @param int $ate_job_id
*
* @return array|WP_Error
* @throws \InvalidArgumentException
*/
public function get_job( $ate_job_id ) {
if ( ! $ate_job_id ) {
return null;
}
return $this->requestWithLog( $this->endpoints->get_ate_jobs( $ate_job_id ) );
}
/**
* If `$job_ids` is not an empty array,
* the `$statuses` parameter will be ignored in ATE's endpoint.
*
* @see https://bitbucket.org/emartini_crossover/ate/wiki/API/V1/jobs/status
*
* @param null|array $job_ids
* @param null|array $statuses
*
* @return array|mixed|null|object|WP_Error
* @throws \InvalidArgumentException
*/
public function get_jobs( $job_ids, $statuses = null ) {
return $this->requestWithLog( $this->endpoints->get_ate_jobs( $job_ids, $statuses ) );
}
public function get_job_status_with_priority( $job_id ) {
return $this->requestWithLog(
$this->endpoints->get_ate_job_status(),
[
'method' => 'POST',
'body' => [ 'id' => $job_id,
'preview' => true],
]
);
}
/**
* @param $wpml_job_ids
*
* @return array|mixed|object|WP_Error|null
*/
public function get_jobs_by_wpml_ids( $wpml_job_ids ) {
return $this->requestWithLog( $this->endpoints->get_ate_jobs_by_wpml_job_ids( $wpml_job_ids ) );
}
/**
* @param array $pairs
* @see https://bitbucket.org/emartini_crossover/ate/wiki/API/V1/migration/migrate
* @return bool
*/
public function migrate_source_id( array $pairs ) {
$lock = $this->clonedSitesHandler->checkCloneSiteLock();
if ( $lock ) {
return false;
}
$verb = 'POST';
$url = $this->auth->get_signed_url_with_parameters( $verb, $this->endpoints->get_source_id_migration(), $pairs );
if ( is_wp_error( $url ) ) {
return $url;
}
$body = wp_json_encode( $pairs, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
$result = $this->wp_http->request(
$url,
array(
'timeout' => 60,
'method' => $verb,
'headers' => $this->json_headers(),
'body' => $body ?: '',
)
);
if ( ! is_wp_error( $result ) ) {
$result = $this->clonedSitesHandler->handleClonedSiteError( $result );
}
return $this->get_response_errors( $result ) === null;
}
/**
* @param LanguageMapping[] $languagesToMap
*
* @return Either
*/
public function create_language_mapping( array $languagesToMap ) {
$result = $this->requestWithLog(
$this->endpoints->getLanguages(),
[
'method' => 'POST',
'body' => [
'mappings' => Fns::map( invoke( 'toATEFormat' ), Obj::values( $languagesToMap ) )
]
]
);
// it has an error when there is at least one record which has falsy "result" => "created" field
$hasError = Lst::find( Logic::complement( Obj::path( [ 'result', 'created' ] ) ) );
$logError = Fns::tap( function ( $data ) {
$entry = new Entry();
$entry->eventType = EventsTypes::SERVER_ATE;
$entry->description = __( 'Saving of Language mapping to ATE failed', 'wpml-translation-management' );
$entry->extraData = $data;
wpml_tm_ate_ams_log( $entry );
} );
return WordPress::handleError( $result )
->map( Obj::prop( 'mappings' ) )
->chain( Logic::ifElse( $hasError, pipe( $logError, Either::left() ), Either::right() ) );
}
/**
* @param $mappingIds
*
* @return false|array
*/
public function remove_language_mapping( $mappingIds ) {
$result = $this->requestWithLog(
$this->endpoints->getDeleteLanguagesMapping(),
[ 'method' => 'POST', 'body' => [ 'mappings' => $mappingIds ] ]
);
return is_wp_error( $result ) ? false : $result;
}
/**
* @param string[] $languageCodes
* @param null|string $sourceLanguage
*
* @return Maybe
*/
public function get_languages_supported_by_automatic_translations( $languageCodes, $sourceLanguage = null ) {
$sourceLanguage = $sourceLanguage ?: Languages::getDefaultCode();
$result = $this->requestWithLog(
$this->endpoints->getLanguagesCheckPairs(),
[
'method' => 'POST',
'body' => [
[
'source_language' => $sourceLanguage,
'target_languages' => $languageCodes,
]
]
]
);
return Maybe::of( $result )
->reject( 'is_wp_error' )
->map( Obj::prop( 'results' ) )
->map( Lst::find( Relation::propEq( 'source_language', $sourceLanguage ) ) )
->map( Obj::prop( 'target_languages' ) );
}
/**
* It returns language details from ATE including the info about translation engine supporting this language.
*
* If $inTheWebsiteContext is true, then we are taking into consideration user's translation engine settings.
* It means that generally language may be supported e.g. by google, but when he turns off this engine, it will be reflected in the response.
*
* @param string $languageCode
* @param bool $inTheWebsiteContext
*
* @return Maybe
*/
public function get_language_details( $languageCode, $inTheWebsiteContext = true ) {
$result = $this->requestWithLog( sprintf( $this->endpoints->getShowLanguage(), $languageCode ), [ 'method' => 'GET' ] );
return Maybe::of( $result )
->reject( 'is_wp_error' )
->map( Obj::prop( $inTheWebsiteContext ? 'website_language' : 'language' ) );
}
/**
* @return array
*/
public function get_available_languages() {
$result = $this->requestWithLog( $this->endpoints->getLanguages(), [ 'method' => 'GET' ] );
return is_wp_error( $result ) ? [] : $result;
}
/**
* @return Maybe
*/
public function get_language_mapping() {
$result = $this->requestWithLog( $this->endpoints->getLanguagesMapping(), [ 'method' => 'GET' ] );
return Maybe::of( $result )->reject( 'is_wp_error' );
}
public function start_translation_memory_migration() {
$result = $this->requestWithLog(
$this->endpoints->startTranlsationMemoryIclMigration(),
[
'method' => 'POST',
'body' => [
'site_identifier' => $this->get_website_id( site_url() ),
'ts_id' => 10,
// random numbers for now, we should check what needs to be done for the final version.
'ts_access_key' => 20,
],
]
);
return WordPress::handleError( $result );
}
public function check_translation_memory_migration() {
$result = $this->requestWithLog(
$this->endpoints->checkStatusTranlsationMemoryIclMigration(),
[
'method' => 'GET',
'body' => [
'site_identifier' => $this->get_website_id( site_url() ),
'ts_id' => 10,
// random numbers for now, we should check what needs to be done for the final version.
'ts_access_key' => 20,
],
]
);
return WordPress::handleError( $result );
}
/**
* @see https://ate.pages.onthegosystems.com/ate-docs/ATE/API/V1/icl/translators/import
*
* @param $iclToken
* @param $iclServiceId
*
* @return callable|Either
*/
public function import_icl_translators( $tsId, $tsAccessKey ) {
$params = [
'site_identifier' => $this->auth->get_site_id(),
'ts_id' => $tsId,
'ts_access_key' => $tsAccessKey
];
$result = $this->requestWithLog( $this->endpoints->importIclTranslators(),
[
'method' => 'POST',
'body' => $params
] );
return WordPress::handleError( $result );
}
private function get_response( $result ) {
$errors = $this->get_response_errors( $result );
if ( is_wp_error( $errors ) ) {
return $errors;
}
return $this->get_response_body( $result );
}
private function get_response_body( $result ) {
if ( is_array( $result ) && array_key_exists( 'body', $result ) ) {
$body = json_decode( $result['body'] );
if ( isset( $body->authenticated ) && ! (bool) $body->authenticated ) {
return new WP_Error(
'ate_auth_failed',
isset( $body->message ) ? $body->message : ''
);
}
return $body;
}
return $result;
}
private function get_response_errors( $response ) {
if ( is_wp_error( $response ) ) {
return $response;
}
$response_errors = null;
$response = (array) $response;
if ( array_key_exists( 'body', $response ) && $response['response']['code'] >= 400 ) {
$errors = array();
$response_body = json_decode( $response['body'], true );
if ( is_array( $response_body ) && array_key_exists( 'errors', $response_body ) ) {
$errors = $response_body['errors'];
}
$response_errors = new WP_Error( $response['response']['code'], $response['response']['message'], $errors );
}
return $response_errors;
}
/**
* @return array
*/
private function json_headers() {
return [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
FingerprintGenerator::SITE_FINGERPRINT_HEADER => $this->fingerprintGenerator->getSiteFingerprint(),
];
}
/**
* @param array $args
*
* @return string
*/
private function encode_body_args( array $args ) {
return wp_json_encode( $args, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
}
/**
* @param string $xliff_url
* @param array|\stdClass|false|null $job
*
* @return string
* @throws RequestException The request to ATE failed.
*/
public function get_remote_xliff_content( $xliff_url, $job = null ) {
$entry = $this->prepare_xliff_log_entry( $xliff_url, $job );
wpml_tm_ate_ams_log( $entry, true );
/** @var \WP_Error|array $response */
$response = $this->wp_http->get( $xliff_url, array(
'timeout' => min( 30, ini_get( 'max_execution_time' ) ?: 10 )
) );
wpml_tm_ate_ams_log_remove( $entry );
if ( is_wp_error( $response ) ) {
throw new RequestException(
$response->get_error_message(),
$response->get_error_code()
);
}
return $response['body'];
}
public function override_site_id( $site_id ) {
$this->auth->override_site_id( $site_id );
}
public function get_website_id( $site_url ) {
$lock = $this->clonedSitesHandler->checkCloneSiteLock();
if ( $lock ) {
return null;
}
$signed_url = $this->auth->get_signed_url_with_parameters( 'GET', $this->endpoints->get_websites() );
if ( is_wp_error( $signed_url ) ) {
return null;
}
$requestArguments = [ 'headers' => $this->json_headers() ];
$response = $this->wp_http->request( $signed_url, $requestArguments );
if ( ! is_wp_error( $response ) ) {
$response = $this->clonedSitesHandler->handleClonedSiteError( $response );
}
$sites = $this->get_response( $response );
foreach ( $sites as $site ) {
if ( $site->url === $site_url ) {
return $site->uuid;
}
}
return null;
}
/**
* @see https://bitbucket.org/emartini_crossover/ate/wiki/API/V1/sync/all
*
* @param array $ateJobIds
*
* @return array|mixed|null|object|WP_Error
* @throws \InvalidArgumentException
*/
public function sync_all( array $ateJobIds ) {
return $this->requestWithLog(
$this->endpoints->get_sync_all(),
[
'method' => 'POST',
'body' => [ 'ids' => $ateJobIds ],
]
);
}
/**
* @see https://bitbucket.org/emartini_crossover/ate/wiki/API/V1/sync/page
*
* @param string $token
* @param int $page
*
* @return array|mixed|null|object|WP_Error
* @throws \InvalidArgumentException
*/
public function sync_page( $token, $page ) {
return $this->requestWithLog( $this->endpoints->get_sync_page( $token, $page ) );
}
/**
* @param string $url
* @param array $requestArgs
*
* @return array|mixed|object|string|WP_Error|null
*/
private function request( $url, array $requestArgs = [] ) {
$lock = $this->clonedSitesHandler->checkCloneSiteLock( $url );
if ( $lock ) {
return $lock;
}
$requestArgs = array_merge(
[
'timeout' => 60,
'method' => 'GET',
'headers' => $this->json_headers(),
],
$requestArgs
);
$bodyArgs = isset( $requestArgs['body'] ) && is_array( $requestArgs['body'] )
? $requestArgs['body'] : null;
$signedUrl = $this->auth->get_signed_url_with_parameters( $requestArgs['method'], $url, $bodyArgs );
if ( is_wp_error( $signedUrl ) ) {
return $signedUrl;
}
if ( $bodyArgs ) {
$requestArgs['body'] = $this->encode_body_args( $bodyArgs );
}
$result = $this->wp_http->request( $signedUrl, $requestArgs );
if ( ! is_wp_error( $result ) ) {
$result = $this->clonedSitesHandler->handleClonedSiteError( $result );
}
return $this->get_response( $result );
}
/**
* @param string $url
* @param array $requestArgs
*
* @return array|int|float|object|string|WP_Error|null
*/
private function requestWithLog( $url, array $requestArgs = [] ) {
$response = $this->request( $url, $requestArgs );
if ( is_wp_error( $response ) ) {
$entry = new Entry();
$entry->eventType = EventsTypes::SERVER_ATE;
$entry->description = $response->get_error_message();
$errorCode = $response->get_error_code();
$entry->extraData = [
'url' => $url,
'requestArgs' => $requestArgs,
];
if ( $errorCode ) {
$entry->extraData['status'] = $errorCode;
}
if ( $response->get_error_data( $errorCode ) ) {
$entry->extraData['details'] = $response->get_error_data( $errorCode );
}
wpml_tm_ate_ams_log( $entry );
ATEDetailedErrorMessage::saveDetailedError( $response );
}
return $response;
}
/**
* @param string $xliff_url
* @param array|\stdClass|false|null $job
*
* @return Entry
*/
private function prepare_xliff_log_entry( $xliff_url, $job ) {
$entry = new WPML\TM\ATE\Log\Entry();
if ( $job ) {
$entry->ateJobId = Obj::prop('ateJobId', $job);
$entry->wpmlJobId = Obj::prop('jobId', $job);
}
$entry->eventType = WPML\TM\ATE\Log\EventsTypes::SERVER_ATE;
$entry->description = 'Started attempt to download xliff file. The process did not finish.';
$entry->extraData = [ 'xliff_url' => $xliff_url ];
return $entry;
}
}