xref: /plugin/deeplautotranslate/action.php (revision 153e4498b45bfe48a498e0f2a99be06d730d26d4)
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;
11use \dokuwiki\plugin\deeplautotranslate\MenuItem;
12
13class action_plugin_deeplautotranslate extends DokuWiki_Action_Plugin {
14
15    // manual mapping of ISO-languages to DeepL-languages to fix inconsistent naming
16    private $langs = [
17        'bg' => 'BG',
18        'cs' => 'CS',
19        'da' => 'DA',
20        'de' => 'DE',
21        'de-informal' => 'DE',
22        'el' => 'EL',
23        'en' => 'EN-GB',
24        'es' => 'ES',
25        'et' => 'ET',
26        'fi' => 'FI',
27        'fr' => 'FR',
28        'hu' => 'HU',
29        'hu-formal' => 'HU',
30        'it' => 'IT',
31        'ja' => 'JA',
32        'lt' => 'LT',
33        'lv' => 'LV',
34        'nl' => 'NL',
35        'pl' => 'PL',
36        'pt' => 'PT-PT',
37        'ro' => 'RO',
38        'ru' => 'RU',
39        'sk' => 'SK',
40        'sl' => 'SL',
41        'sv' => 'SV',
42        'zh' => 'ZH'
43    ];
44
45    /**
46     * Register its handlers with the DokuWiki's event controller
47     */
48    public function register(Doku_Event_Handler $controller) {
49        $controller->register_hook('ACTION_ACT_PREPROCESS','BEFORE', $this, 'preprocess');
50        $controller->register_hook('COMMON_PAGETPL_LOAD','AFTER', $this, 'autotrans_editor');
51        $controller->register_hook('MENU_ITEMS_ASSEMBLY', 'AFTER', $this, 'add_menu_button');
52    }
53
54    public function add_menu_button(Doku_Event $event) {
55        global $ID;
56
57        if ($event->data['view'] != 'page') return;
58
59        if (!$this->getConf('show_button')) return;
60
61        $split_id = explode(':', $ID);
62        $lang_ns = array_shift($split_id);
63        // check if we are in a language namespace
64        if (array_key_exists($lang_ns, $this->langs)) {
65            // in language namespace --> check if we should translate
66            if (!$this->check_do_translation(true)) return;
67        } else {
68            // not in language namespace --> check if we should show the push translate button
69            if (!$this->check_do_push_translate()) return;
70        }
71
72        array_splice($event->data['items'], -1, 0, [new MenuItem()]);
73    }
74
75    public function preprocess(Doku_Event  $event, $param): void {
76        global $ID;
77
78        // check if action is show or translate
79        if ($event->data != 'show' and $event->data != 'translate') return;
80
81        $split_id = explode(':', $ID);
82        $lang_ns = array_shift($split_id);
83        // check if we are in a language namespace
84        if (array_key_exists($lang_ns, $this->langs)) {
85            // in language namespace --> autotrans_direct
86            $this->autotrans_direct($event);
87        } else {
88            // not in language namespace --> push translate
89            $this->push_translate($event);
90        }
91    }
92
93    private function autotrans_direct(Doku_Event $event): void {
94        global $ID;
95
96        // abort if action is translate and the translate button is disabled
97        if ($event->data == 'translate' and !$this->getConf('show_button')) return;
98
99        // do nothing on show action when mode is not direct
100        if ($event->data == 'show' and $this->get_mode() != 'direct') return;
101
102        // allow translation of existing pages is we are in the translate action
103        $allow_existing = ($event->data == 'translate');
104
105        // reset action to show
106        $event->data = 'show';
107
108        if (!$this->check_do_translation($allow_existing)) {
109            send_redirect(wl($ID));
110            return;
111        }
112
113        $org_page_text = $this->get_org_page_text();
114        $translated_text = $this->deepl_translate($org_page_text, $this->langs[$this->get_target_lang()]);
115
116        if ($translated_text === '') {
117            send_redirect(wl($ID));
118            return;
119        }
120
121        saveWikiText($ID, $translated_text, 'Automatic translation');
122
123        msg($this->getLang('msg_translation_success'), 1);
124
125        // reload the page after translation
126        send_redirect(wl($ID));
127    }
128
129    public function autotrans_editor(Doku_Event $event, $param): void {
130        if ($this->get_mode() != 'editor') return;
131
132        if (!$this->check_do_translation()) return;
133
134        $org_page_text = $this->get_org_page_text();
135
136        $event->data['tpl'] = $this->deepl_translate($org_page_text, $this->langs[$this->get_target_lang()]);
137    }
138
139    private function push_translate(Doku_Event $event): void {
140        global $ID;
141
142        // check if action is translate
143        if ($event->data != 'translate') return;
144
145        // check if button is enabled
146        if (!$this->getConf('show_button')) {
147            send_redirect(wl($ID));
148            return;
149        }
150
151        if (!$this->check_do_push_translate()) {
152            send_redirect(wl($ID));
153            return;
154        }
155
156        // push translate
157        $push_langs = $this->get_push_langs();
158        $org_page_text = rawWiki($ID);
159        foreach ($push_langs as $lang) {
160            // skip invalid languages
161            if (!array_key_exists($lang, $this->langs)) {
162                msg($this->getLang('msg_translation_fail_invalid_lang') . $lang, -1);
163                continue;
164            }
165
166            $lang_id = $lang . ':' . $ID;
167
168            // check permissions
169            $perm = auth_quickaclcheck($ID);
170            $exists = page_exists($lang_id);
171            if (($exists and $perm < AUTH_EDIT) or (!$exists and $perm < AUTH_CREATE)) {
172                msg($this->getLang('msg_translation_fail_no_permissions') . $lang_id, -1);
173                continue;
174            }
175
176            $translated_text = $this->deepl_translate($org_page_text, $this->langs[$lang]);
177            saveWikiText($lang_id, $translated_text, 'Automatic push translation');
178        }
179
180        msg($this->getLang('msg_translation_success'), 1);
181
182        // reload the page after translation to clear the action
183        send_redirect(wl($ID));
184    }
185
186    private function get_mode(): string {
187        global $ID;
188        if ($this->getConf('editor_regex')) {
189            if (preg_match('/' . $this->getConf('editor_regex') . '/', $ID) === 1) return 'editor';
190        }
191        if ($this->getConf('direct_regex')) {
192            if (preg_match('/' . $this->getConf('direct_regex') . '/', $ID) === 1) return 'direct';
193        }
194        return $this->getConf('mode');
195    }
196
197    private function get_target_lang(): string {
198        global $ID;
199        $split_id = explode(':', $ID);
200        return array_shift($split_id);
201    }
202
203    private function get_org_page_text(): string {
204        global $ID;
205
206        $split_id = explode(':', $ID);
207        array_shift($split_id);
208        $org_id = implode(':', $split_id);
209
210        return rawWiki($org_id);
211    }
212
213    private function check_do_translation($allow_existing = false): bool {
214        global $INFO;
215        global $ID;
216
217        // only translate if the current page does not exist
218        if ($INFO['exists'] and !$allow_existing) return false;
219
220        // permission check
221        $perm = auth_quickaclcheck($ID);
222        if (($INFO['exists'] and $perm < AUTH_EDIT) or (!$INFO['exists'] and $perm < AUTH_CREATE)) return false;
223
224        // skip blacklisted namespaces and pages
225        if ($this->getConf('blacklist_regex')) {
226            if (preg_match('/' . $this->getConf('blacklist_regex') . '/', $ID) === 1) return false;
227        }
228
229        $split_id = explode(':', $ID);
230        $lang_ns = array_shift($split_id);
231        // only translate if the current page is in a language namespace
232        if (!array_key_exists($lang_ns, $this->langs)) return false;
233
234        $org_id = implode(':', $split_id);
235        // check if the original page exists
236        if (!page_exists($org_id)) return false;
237
238        return true;
239    }
240
241    private function check_do_push_translate(): bool {
242        global $ID;
243
244        $push_langs = $this->get_push_langs();
245        // push_langs empty --> push_translate disabled --> abort
246        if (empty($push_langs)) return false;
247
248        // skip blacklisted namespaces and pages
249        if ($this->getConf('blacklist_regex')) {
250            // blacklist regex match --> abort
251            if (preg_match('/' . $this->getConf('blacklist_regex') . '/', $ID) === 1) return false;
252        }
253
254        return true;
255    }
256
257    private function deepl_translate($text, $target_lang): string {
258        if (!trim($this->getConf('api_key'))) return '';
259
260        $text = $this->insert_ignore_tags($text);
261
262        $data = [
263            'auth_key' => $this->getConf('api_key'),
264            'target_lang' => $target_lang,
265            'tag_handling' => 'xml',
266            'ignore_tags' => 'ignore,code,file,php',
267            'text' => $text
268        ];
269
270        if ($this->getConf('api') == 'free') {
271            $url = 'https://api-free.deepl.com/v2/translate';
272        } else {
273            $url = 'https://api.deepl.com/v2/translate';
274        }
275
276        $http = new DokuHTTPClient();
277        $raw_response = $http->post($url, $data);
278
279        if ($http->status >= 400) {
280            // add error messages
281            switch ($http->status) {
282                case 403:
283                    msg($this->getLang('msg_translation_fail_bad_key'), -1);
284                    break;
285                case 456:
286                    msg($this->getLang('msg_translation_fail_quota_exceeded'), -1);
287                    break;
288                default:
289                    msg($this->getLang('msg_translation_fail'), -1);
290                    break;
291            }
292
293            // if any error occurred return an empty string
294            return '';
295        }
296
297        $json_response = json_decode($raw_response, true);
298        $translated_text = $json_response['translations'][0]['text'];
299
300        $translated_text = $this->remove_ignore_tags($translated_text);
301
302        return $translated_text;
303    }
304
305    private function get_push_langs(): array {
306        $push_langs = trim($this->getConf('push_langs'));
307
308        if ($push_langs === '') return array();
309
310        return explode(' ', $push_langs);
311    }
312
313    private function insert_ignore_tags($text): string {
314        $text = str_replace('[[', '<ignore>[[', $text);
315        $text = str_replace('{{', '<ignore>{{', $text);
316        $text = str_replace(']]', ']]</ignore>', $text);
317        $text = str_replace('}}', '}}</ignore>', $text);
318        $text = str_replace("''", "<ignore>''</ignore>", $text);
319
320        $ignored_expressions = explode(':', $this->getConf('ignored_expressions'));
321
322        foreach ($ignored_expressions as $expression) {
323            $text = str_replace($expression, '<ignore>' . $expression . '</ignore>', $text);
324        }
325
326        return $text;
327    }
328
329    private function remove_ignore_tags($text): string {
330        $text = str_replace('<ignore>[[', '[[', $text);
331        $text = str_replace('<ignore>{{', '{{', $text);
332        $text = str_replace(']]</ignore>', ']]', $text);
333        $text = str_replace('}}</ignore>', '}}', $text);
334        $text = str_replace("<ignore>''</ignore>", "''", $text);
335
336        // restore < and > for example from arrows (-->) in wikitext
337        $text = str_replace('&gt;', '>', $text);
338        $text = str_replace('&lt;', '<', $text);
339
340        $ignored_expressions = explode(':', $this->getConf('ignored_expressions'));
341
342        foreach ($ignored_expressions as $expression) {
343            $text = str_replace('<ignore>' . $expression . '</ignore>', $expression, $text);
344        }
345
346        return $text;
347    }
348}
349
350