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
|
<?php
/**
* Contains a class for querying external translation service.
*
* @file
* @author Niklas Laxström
* @license GPL-2.0+
*/
/**
* Implements support for Microsoft translation api v2.
* @see http://msdn.microsoft.com/en-us/library/ff512421.aspx
* @ingroup TranslationWebService
* @since 2013-01-01
*/
class MicrosoftWebService extends TranslationWebService {
public function getType() {
return 'mt';
}
protected function mapCode( $code ) {
$map = array(
'zh-hant' => 'zh-CHT',
'zh-hans' => 'zh-CHS',
);
return isset( $map[$code] ) ? $map[$code] : $code;
}
protected function doPairs() {
if ( !isset( $this->config['key'] ) ) {
throw new TranslationWebServiceException( 'API key is not set' );
}
$options = array();
$options['method'] = 'GET';
$options['timeout'] = $this->config['timeout'];
$params = array(
'appId' => $this->config['key'],
);
$url = 'http://api.microsofttranslator.com/V2/Http.svc/GetLanguagesForTranslate?';
$url .= wfArrayToCgi( $params );
$req = MWHttpRequest::factory( $url, $options );
$status = $req->execute();
if ( !$status->isOK() ) {
$error = $req->getContent();
// Most likely a timeout or other general error
$exception = 'Http request failed:' . serialize( $error ) . serialize( $status );
throw new TranslationWebServiceException( $exception );
}
$xml = simplexml_load_string( $req->getContent() );
$languages = array();
foreach ( $xml->string as $language ) {
$languages[] = (string)$language;
}
// Let's make a cartesian product, assuming we can translate from any
// language to any language
$pairs = array();
foreach ( $languages as $from ) {
foreach ( $languages as $to ) {
$pairs[$from][$to] = true;
}
}
return $pairs;
}
protected function getQuery( $text, $from, $to ) {
if ( !isset( $this->config['key'] ) ) {
throw new TranslationWebServiceException( 'API key is not set' );
}
$text = trim( $text );
$text = $this->wrapUntranslatable( $text );
$params = array(
'text' => $text,
'from' => $from,
'to' => $to,
'appId' => $this->config['key'],
);
return TranslationQuery::factory( $this->config['url'] )
->timeout( $this->config['timeout'] )
->queryParamaters( $params );
}
protected function parseResponse( TranslationQueryResponse $reply ) {
$body = $reply->getBody();
$text = preg_replace( '~<string.*>(.*)</string>~', '\\1', $body );
$text = Sanitizer::decodeCharReferences( $text );
$text = $this->unwrapUntranslatable( $text );
return $text;
}
}
|