xref: /plugin/deeplautotranslate/action.php (revision e4700ea0fd9ca0909925e0405ccc5a4355b76a89)
1<?php
2/**
3 * Deepl Autotranslate Plugin
4 *
5 * @author     Jennifer Graul <me@netali.de>
6 */
7
8if(!defined('DOKU_INC')) die();
9
10use \dokuwiki\HTTP\DokuHTTPClient;
11
12class action_plugin_deeplautotranslate extends DokuWiki_Action_Plugin {
13
14    // manual mapping of ISO-languages to DeepL-languages to fix inconsistent naming
15    private $langs = [
16        'bg' => 'BG',
17        'cs' => 'CS',
18        'da' => 'DA',
19        'de' => 'DE',
20        'de-informal' => 'DE',
21        'el' => 'EL',
22        'en' => 'EN-GB',
23        'es' => 'ES',
24        'et' => 'ET',
25        'fi' => 'FI',
26        'fr' => 'FR',
27        'hu' => 'HU',
28        'hu-formal' => 'HU',
29        'it' => 'IT',
30        'ja' => 'JA',
31        'lt' => 'LT',
32        'lv' => 'LV',
33        'nl' => 'NL',
34        'pl' => 'PL',
35        'pt' => 'PT-PT',
36        'ro' => 'RO',
37        'ru' => 'RU',
38        'sk' => 'SK',
39        'sl' => 'SL',
40        'sv' => 'SV',
41        'zh' => 'ZH'
42    ];
43
44    /**
45     * Register its handlers with the DokuWiki's event controller
46     */
47    public function register(Doku_Event_Handler $controller) {
48        $controller->register_hook('ACTION_ACT_PREPROCESS','BEFORE', $this, 'autotrans_direct');
49        $controller->register_hook('COMMON_PAGETPL_LOAD','AFTER', $this, 'autotrans_editor');
50    }
51
52    public function autotrans_direct(Doku_Event $event, $param) {
53        if ($this->get_mode() != 'direct') return;
54        if ($event->data != 'show') return;
55
56        if (!$this->check_do_translation()) return;
57
58        global $ID;
59        global $INFO;
60
61        $org_page_text = $this->get_org_page_text();
62        $translated_text = $this->deepl_translate($org_page_text, $this->langs[$this->get_target_lang()]);
63
64        if ($translated_text === '') return;
65
66        saveWikiText($ID, $translated_text, 'Automatic translation');
67
68        $INFO = pageinfo();
69    }
70
71    public function autotrans_editor(Doku_Event $event, $param) {
72        if ($this->get_mode() != 'editor') return;
73
74        if (!$this->check_do_translation()) return;
75
76        $org_page_text = $this->get_org_page_text();
77
78        $event->data['tpl'] = $this->deepl_translate($org_page_text, $this->langs[$this->get_target_lang()]);
79    }
80
81    private function get_mode(): string {
82        global $ID;
83        if ($this->getConf('editor_regex')) {
84            if (preg_match('/' . $this->getConf('editor_regex') . '/', $ID) === 1) return 'editor';
85        }
86        if ($this->getConf('direct_regex')) {
87            if (preg_match('/' . $this->getConf('direct_regex') . '/', $ID) === 1) return 'direct';
88        }
89        return $this->getConf('mode');
90    }
91
92    private function get_target_lang(): string {
93        global $ID;
94        $split_id = explode(':', $ID);
95        return array_shift($split_id);
96    }
97
98    private function get_org_page_text(): string {
99        global $ID;
100
101        $split_id = explode(':', $ID);
102        array_shift($split_id);
103        $org_id = implode(':', $split_id);
104
105        return rawWiki($org_id);
106    }
107
108    private function check_do_translation(): bool {
109        global $INFO;
110        // only translate if the current page does not exist
111        if ($INFO['exists']) return false;
112
113        global $ID;
114
115        // skip blacklisted namespaces and pages
116        if ($this->getConf('blacklist_regex')) {
117            if (preg_match('/' . $this->getConf('blacklist_regex') . '/', $ID) === 1) return false;
118        }
119
120        $split_id = explode(':', $ID);
121        $lang_ns = array_shift($split_id);
122        // only translate if the current page is in a language namespace
123        if (!array_key_exists($lang_ns, $this->langs)) return false;
124
125        $org_id = implode(':', $split_id);
126        // check if the original page exists
127        if (!page_exists($org_id)) return false;
128
129        return true;
130    }
131
132    private function deepl_translate($text, $target_lang): string {
133        if (!$this->getConf('api_key')) return '';
134
135        $text = $this->insert_ignore_tags($text);
136
137        $data = [
138            'auth_key' => $this->getConf('api_key'),
139            'target_lang' => $target_lang,
140            'tag_handling' => 'xml',
141            'ignore_tags' => 'ignore,code,file,php',
142            'text' => $text
143        ];
144
145        if ($this->getConf('api') == 'free') {
146            $url = 'https://api-free.deepl.com/v2/translate';
147        } else {
148            $url = 'https://api.deepl.com/v2/translate';
149        }
150
151        $http = new DokuHTTPClient();
152        $raw_response = $http->post($url, $data);
153
154        // if any error occurred return an empty string
155        if ($http->status >= 400) return '';
156
157        $json_response = json_decode($raw_response, true);
158        $translated_text = $json_response['translations'][0]['text'];
159
160        $translated_text = $this->remove_ignore_tags($translated_text);
161
162        return $translated_text;
163    }
164
165    private function insert_ignore_tags($text): string {
166        $text = str_replace('[[', '<ignore>[[', $text);
167        $text = str_replace('{{', '<ignore>{{', $text);
168        $text = str_replace(']]', ']]</ignore>', $text);
169        $text = str_replace('}}', '}}</ignore>', $text);
170
171        $ignored_expressions = explode(':', $this->getConf('ignored_expressions'));
172
173        foreach ($ignored_expressions as $expression) {
174            $text = str_replace($expression, '<ignore>' . $expression . '</ignore>', $text);
175        }
176
177        return $text;
178    }
179
180    private function remove_ignore_tags($text): string {
181        $text = str_replace('<ignore>[[', '[[', $text);
182        $text = str_replace('<ignore>{{', '{{', $text);
183        $text = str_replace(']]</ignore>', ']]', $text);
184        $text = str_replace('}}</ignore>', '}}', $text);
185
186        $ignored_expressions = explode(':', $this->getConf('ignored_expressions'));
187
188        foreach ($ignored_expressions as $expression) {
189            $text = str_replace('<ignore>' . $expression . '</ignore>', $expression, $text);
190        }
191
192        return $text;
193    }
194}
195
196