3 # -n do not include custom_ scripts
4 # -v verbose mode, shows progress stuff
6 # this version of locles processes not only all required .pl files
7 # but also all parse_html_templated files.
13 unshift(@INC, 'modules/override'); # Use our own versions of various modules (e.g. YAML).
14 push (@INC, 'modules/fallback'); # Only use our own versions of modules if there's no system version.
21 use File::Slurp qw(slurp);
25 use List::MoreUtils qw(apply);
26 use List::Util qw(first);
29 use YAML::Loader (); # YAML tries to load Y:L at runtime, but can't find it after we chdir'ed
32 $OUTPUT_AUTOFLUSH = 1;
43 my $basedir = "../..";
44 my $locales_dir = ".";
45 my $bindir = "$basedir/bin/mozilla";
46 my @progdirs = ( "$basedir/SL" );
47 my @menufiles = glob("${basedir}/menus/*/*");
48 my @javascript_dirs = ($basedir .'/js', $basedir .'/templates/webpages');
49 my $javascript_output_dir = $basedir .'/js';
50 my $submitsearch = qr/type\s*=\s*[\"\']?submit/i;
55 my %ignore_unused_templates = (
56 map { $_ => 1 } qw(ct/testpage.html generic/autocomplete.html oe/periodic_invoices_email.txt part/testpage.html t/render.html t/render.js task_server/failure_notification_email.txt
57 failed_background_jobs_report/email.txt)
60 my (%referenced_html_files, %locale, %htmllocale, %alllocales, %cached, %submit, %jslocale);
61 my ($ALL_HEADER, $MISSING_HEADER, $LOST_HEADER);
66 my ($top_dir_name) = @_;
73 tie my %dir_h, 'IO::Dir', $dir_name;
75 push @files, grep { -f } map { "${dir_name}/${_}" } keys %dir_h;
76 my @sub_dirs = grep { -d } map { "${dir_name}/${_}" } grep { ! m/^\.\.?$/ } keys %dir_h;
78 $finder->($_) for @sub_dirs;
81 $finder->($top_dir_name);
87 # overwrite existing entries with the ones from 'missing'
88 $self->{texts}->{$_} = $missing->{$_} for grep { $missing->{$_} } keys %alllocales;
90 # try to set missing entries from lost ones
91 my %lost_by_text = map { ($_->{text} => $_->{translation}) } @lost;
92 $self->{texts}->{$_} = $lost_by_text{$_} for grep { !$self->{texts}{$_} } keys %alllocales;
95 my @bindir_files = find_files($bindir);
96 my @progfiles = map { m:^(.+)/([^/]+)$:; [ $2, $1 ] } grep { /\.pl$/ && !/_custom/ } @bindir_files;
97 my @customfiles = grep /_custom/, @bindir_files;
99 push @progfiles, map { m:^(.+)/([^/]+)$:; [ $2, $1 ] } grep { /\.pm$/ } map { find_files($_) } @progdirs;
101 # put customized files into @customfiles
105 foreach my $sub_dir ("Pg-upgrade2", "Pg-upgrade2-auth") {
106 my $dir = "$basedir/sql/$sub_dir";
107 tie %dir_h, 'IO::Dir', $dir;
108 push @dbplfiles, map { [ $_, $dir ] } grep { /\.pl$/ } keys %dir_h;
111 # slurp the translations in
112 if (-f "$locales_dir/all") {
113 require "$locales_dir/all";
115 # load custom translation (more_texts)
116 for my $file (glob("${locales_dir}/more/*")) {
117 if (open my $in, "<", "$file") {
122 $self->{more_texts_temp}{$_} = $self->{more_texts}{$_} for keys %{ $self->{more_texts} };
125 $self->{more_texts} = delete $self->{more_texts_temp};
127 if (-f "$locales_dir/missing") {
128 require "$locales_dir/missing" ;
129 unlink "$locales_dir/missing";
131 if (-f "$locales_dir/lost") {
132 require "$locales_dir/lost";
133 unlink "$locales_dir/lost";
136 my %old_texts = %{ $self->{texts} || {} };
138 handle_file(@{ $_ }) for @progfiles;
139 handle_file(@{ $_ }) for @dbplfiles;
140 scanmenu($_) for @menufiles;
143 for my $file_name (grep { /\.(?:js|html)$/i } map({find_files($_)} @javascript_dirs)) {
144 scan_javascript_file($file_name);
147 # merge entries to translate with entries from files 'missing' and 'lost'
152 file => "$locales_dir/all",
153 header => $ALL_HEADER,
154 data_name => '$self->{texts}',
155 data_sub => sub { _print_line($_, $self->{texts}{$_}, @_) for sort keys %alllocales },
158 open(my $js_file, '>:encoding(utf8)', $javascript_output_dir .'/locale/'. $locale .'.js') || die;
159 print $js_file 'namespace("kivi").setupLocale({';
161 for my $key (sort(keys(%jslocale))) {
162 print $js_file ((!$first_entry ? ',' : '') ."\n". _double_quote($key) .':'. _double_quote($self->{texts}{$key}));
165 print $js_file ("\n");
166 print $js_file ('});'."\n");
169 foreach my $text (keys %$missing) {
170 if ($locale{$text} || $htmllocale{$text}) {
171 unless ($self->{texts}{$text}) {
172 $self->{texts}{$text} = $missing->{$text};
178 # calc and generate missing
179 # don't add missing ones if we have a translation in more_texts
180 my @new_missing = grep { !$self->{more_texts}{$_} && !$self->{texts}{$_} } sort keys %alllocales;
184 my %existing_lc = map { (lc $_ => $_) } grep { $self->{texts}->{$_} } keys %{ $self->{texts} };
185 foreach my $entry (@new_missing) {
186 my $other = $existing_lc{lc $entry};
187 print "W: No entry for '${entry}' exists, but there is one with different case: '${other}'\n" if $other;
192 for my $string (@new_missing) {
193 print "new string '$string' in files:\n";
196 apply { s{^(?:\.\./)+}{} }
197 grep { $cached{$_}{all}{$string} }
203 file => "$locales_dir/missing",
204 header => $MISSING_HEADER,
205 data_name => '$missing',
206 data_sub => sub { _print_line($_, '', @_) for @new_missing },
210 # calc and generate lost
211 while (my ($text, $translation) = each %old_texts) {
212 next if ($alllocales{$text});
213 push @lost, { 'text' => $text, 'translation' => $translation };
217 splice @lost, 0, (scalar @lost - 50) if (scalar @lost > 50);
219 file => "$locales_dir/lost",
220 header => $LOST_HEADER,
222 data_name => '@lost',
224 _print_line($_->{text}, $_->{translation}, @_, template => " { 'text' => %s, 'translation' => %s },\n") for @lost;
229 my $trlanguage = slurp("$locales_dir/LANGUAGE");
232 search_unused_htmlfiles() if $opt_c;
234 my $count = scalar keys %alllocales;
235 my $notext = scalar @new_missing;
236 my $per = sprintf("%.1f", ($count - $notext) / $count * 100);
237 print "\n$trlanguage - ${per}%";
238 print " - $notext/$count missing" if $notext;
247 # These are all the texts to build the translations files.
248 # The file has the form of 'english text' => 'foreign text',
249 # you can add the translation in this file or in the 'missing' file
250 # run locales.pl from this directory to rebuild the translation files
252 $MISSING_HEADER = <<EOL;
253 # add the missing texts and run locales.pl to rebuild
255 $LOST_HEADER = <<EOL;
256 # The last 50 text strings, that have been removed.
257 # This file has been auto-generated by locales.pl. Please don't edit!
264 my ($opt_no_c, $ignore_for_compatiblity);
267 'no-custom-files' => \$opt_n,
268 'check-files' => \$ignore_for_compatiblity,
269 'no-check-files' => \$opt_no_c,
270 'verbose' => \$opt_v,
271 'filenames' => \$opt_f,
285 pod2usage(-exitstatus => 0, -verbose => 2);
290 my $arg = shift @ARGV;
292 foreach my $dir ("../locale/$arg", "locale/$arg", "../$arg", $arg) {
293 next unless -d $dir && -f "$dir/all" && -f "$dir/LANGUAGE";
302 print "The locale directory '$arg' could not be found.\n";
306 } elsif (!-f 'all' || !-f 'LANGUAGE') {
307 print "locales.pl was not called from a locale/* subdirectory,\n"
308 . "and no locale directory name was given.\n";
312 $locale ||= (grep { $_ } split m:/:, getcwd())[-1];
317 my ($file, $dir) = @_;
318 print "\n$file" if $opt_v;
322 &scanfile("$dir/$file");
324 # scan custom_{module}.pl or {login}_{module}.pl files
325 foreach my $customfile (@customfiles) {
326 if ($customfile =~ /_$file/) {
327 if (-f "$dir/$customfile") {
328 &scanfile("$dir/$customfile");
336 sub extract_text_between_parenthesis {
337 my ($fh, $line) = @_;
338 my ($inside_string, $pos, $text, $quote_next) = (undef, 0, "", 0);
341 if (length($line) <= $pos) {
343 return ($text, "") unless ($line);
347 my $cur_char = substr($line, $pos, 1);
349 if (!$inside_string) {
350 if ((length($line) >= ($pos + 3)) && (substr($line, $pos, 2)) eq "qq") {
351 $inside_string = substr($line, $pos + 2, 1);
354 } elsif ((length($line) >= ($pos + 2)) &&
355 (substr($line, $pos, 1) eq "q")) {
356 $inside_string = substr($line, $pos + 1, 1);
359 } elsif (($cur_char eq '"') || ($cur_char eq '\'')) {
360 $inside_string = $cur_char;
362 } elsif (($cur_char eq ")") || ($cur_char eq ',')) {
363 return ($text, substr($line, $pos + 1));
368 $text .= '\\' unless $cur_char eq "'";
372 } elsif ($cur_char eq '\\') {
375 } elsif ($cur_char eq $inside_string) {
376 undef($inside_string);
389 my $dont_include_subs = shift;
390 my $scanned_files = shift;
395 $scanned_files = {} unless ($scanned_files);
396 return if ($scanned_files->{$file});
397 $scanned_files->{$file} = 1;
399 if (!defined $cached{$file}) {
401 return unless (-f "$file");
403 my $fh = new FileHandle;
404 open $fh, '<:encoding(utf8)', $file or die "$! : $file";
406 my ($is_submit, $line_no, $sub_line_no) = (0, 0, 0);
409 last if /^\s*__END__/;
413 # is this another file
414 if (/require\s+\W.*\.pl/) {
416 $newfile =~ s/require\s+\W//;
417 $newfile =~ s|bin/mozilla||;
418 $cached{$file}{scan}{"$bindir/$newfile"} = 1;
419 } elsif (/use\s+SL::([\w:]*)/) {
422 $cached{$file}{scannosubs}{"../../SL/${module}.pm"} = 1;
425 # Some calls to render() are split over multiple lines. Deal
427 while (/(?:parse_html_template2?|render)\s*\( *$/) {
432 # is this a template call?
433 if (/(?:parse_html_template2?|render)\s*\(\s*[\"\']([\w\/]+)\s*[\"\']/) {
434 my $new_file_base = "$basedir/templates/webpages/$1.";
435 if (/parse_html_template2/) {
436 print "E: " . strip_base($file) . " is still using 'parse_html_template2' for " . strip_base("${new_file_base}html") . ".\n";
440 foreach my $ext (qw(html js json)) {
441 my $new_file = "${new_file_base}${ext}";
443 $cached{$file}{scanh}{$new_file} = 1;
449 if ($opt_c && !$found_one) {
450 print "W: missing HTML template: " . strip_base($new_file_base) . "{html,json,js} (referenced from " . strip_base($file) . ")\n";
459 my ($null, $country) = split(/,/);
460 $country =~ s/^ +[\"\']//;
461 $country =~ s/[\"\'].*//;
467 # is it a submit button before $locale->
468 if (/$submitsearch/) {
470 if ($` !~ /locale->text/) {
472 $sub_line_no = $line_no;
477 if (/ (?: locale->text | \b t8 ) \b .*? \(/x) {
484 ($string, $_) = extract_text_between_parenthesis($fh, $postmatch);
487 # if there is no $ in the string record it
488 unless (($string =~ /\$\D.*/) || ("" eq $string)) {
490 # this guarantees one instance of string
491 $cached{$file}{locale}{$string} = 1;
493 # this one is for all the locales
494 $cached{$file}{all}{$string} = 1;
496 # is it a submit button before $locale->
498 $cached{$file}{submit}{$string} = 1;
501 } elsif ($postmatch =~ />/) {
505 # exit loop if there are no more locales on this line
506 ($rc) = ($postmatch =~ /locale->text | \b t8/x);
508 if ( ($postmatch =~ />/)
509 || (!$found && ($sub_line_no != $line_no) && />/)) {
519 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
520 $locale{$_} = 1 for keys %{$cached{$file}{locale}};
521 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
523 scanfile($_, 0, $scanned_files) for keys %{$cached{$file}{scan}};
524 scanfile($_, 1, $scanned_files) for keys %{$cached{$file}{scannosubs}};
525 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
527 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
533 my $menu = YAML::LoadFile($file);
535 for my $node (@$menu) {
536 # possible for override files
537 next unless exists $node->{name};
539 $locale{$node->{name}} = 1;
540 $alllocales{$node->{name}} = 1;
541 $cached{$file}{all}{$node->{name}} = 1;
546 # we only need to do this for auth atm, because only auth scripts can include new rights, which are translateable
549 my $dbu = SL::DBUpgrade2->new(auth => $auth, path => '../../sql/Pg-upgrade2-auth');
551 for my $upgrade ($dbu->sort_dbupdate_controls) {
552 for my $string (@{ $upgrade->{locales} || [] }) {
553 $locale{$string} = 1;
554 $alllocales{$string} = 1;
555 $cached{$upgrade->{tag}}{all}{$string} = 1;
560 sub unescape_template_string {
571 return if defined $cached{$file};
573 my %plugins = ( 'loaded' => { }, 'needed' => { } );
575 if (!open(IN, '<:encoding(utf8)', $file)) {
576 print "E: template file '$file' not found\n";
583 while (my $line = <IN>) {
586 while ($line =~ m/\[\%[^\w]*use[^\w]+(\w+)[^\w]*?\%\]/gi) {
587 $plugins{loaded}->{$1} = 1;
590 while ($line =~ m/\[\%[^\w]*(\w+)\.\w+\(/g) {
592 $plugins{needed}->{$plugin} = 1 if (first { $_ eq $plugin } qw(HTML LxERP JavaScript JSON L P));
595 $plugins{needed}->{T8} = 1 if $line =~ m/\[\%.*\|.*\$T8/;
597 while ($line =~ m/(?: # Start von Variante 1: LxERP.t8('...'); ohne darumliegende [% ... %]-Tags
598 (LxERP\.t8)\( # LxERP.t8( ::Parameter $1::
599 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $2::
600 (.*?) # Der zu übersetzende String ::Parameter $3::
601 (?<!\\)\2 # Ende des zu übersetzenden Strings
602 | # Start von Variante 2: [% '...' | $T8 %]
603 \[\% # Template-Start-Tag
604 [\-~#]? # Whitespace-Unterdrückung
605 \s* # Optional beliebig viele Whitespace
606 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $4::
607 (.*?) # Der zu übersetzende String ::Parameter $5::
608 (?<!\\)\4 # Ende des zu übersetzenden Strings
609 \s*\|\s* # Pipe-Zeichen mit optionalen Whitespace davor und danach
610 (\$T8) # Filteraufruf ::Parameter $6::
611 .*? # Optionale Argumente für den Filter
613 [\-~#]? # Whitespace-Unterdrückung
614 \%\] # Template-Ende-Tag
617 my $module = $1 || $6;
618 my $string = $3 || $5;
619 print "Found filter >>>$string<<<\n" if $debug;
620 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
622 $string = unescape_template_string($string);
623 $cached{$file}{all}{$string} = 1;
624 $cached{$file}{html}{$string} = 1;
625 $cached{$file}{submit}{$string} = 1 if $PREMATCH =~ /$submitsearch/;
626 $plugins{needed}->{T8} = 1 if $module eq '$T8';
627 $plugins{needed}->{LxERP} = 1 if $module eq 'LxERP.t8';
630 while ($line =~ m/\[\% # Template-Start-Tag
631 [\-~#]* # Whitespace-Unterdrückung
632 \s* # Optional beliebig viele Whitespace
633 (?: # Die erkannten Template-Direktiven
638 \s+ # Mindestens ein Whitespace
639 [\'\"]? # Anfang des Dateinamens
640 ([^\s]+) # Beliebig viele Nicht-Whitespaces -- Dateiname
641 \.(html|js) # Endung ".html" oder ".js", ansonsten kann es der Name eines Blocks sein
643 my $new_file_name = "$basedir/templates/webpages/$1.$2";
644 $cached{$file}{scanh}{$new_file_name} = 1;
645 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
651 foreach my $plugin (keys %{ $plugins{needed} }) {
652 next if ($plugins{loaded}->{$plugin});
653 print "E: " . strip_base($file) . " requires the Template plugin '$plugin', but is not loaded with '[\% USE $plugin \%]'.\n";
656 # copy back into global arrays
657 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
658 $locale{$_} = 1 for keys %{$cached{$file}{html}};
659 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
661 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
663 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
666 sub scan_javascript_file {
669 open(my $fh, '<:encoding(utf8)', $file) || die('can not open file: '. $file);
671 while( my $line = readline($fh) ) {
682 my $text = unescape_template_string($2);
684 $jslocale{$text} = 1;
685 $alllocales{$text} = 1;
691 sub search_unused_htmlfiles {
692 my @unscanned_dirs = ('../../templates/webpages');
694 while (scalar @unscanned_dirs) {
695 my $dir = shift @unscanned_dirs;
697 foreach my $entry (<$dir/*>) {
699 push @unscanned_dirs, $entry;
701 } elsif (!$ignore_unused_templates{strip_base($entry)} && -f $entry && !$referenced_html_files{$entry}) {
702 print "W: unused HTML template: " . strip_base($entry) . "\n";
710 my $s = "$_[0]"; # Create a copy of the string.
713 $s =~ s|templates/webpages/||;
720 $val =~ s/(\'|\\$)/\\$1/g;
721 return "'" . $val . "'";
726 $val =~ s/(\"|\\$)/\\$1/g;
727 return '"'. $val .'"';
731 my $key = _single_quote(shift);
732 my $text = _single_quote(shift);
734 my $template = $params{template} || qq| %-29s => %s,\n|;
735 my $fh = $params{fh} || croak 'need filehandle in _print_line';
737 print $fh sprintf $template, $key, $text;
743 my $file = $params{file} || croak 'need filename in generate_file';
744 my $header = $params{header};
745 my $lines = $params{data_sub};
746 my $data_name = $params{data_name};
747 my @delim = split //, ($params{delim} || '{}');
749 open my $fh, '>:encoding(utf8)', $file or die "$! : $file";
751 print $fh "#!/usr/bin/perl\n# -*- coding: utf-8; -*-\n# vim: fenc=utf-8\n\nuse utf8;\n\n";
752 print $fh $header, "\n" if $header;
753 print $fh "$data_name = $delim[0]\n" if $data_name;
757 print $fh qq|$delim[1];\n\n1;\n|;
765 locales.pl - Collect strings for translation in kivitendo
769 locales.pl [options] lang_code
772 -n, --no-custom-files Do not process files whose name contains "_"
773 -c, --check-files Run extended checks on HTML files
774 -f, --filenames Show the filenames where new strings where found
775 -v, --verbose Be more verbose
776 -h, --help Show this help
782 =item B<-n>, B<--no-custom-files>
784 Do not process files whose name contains "_", e.g. "custom_io.pl".
786 =item B<-c>, B<--check-files>
788 Run extended checks on the usage of templates. This can be used to
789 discover HTML templates that are never used as well as the usage of
790 non-existing HTML templates.
792 =item B<-v>, B<--verbose>
800 This script collects strings from Perl files, the menu files and
801 HTML templates and puts them into the file "all" for translation.