summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/Translate/webservices/YandexWebService.php
blob: fbb16844edb1ce8a87e6ab00045a3859c1ca8a0c (plain)
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
<?php
/**
 * Contains a class for querying external translation service.
 *
 * @file
 * @author Niklas Laxström
 * @license GPL-2.0-or-later
 */

/**
 * Implements support for Yandex translation api v1.
 * @see https://tech.yandex.com/translate/
 * @ingroup TranslationWebService
 * @since 2013-01-01
 */
class YandexWebService extends TranslationWebService {
	public function getType() {
		return 'mt';
	}

	protected function mapCode( $code ) {
		if ( $code === 'be-tarask' ) {
			$code = 'be';
		}
		return $code;
	}

	protected function doPairs() {
		if ( !isset( $this->config['key'] ) ) {
			throw new TranslationWebServiceConfigurationException( 'API key is not set' );
		}

		$pairs = [];

		$params = [
			'key' => $this->config['key'],
		];

		$url = $this->config['pairs'] . '?' . wfArrayToCgi( $params );
		$json = Http::get(
			$url,
			[ 'timeout' => $this->config['timeout'] ],
			__METHOD__
		);
		$response = FormatJson::decode( $json );

		if ( !is_object( $response ) ) {
			$exception = 'Malformed reply from remote server: ' . (string)$json;
			throw new TranslationWebServiceException( $exception );
		}

		foreach ( $response->dirs as $pair ) {
			list( $source, $target ) = explode( '-', $pair );
			$pairs[$source][$target] = true;
		}

		return $pairs;
	}

	protected function getQuery( $text, $from, $to ) {
		if ( !isset( $this->config['key'] ) ) {
			throw new TranslationWebServiceConfigurationException( 'API key is not set' );
		}

		# https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/
		if ( strlen( $text ) > 10000 ) {
			throw new TranslationWebServiceInvalidInputException( 'Source text too long' );
		}

		$text = trim( $text );
		$text = $this->wrapUntranslatable( $text );

		return TranslationQuery::factory( $this->config['url'] )
			->timeout( $this->config['timeout'] )
			->postWithData(
				[
					'key' => $this->config['key'],
					'text' => $text,
					'lang' => "$from-$to",
					'format' => 'html',
				]
			);
	}

	protected function parseResponse( TranslationQueryResponse $reply ) {
		$body = $reply->getBody();
		$response = FormatJson::decode( $body );
		if ( !is_object( $response ) ) {
			throw new TranslationWebServiceException( 'Invalid json: ' . serialize( $body ) );
		} elseif ( $response->code !== 200 ) {
			throw new TranslationWebServiceException( $response->message );
		}

		$text = Sanitizer::decodeCharReferences( $response->text[0] );
		$text = $this->unwrapUntranslatable( $text );

		return trim( $text );
	}
}