forked from webmin/webmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlanguage-manager
executable file
·1851 lines (1530 loc) · 76.2 KB
/
language-manager
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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl
# language-manager - Automatic translation and/or transcoding language files for all or specific modules
use strict;
use warnings;
use 5.014;
use File::Spec;
use File::Basename;
use File::Find;
use JSON::PP;
use HTTP::Tiny;
use HTML::Entities;
use List::MoreUtils qw(any uniq);
use Cwd qw(cwd);
use Encode qw/encode decode/;
use Encode::Detect::Detector;
use Term::ANSIColor qw(:constants);
use Getopt::Long qw(:config permute pass_through);
use Pod::Usage;
sub main
{
my %data;
# Register start time
$data{'start_time'} = time();
# Prevent accidental script termination
my $sigkill = sub {
if ($data{'sigkill'}++ > 5) {
say RED, "\nTerminating: Ctrl-C has been pressed more than 5 times ..", RESET;
exit;
}
};
$SIG{INT} = \&$sigkill;
# Get user options from the command line
my %opt;
GetOptions('help|h' => \$opt{'help'},
'mode|x:s' => \$opt{'mode'},
'type|w:s' => \$opt{'type'},
'modules|m:s' => \$opt{'modules'},
'modules-exclude|me:s' => \$opt{'modules-exclude'},
'language-target|t:s' => \$opt{'language-target'},
'language-target-exclude|te:s' => \$opt{'language-target-exclude'},
'language-source|s:s' => \$opt{'language-source'},
'language-source-exclude|se:s' => \$opt{'language-source-exclude'},
'language-source-ignore-auto|sia!' => \$opt{'language-source-ignore-auto'},
'language-source-encoding|e:s' => \$opt{'language-source-encoding'},
'only-diff|od!' => \$opt{'only-diff'},
'only-transcode|ot!' => \$opt{'only-transcode'},
'keys-exclude|ke:s' => \$opt{'keys-exclude'},
'keys-force-translate|kft:s' => \$opt{'keys-force-translate'},
'keys-force-html|kfh:s' => \$opt{'keys-force-html'},
'keys-test|kt:s' => \$opt{'keys-test'},
'values-fix|vf:s' => \$opt{'values-fix'},
'values-fix-delimiter|vfd:s' => \$opt{'values-fix-delimiter'},
'translate-format|tf:s' => \$opt{'translate-format'},
'git-commit|gc!' => \$opt{'git-commit'},
'log|l:s' => \$opt{'log'},
'verbose|v:i' => \$opt{'verbose'});
# Print help and exit
pod2usage(0) if ($opt{'help'});
# Enforce verbose output by default
if (!defined($opt{'verbose'})) {
$opt{'verbose'} = 1;
}
# Get current path and make workaround to run from sub dir
my $path = cwd;
if ($path =~ /\/bin$/) {
$path = Cwd::realpath('..');
}
my $type = -d "$path/ulang" ? 'ulang' : 'lang';
# Load Webmin lib
require("$path/web-lib-funcs.pl");
# Enforce user specific target: language directory, config.info or module.info file {lang|ulang|config|uconfig|module}
$opt{'type'} && ($type = $opt{'type'});
# Store path and type
$data{'path'} = $path;
$data{'type'} = $type;
# Set default format to text
$opt{'translate-format'} ||= 'text';
# Force HTML format for "module" type translates
if (defined($opt{'type'}) && $opt{'type'} =~ /module|help/) {
$opt{'translate-format'} = 'html';
}
# Check if we can get Google Translate API token
$data{'token'} = get_google_translate_token();
if (!$data{'token'}) {
$opt{'only-diff'} = 1;
$opt{'only-diff-auto'} = 1;
say YELLOW .
"Translation will not be done as Google Translate API key is missing. Falling back to `only-diff` mode.." . RESET;
}
# Get list of languages from `lang_list.txt` file
$data{'languages_source_list'} = list_languages_local(\%data);
$data{'languages_source_list_codes'} = [map {$_->{'lang'}} @{ $data{'languages_source_list'} }];
# Define base language. Default is set English
$opt{'language-source'} ||= 'en';
my $language_source = $opt{'language-source'};
# Check, if source language exists
if (!any {$_ =~ /^$language_source/} @{ $data{'languages_source_list_codes'} }) {
errors('language-source', $language_source);
exit;
}
# What language encoding do we expect on human translated files
$opt{'language-source-encoding'} ||= 'utf-8';
# Always exclude source language
my $language_target_exclude = $opt{'language-target-exclude'};
if ($language_target_exclude) {
$language_target_exclude .= ",$language_source";
} else {
$language_target_exclude = $language_source;
}
# Don't put on the list user excluded languages
if ($language_target_exclude) {
my @languages_excluded = split(',', $language_target_exclude);
my @languages_allowed;
for my $language (@{ $data{'languages_source_list_codes'} }) {
if (!any {$_ =~ /^$language$/} @languages_excluded) {
push(@languages_allowed, $language);
}
}
if (@languages_allowed) {
$data{'languages_source_list_codes'} = [@languages_allowed];
}
}
# Define the mode
$opt{'mode'} ||= 'sync';
# Find out which modules to update, if exist
my $modules = $opt{'modules'};
my @modules;
my @modules_exclude = $opt{'modules-exclude'} ? split(',', $opt{'modules-exclude'}) : ();
if ($modules) {
my @ml = split(',', $modules);
foreach my $module (@ml) {
my ($exists) = source_data($module, \%data, \%opt);
if ($exists) {
if (!any {$_ =~ /^$module$/} @modules_exclude) {
push(@modules, $module);
}
}
}
@modules = sort @modules;
} else {
my $f;
find(
{
wanted => sub {
$f = $File::Find::name;
my $d = -d $f;
my $l = $f =~ /$type\/$language_source$/;
my $i = $f =~ /$type\.info$/;
my $h = $d && ($f =~ s/$path//r =~ tr/\///) == 2 && $f =~ /$path\/.*\/$type$/;
if (!-l $f && ($l || $i || $h)) {
$f =~ s/^$path\///g;
$f =~ s/\/$type\/$language_source//g;
$f =~ s/\/$type\.info//g;
$f =~ s/\/$language_source//g;
$f =~ s/\/$language_source//g;
$f =~ s/\/$type$//g if ($d);
if (!any {$_ =~ /^$f$/} @modules_exclude) {
push(@modules, $f);
}
}
},
},
$path);
@modules = sort(uniq(@modules));
}
$data{'modules'} = \@modules;
# Define target language(s) or translate all
$opt{'language-target'} = [$opt{'language-target'} ? split(',', $opt{'language-target'}) : ()];
if (@{ $opt{'language-target'} }) {
my @bad_languages;
for my $language (@{ $opt{'language-target'} }) {
push(@bad_languages, $language) if !any {$_ =~ /^$language$/} @{ $data{'languages_source_list_codes'} };
}
if (@bad_languages) {
errors('language-target', join(',', @bad_languages));
exit;
}
}
# Test only given keys in bulk translation. Translated strings are not saved
$opt{'keys-test'} = [$opt{'keys-test'} ? split(',', $opt{'keys-test'}) : ()];
# Exclude listed keys from bulk translation
$opt{'keys-exclude'} = [$opt{'keys-exclude'} ? split(',', $opt{'keys-exclude'}) : ()];
# Forced list of keys that will be re-translated
$opt{'keys-force-translate'} = [$opt{'keys-force-translate'} ? split(',', $opt{'keys-force-translate'}) : ()];
# Forced list of keys to run translations in HTML format
$opt{'keys-force-html'} = [$opt{'keys-force-html'} ? split(',', $opt{'keys-force-html'}) : ()];
# Value fix delimiter. Default is `:`
$opt{'values-fix-delimiter'} ||= ':';
# Build a list of value to check based on source file, and replace with, in all other languages
$opt{'values-fix'} = [$opt{'values-fix'} ? split(',', $opt{'values-fix'}) : ()];
# Just run tests, and exit, without writing anything
if (@{ $opt{'keys-test'} }) {
say CYAN, "Translation testing for selected keys is about to start ..", RESET;
if (prompt('next')) {
go(\%opt, \%data);
}
} else {
# Log the output. Start
$opt{'log'} ||= "/tmp/language-manager-@{[time()]}.log";
open $data{'out'}, ">", "$opt{'log'}" or die RED, "Error creating log: $!\n", RESET, "\n";
# User interactions
talk('affected', \%opt, \%data);
# Run in overwrite mode
if ($opt{'mode'} eq 'full') {
# Execute force transcode/translate
talk('overwrite-pre', \%opt, \%data);
if (prompt('next')) {
go(\%opt, \%data);
}
}
# Simply translate newly added strings to source language (def. en),
# to all targets ".auto". Deleted keys on source language will also
# be removed from targets, in both, human translated and ".auto" files
else {
# Execute language fixer
if (@{ $opt{'values-fix'} }) {
talk('fix-pre', \%opt, \%data);
}
# Execute language fix for double encoded strings
elsif ($opt{'mode'} eq 'transcode') {
talk('transcode-pre', \%opt, \%data);
}
# Execute language sync
else {
talk('sync-pre', \%opt, \%data);
}
if (prompt('next')) {
go(\%opt, \%data);
}
}
# Log the output. End
close $data{'out'};
}
return 0;
}
main();
# The following is used to get correct language files based on old language table.
# This function, should not be really needed, unless compiling languages with
# Webmin version prior to 1.950 (first time), as Webmin 1.950+ is going to
# use new langauge map and have all related language files in UTF-8 already
sub language_map
{
my ($code) = @_;
my %language_map = (
# Use plain language codes
'ja' => 'ja_JP.euc',
'ko' => 'ko_KR.euc',
'ms' => 'ms_MY',
'ru' => 'ru_RU',
'uk' => 'uk_UA',
'zh' => 'zh_CN',
'zh_TW' => 'zh_TW.Big5',
# Czech is `cs` not `cz`, as there is no `cz` at all
'cs' => 'cz',
# Slovenian is `sl` not `si`, as `si` is Sinhala
'sl' => 'si',
# Greek is `el` not `gr`
'el' => 'gr',);
if ($language_map{$code}) {
$code = $language_map{$code};
}
return $code;
}
# Always check, if strings that are about to be translated haven't been
# translated by human already, and if so, extract them with correct
# encoding, to be further converted to UTF-8 and stored on destination file
sub language_source_file
{
my ($opt, $data, %data) = @_;
my $language_code = $data{'language-code'};
my %language_source_file;
my %language_source_file_auto;
my $language_source_file;
my $language_source_file_encoding = 'utf-8';
# Ignore user defined source languages
my $language_source_exclude = $opt->{'language-source-exclude'};
if ($language_source_exclude) {
my @languages_excluded = split(',', $language_source_exclude);
if (any {$_ =~ /^$language_code$/} @languages_excluded) {
return (undef, undef);
}
}
# Correct language code according to the old language map
if ($opt->{'language-source-encoding'} eq 'map') {
$language_code = language_map($language_code);
}
# Set prefix in case of processing `config.info` or `module.info`
my $language_source_file_target_ = "/";
if (defined($opt->{'type'}) && $opt->{'type'} =~ /config|uconfig|module/) {
$language_source_file_target_ = "/$opt->{'type'}.info.";
}
# Get already translated language strings from current directory
my $language_source_file_target = "$data{'module-path'}$language_source_file_target_$language_code";
if (-r $language_source_file_target) {
$language_source_file = $language_source_file_target;
}
# Load machine translated file
if ($opt->{'mode'} ne 'full') {
my $language_source_file_target_auto = "$language_source_file_target.auto";
if (-r $language_source_file_target_auto) {
read_file($language_source_file_target_auto, \%language_source_file_auto);
talk_log(
("" . GREEN .
" .. Found machine translated file for $data{'language-name'} ($language_code.auto)" . RESET . ""
),
$data,
1);
} else {
say YELLOW, " .. No machine translated file has be found for $data{'language-name'} ($language_code.auto)",
RESET;
}
}
# Supply proper encoding for existing language files
if ($language_source_file) {
talk_log(("" . GREEN . " .. Found human translated file for $data{'language-name'} ($language_code)" . RESET . ""),
$data, 1);
read_file("$language_source_file", \%language_source_file);
# Force encoding based on map
if ($opt->{'mode'} eq 'full' && $opt->{'language-source-encoding'} eq 'map') {
my $code = $data{'language-code'};
my $map_auto;
($language_source_file_encoding, $map_auto) = language_file_encoding($code, $language_source_file_target);
talk_log(
("" . CYAN . " .. Force file encoding to \`$language_source_file_encoding\`" .
($map_auto // '') . " as derived from language map" . RESET . ""
),
$data,
1);
}
# Figure out encoding automatically
elsif ($opt->{'mode'} eq 'full' && $opt->{'language-source-encoding'} eq 'auto') {
my $language_source_file_data = read_file_contents($language_source_file_target);
$language_source_file_encoding = Encode::Detect::Detector::detect($language_source_file_data);
if (!$language_source_file_encoding) {
$language_source_file_encoding =
ask(' ' . BRIGHT_RED . '.. Cannot detect encoding, enter it manually' . RESET . '');
talk_log(
("" . BRIGHT_RED .
" .. Manually set file encoding to \`$language_source_file_encoding\`" . RESET . ""),
$data,
1);
} else {
talk_log(
("" . MAGENTA .
" .. Automatically detected file encoding is \`$language_source_file_encoding\`" . RESET . ""
),
$data,
1);
}
} else {
$language_source_file_encoding = $opt->{'language-source-encoding'};
talk_log(("" . MAGENTA . " .. Set file encoding to default \`$language_source_file_encoding\`" . RESET . ""),
$data, 1);
}
} else {
say YELLOW, " .. No human translated file has been found for $data{'language-name'} ($language_code)", RESET;
}
return (\%language_source_file, \%language_source_file_auto, $language_source_file_encoding,
$language_source_file_target);
}
sub language_file_encoding
{
my ($code, $file) = @_;
my $encoding = 'utf-8';
my $auto;
if ($code eq 'ja') {
$encoding = "euc-jp";
} elsif ($code eq 'ko') {
$encoding = "euc-kr";
} elsif ($code eq 'ru' || $code eq 'bg' || $code eq 'uk') {
$encoding = "cp1251";
} elsif ($code eq 'ca' ||
$code eq 'fr' ||
$code eq 'hr' ||
$code eq 'lt' ||
$code eq 'no')
{
$encoding = "cp1252";
} elsif ($code eq 'cs' ||
$code eq 'sk' ||
$code eq 'pl' ||
$code eq 'sl' ||
$code eq 'hu')
{
$encoding = "iso-8859-2";
} elsif ($code eq 'tr') {
$encoding = "iso-8859-9";
} elsif ($code eq 'he') {
$encoding = "cp1255";
} elsif ($code eq 'th') {
$encoding = "tis-620";
} elsif ($code eq 'zh') {
$encoding = "gb2312";
} elsif ($code eq 'zh_TW') {
$encoding = "big5";
} else {
my $file_data = read_file_contents($file);
my $detected = Encode::Detect::Detector::detect($file);
if ($detected) {
$encoding = $detected;
$auto = " (auto)";
} else {
$encoding = 'utf-8';
$auto = " (auto enforced)";
}
}
return ($encoding, $auto);
}
sub language_disallowed
{
my ($code, $opt) = @_;
my $language_target = $opt->{'language-target'};
my $language_target_exclude = $opt->{'language-target-exclude'};
# Process only user defined languages or do all
if (@{$language_target}) {
if (!any {$_ =~ /^$code$/} @{$language_target}) {
return 1;
}
}
# Do not process excluded languages
if ($language_target_exclude) {
my @languages_excluded = split(',', $language_target_exclude);
if (any {$_ =~ /^$code$/} @languages_excluded) {
return 1;
}
}
}
sub language_transcode
{
my ($string, $encoding, $opt) = @_;
# In case it's a `config` or `uconfig` file, preserve
# , and -, as a literal characters
# Warning - it will be removed in the near future, after config parser for translator is created
my $type = $opt->{'type'};
my $type_config = $type =~ /config|uconfig/ if ($type);
my $utf8 = 'utf-8';
if ($type_config) {
$string =~ s/,/~,~,~/g;
$string =~ s/-/~-~-~/g;
}
# Preserve actual tags
$string =~ s/ /~!!SS!!~/g;
$string =~ s/</~!~!!~/g;
$string =~ s/>/~!!~!~/g;
if ($encoding eq $utf8) {
# Handle consecutive entities first
my @entities = ($string =~ /&#\d+;[&#\d+;]{2,}/g);
foreach my $entity (@entities) {
my $decoded_intity = decode_entities($entity);
$string =~ s/$entity/$decoded_intity/g;
}
# Fix the string finally
utf8::decode($string);
$string = decode_entities($string);
utf8::encode($string);
} else {
eval {$string = decode($encoding, $string)};
if ($@) {
say "Error found: $@";
if (!prompt('next')) {
exit;
}
}
$string = decode_entities($string);
$string = encode($utf8, $string);
}
# Restore special commas and dashes
if ($type_config) {
$string =~ s/~-~-~/-/g;
$string =~ s/~,~,~/,/g;
}
# Restore escaped tags
$string =~ s/~!!~!~/>/g;
$string =~ s/~!~!!~/</g;
$string =~ s/~!!SS!!~/ /g;
return $string;
}
sub source_data
{
my ($module, $data, $opt) = @_;
my ($language_source, $type, $target, $target_help, $source_file, $source_file_, $exists);
$language_source = $opt->{'language-source'};
$type = $data->{'type'};
$target_help = '';
if ($type eq 'config' || $type eq 'uconfig' || $type eq 'module') {
$language_source = $language_source ne 'en' ? "$type.info.$language_source" : "$type.info";
}
if ($type eq 'help') {
$target_help = '/help';
}
$target = "$data->{'path'}/$module$target_help";
$source_file = "$target/$type/$language_source";
$source_file_ = "$target/$language_source";
$exists =
(-d $target &&
!-l $target &&
((-r $source_file && !-l $source_file) || (-r $source_file_ && !-l $source_file_) || $target_help)) ||
0;
if (-r $source_file && !-l $source_file) {
$target .= "/$type";
} elsif (-r $source_file_ && !-l $source_file_) {
$source_file = $source_file_;
}
return ($exists, $target, $source_file);
}
# Returns an array of supported languages,
# taken from Webmin's lang_list.txt file.
sub list_languages_local
{
my ($data) = @_;
my ($key, $value, $options, $language, @languages);
open(my $LANG, "$data->{'path'}/lang_list.txt");
while (<$LANG>) {
if (/^(.*=\w+)\s+(.*)/) {
$language = { 'desc' => $2 };
foreach $options (split(/,/, $1)) {
if ($options =~ /^([^=]+)=(.*)$/) {
$key = $1;
$value = $2;
$key =~ s/^\s+|\s+$//g;
$value =~ s/^\s+|\s+$//g;
$language->{$key} = $value;
}
}
push(@languages, $language);
}
}
close($LANG);
@languages = sort {$a->{'desc'} cmp $b->{'desc'}} @languages;
return wantarray ? @languages : \@languages;
}
# Prepare the string that is going to be sent to translator
sub translate_substitute
{
my ($value, $opt) = @_;
my $format = $opt->{'translate-format'};
$format = 'html' if ($opt->{'translate-format-html'});
$value = language_transcode($value, 'utf-8', $opt);
# Preserve un-quoted $1, $2, $3 in strings, which are broken in so different ways, in different languages differently
if ($format eq 'text') {
$value =~ s/(?<!['|"|`|“|«|=|?|&])(\$(\d+))/%$2/g;
}
# Preserve path in strings
elsif ($format eq 'html') {
$value =~ s/<tt>/<tt translate="no">/gm;
$value =~
s/(?:(^(?<!<)(\/[\w+].*?),|^(?<!<)(\/[\w+].*?)\.|(?<!<)(\/[\w+].*?) |(?<!<)(\/[\w+].*?)$))/<span translate="no">"$1"<\/span>/g;
}
return $value;
}
# Perform white sorcery on returned string from translator,
# as it seems to be breaking quite a lot of things
sub translated_substitute
{
my ($translated, $original, $code, $rtl, $opt) = @_;
my $format = $opt->{'translate-format'};
$format = 'html' if ($opt->{'translate-format-html'});
my $remove_spaces = sub {
my ($str) = @_;
$str =~ s/[ ]+//g;
return $str;
};
# Fix broken by translator HTML closing tags
$translated =~ s/<\/[ ]*(\w+)>/<\/$1>/g;
$translated =~ s/<[ ](.*?)[ ]/<$1/g;
if ($format eq 'text') {
# Unescape preserved, un-quoted $1, $2, $3
$translated =~ s/\%[ ]+(\d+)/ \$$1 /gi;
# If replacement is changed to localized version
$translated =~ s/%(\d+)/ \$$1/gi;
# If the string starts with $1 and contains a space
$translated =~ s/(^[ ]+\$)/\$/gi;
# Get rid from undesirable spaces in parentheses
$translated =~ s/([ ]+\))/)/gi;
$translated =~ s/([ ]+\))/)/gi;
$translated =~ s/(\([ ]+)/(/gi;
$translated =~ s/(\([ ]+)/(/gi;
# Print actual values with percent sign
$translated =~ s/\([ ]+\$(\d+)[ ]*%\)/(\$$1 %)/gi;
# The following, is abnormal way to make things work, around of the bugs produced by Google Translate API for (bg).
if ($code eq 'bg') {
if ($original =~ /\$(\d+)/ && $translated !~ /\$(\d+)/) {
$translated =~ s/(\d+)/\$$1/g;
}
}
# For RTL substitute `\d ٪` with `$\d`
if ($rtl) {
$translated =~ s/(٪[ ]+(\d+))/\$$2/g;
# Fix stuck, consecutive $2$1
$translated =~ s/\$(\d+)\$(\d+)/\$$1 \$$2/g;
# Urdu returned as ٪1
if ($code eq 'ur') {
$translated =~ s/((\d+)٪)/\$$2/g;
}
}
# Language specific fixes
if ($code eq 'th') {
$translated =~ s/(([3-9])%)/\$$2/g;
}
if ($code eq 'ro') {
$translated =~ s/ (([1-9])%) / \$$2 /g;
}
} elsif ($format eq 'html') {
# Unescape path in strings
$translated =~ s/<span.*?translate.*?>(.*?)<.*?>/$1/gi;
# Remove any escapes as returned by translator, when run in HTML mode
$translated =~ s/"//gi;
$translated =~ s/'/'/gi;
$translated =~ s/<tt translate="no">/<tt>/gm;
}
# Restore destroyed tags
$translated =~ s/<[ ]*(?:(\?\w+|((?![br|hr|p|tt|pre|ul|li|ol])\w+).*?))[ ]*>(.*?)<.*?>/<$1>$3<\/$2>/gi;
$translated =~ s/([ ]*)\$[ ]*(\d+)/$1\$$2/g;
$translated =~ s/(['|"|`|“|«])[ ]*\$(\d+)[ ]*(['|"|`|“|»])/$1\$$2$3/g;
$translated =~ s/(<.*?>)[ ]*(.*?)[ ]*(<.*?>)/$1$2$3/g;
$translated =~ s/\$(\d+)[ ]*([:|:])[ ]*\$(\d+)[ ]*/ \$$1:\$$3 /g;
$translated =~ s/\$(\d+)[ ]*:[ ]*\$(\d+)/\$$1:\$$2/g;
$translated =~ s/(\p{L})\$(\d+)[ ]+/$1 \$$2 /g;
$translated =~ s/(\p{L})[ ]+([:|:]){2}[ ]+(\p{L})/$1::$3/g;
# Remove any whitespaces
$translated =~ s/([ ]+)/ /g;
# Fix trailing dot, which is separated from a word
$translated =~ s/(.)[ ]+\./$1./g;
# Fix trailing comma, which is separated from a word
$translated =~ s/(.)[ ]+,/$1,/g;
# Preserve inner formatting for tag's attrs
$translated =~ s/<(\w+)[ ]+(\w+)(.*?)(=)[ ]*(.*?)[ ]*(\w+)/<$1 $2=$5$6/g;
# Last .. should also be preceded by space
$translated =~ s/[ ]*(\.\.)$/ ../g;
# Preserve dates example formatting
$translated =~ s/(\p{L}{2,4}) \/ (\p{L}{2,3}) \/ (\p{L}{2,4}) (\(.*?\))/$1\/$2\/$3 $4/g;
# If initial value contains in the end of the string `text : ` or `text : $1`,
# then print it as such and not as `text: ` or `text: $1`
if ($original =~ /(?:([ ]+:[ ]*$|[ ]+:[ ]*\$\d+$))/) {
$translated =~ s/(?:(:[ ]*[^:]+$|:$))/ $1/g;
# Fix incorrectly positioned $1 :$2
if ($translated =~ /\$(\d+)[ ]+:\$\d+/) {
$translated =~ s/\$(\d+)[ ]+:\$(\d+)/\$$1 : \$$2/;
}
}
# If initial string contains `/$1/` then format translated accordingly
if ($original =~ /\/\$\d+\//) {
$translated =~ s/\/[ ]*\$(\d+)[ ]*\//\/\$$1\//g;
}
# If initial string contains `($2 %)` then format translated accordingly
if ($original =~ /\(\$(\d+)[ ]+%\)/) {
$translated =~ s/\(\$(\d+)[ ]*%\)/(\$$1 %)/g;
}
# Always fix properly included path
if ($original =~ /<tt>[\/|~\/].*?<\/tt>/) {
$translated =~ s/(<tt>)([\/|~\/].*?)(<\/tt>)/$1@{[&$remove_spaces($2)]}$3/g;
}
# Always consider `/` to be a delimiter and replace ` / ` to `/`
if ($original =~ /\w+\/\w+/) {
$translated =~ s/[ ]+(\/)[ ]+/$1/g;
}
# Treat `+` it is not not as ` + `
if ($original =~ /\w+\+\w+/) {
$translated =~ s/[ ]+(\+)[ ]+/$1/g;
}
# The following should have no spaces, e.g. `<tt>uid=joe,dc=my-domain,dc=com</tt>`
$translated =~ s/(<tt>)(uid[ ]*=.*?)(<\/tt>)/$1@{[&$remove_spaces($2)]}$3/g;
# If original string contains ` % ` make sure output also has it
if ($original =~ / % /) {
$translated =~ s/[ ]*%[ ]*/ % /g;
$translated =~ s/[ ]*٪[ ]*/ ٪ /g;
}
# If original string contains `${VAR}`, fix the output
if ($original =~ /\$\{/ || $original =~ /\{\$/) {
$translated =~ s/\$ \{/\${/g;
$translated =~ s/\{\$ /{\$/g;
$translated =~ s/\.\.\. /.../g;
}
# If original value on template file contained escaped HTML entities, do the same on translated string
if ($original =~ /<|>/ && $original !~ /<|>/ && $translated =~ /<|>/) {
$translated =~ s/</</g;
$translated =~ s/>/>/g;
}
# If original string contains "\n" character, fix it, as it's broken in text mode translations
if ($original =~ /\\n/) {
$translated =~
s/(?|(\\\s*n\s*\\\s*n\s*\\\s*n\s*\\\s*n\s*\\\s*n)|(\\\s*n\s*\\\s*n\s*\\\s*n\s*\\\s*n)|(\\\s*n\s*\\\s*n\s*\\\s*n)|(\\\s*n\s*\\\s*n)|(\\\s*n))/@{[lc(&$remove_spaces($1))]}/gi;
}
return $translated;
}
# Make actual translation using Google Translate API
sub translate
{
my ($data, $opt, $target, $value) = @_;
my $source = $opt->{'language-source'};
my $format = $opt->{'translate-format'};
$format = 'html' if ($opt->{'translate-format-html'});
# Updating Google Translate API token to avoid expiration
my $time = time();
if ((($time - $data->{'start_time'}) / 60) > 10) {
say CYAN, "Updating Google Translate API token..", RESET;
$data->{'token'} = get_google_translate_token();
$data->{'start_time'} = $time;
}
my $token = $data->{'token'};
# Replace language code to match what translator expects
$target =~ s/_/-/;
my $tr;
my $rsp = "https://translation.googleapis.com/language/translate/v2";
my $rsh = { 'Authorization' => "Bearer \"@{[trim($token)]}\"",
'User-Agent' => 'curl/7.29.1',
'Content-Type' => 'application/json; charset=utf-8', };
my $rsc = "{ 'source': '" . $source . "', 'target': '" . $target . "', 'format': '" . $format . "', 'q': '" .
quotemeta($value) . "'}";
my $rs = HTTP::Tiny->new()->request('POST' => $rsp, { 'headers' => $rsh, 'content' => $rsc });
my $ts = $rs->{'success'};
my $tc = $rs->{'content'};
# Exctract translation on success
if ($ts) {
$tr = JSON::PP->new->decode($rs->{'content'});
$tr = $tr->{'data'}->{'translations'}[0]->{'translatedText'};
return $tr;
}
# On error just try again in 5 seconds
else {
say YELLOW, "Error: Stopped when translating `$target` language", RESET;
print RED, "Error: Google Translator - $tc", RESET;
say CYAN, "Retrying automatically in 5 seconds ..", RESET;
sleep 5;
my $translated = translate($data, $opt, $target, $value);
return $translated;
}
}
# Run transcoding or translation of module(s) for the very first time
sub go
{
my ($opt, $data) = @_;
my ($module, $language);
my $path = $data->{'path'};
my $type = $data->{'type'};
my $token = $data->{'token'};
my $modules = $data->{'modules'};
my $language_source = $opt->{'language-source'};
my $language_source_encoding = $opt->{'language-source-encoding'};
my $language_source_ignore_auto = $opt->{'language-source-ignore-auto'};
my $language_target = $opt->{'language-target'};
my $language_target_exclude = $opt->{'language-target-exclude'};
my $keys_exclude = $opt->{'keys-exclude'};
my $keys_force_translate = $opt->{'keys-force-translate'};
my $keys_force_html = $opt->{'keys-force-html'};
my $keys_test = $opt->{'keys-test'};
my $values_fix = $opt->{'values-fix'};
my $git_commit = $opt->{'git-commit'};
my $verbose = $opt->{'verbose'} || @{$keys_test};
my $mode_sync = $opt->{'mode'} ne 'full';
my $mode_transcode = $opt->{'mode'} eq 'transcode';
my $verbose_silent_mode = $mode_sync && $verbose != 2;
if ($type eq 'help') {
foreach $module (@{$modules}) {
my @module_help;
my @module_help_info;
my $ext = '.html';
my $utf8 = '.UTF-8';
my $old_map = $language_source_encoding eq 'map';
my $only_transcode = $opt->{'only-transcode'};
my ($exists, $help_path) = source_data($module, $data, $opt);
# Check if there has been something to process, if not print a message
my $output;
# Build targets first
talk_log(("Transcoding/translating " . CYAN BOLD, $module, RESET . " module's help .."), $data, 1);
talk_log(("" . CYAN . " .. Building list of help files to process" . RESET . ""), $data, 1);
find(
{
wanted => sub {
my $found = $File::Find::name;
my $found_nonutf8 = $found =~ s/$utf8//r;
my $found_nonutf8_big5 = $found_nonutf8 =~ s/$ext/.Big5$ext/r;
my $found_nonutf8_euc = $found_nonutf8 =~ s/$ext/.euc$ext/r;
my $found_relative_name = $found =~ s/$data->{'path'}\/$module\/$type\///r;
# Check if file exists in both UTF-8 and original encoding, if so, keep original only
my @found_nonutf8 = ($found_nonutf8, $found_nonutf8_big5, $found_nonutf8_euc);
foreach my $found_nonutf8 (@found_nonutf8) {
if (-r $found_nonutf8 && $found ne $found_nonutf8) {
talk_log(
("" . RED .
" .. Deleting duplicate file in UTF-8 encoding..\n - $found_relative_name" .
RESET . ""
),
$data,
1);
unlink($found);
} elsif (-f $found) {
push(@module_help, $found);
push(@module_help_info, $found_relative_name);
}
}
},
},
$help_path);
@module_help = sort(uniq(@module_help));
@module_help_info = sort(uniq(@module_help_info));
if (scalar(@module_help)) {
talk_log(
("" . GREEN . " .. Found help files to process" .
RESET . " \n - @{[join(\"\n - \", @module_help_info)]}"
),
$data,
1);
}
# Store template files
my @templates = ();
# Store language codes, for which human translations have been done
my @help_translated_language_codes = ();
foreach $language (@{ $data->{'languages_source_list'} }) {
# Get target language code and other attributes
my $code = $language->{'lang'};
my $code_ = language_map($code);
my $code__ = $code_ =~ s/\.(euc|Big5)//r;
my $rtl = $language->{'rtl'};
# Skip translating source, base language
next if ($code eq $language_source);
# Process only user defined languages or do all; do not process excluded languages
if ($only_transcode) {
next if language_disallowed($code, $opt);
}
# Transcode each help file first
foreach my $help_file (@module_help) {
my $source;
if ($help_file =~
/(?|\.($code__|$code).(UTF-8)\.html|\.($code__|$code).(euc)\.html|\.($code__|$code).(Big5)\.html|\.($code__|$code)\.html)/)
{
my $e_lang = $1;
my $e_attr = $2 || '';
$e_lang = "$e_lang.$e_attr" if ($e_attr);
# Final file name to be writtten
my $help_file_write = $help_file =~ s/$e_lang/$code/r;
my $help_file_write_short = $help_file_write =~ s/.*\/(.+)$/$1/r;
my $help_file_short = $help_file =~ s/.*\/(.+)$/$1/r;
# Search for old format files and encodings, and convert at first
if ($old_map) {
# Rename, if old style format
if ($code ne $e_lang || $e_attr) {
talk_log(
("" . YELLOW .
" .. Renaming help file to new format - " . RED . "$help_file_short" .
RESET . " --> " . GREEN . "$help_file_write_short" . RESET . "" . RESET . ""
),
$data,
1);
rename_file($help_file, $help_file_write);