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::Util qw(first);
28 $OUTPUT_AUTOFLUSH = 1;
39 my $basedir = "../..";
40 my $locales_dir = ".";
41 my $bindir = "$basedir/bin/mozilla";
42 my @progdirs = ( "$basedir/SL" );
43 my @menufiles = <${basedir}/menus/*.ini>;
44 my @javascript_dirs = ($basedir .'/js', $basedir .'/templates/webpages');
45 my $javascript_output_dir = $basedir .'/js';
46 my $submitsearch = qr/type\s*=\s*[\"\']?submit/i;
51 my %ignore_unused_templates = (
52 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
53 failed_background_jobs_report/email.txt)
56 my (%referenced_html_files, %locale, %htmllocale, %alllocales, %cached, %submit, %jslocale);
57 my ($ALL_HEADER, $MISSING_HEADER, $LOST_HEADER);
62 my ($top_dir_name) = @_;
69 tie my %dir_h, 'IO::Dir', $dir_name;
71 push @files, grep { -f } map { "${dir_name}/${_}" } keys %dir_h;
72 my @sub_dirs = grep { -d } map { "${dir_name}/${_}" } grep { ! m/^\.\.?$/ } keys %dir_h;
74 $finder->($_) for @sub_dirs;
77 $finder->($top_dir_name);
83 # overwrite existing entries with the ones from 'missing'
84 $self->{texts}->{$_} = $missing->{$_} for grep { $missing->{$_} } keys %alllocales;
86 # try to set missing entries from lost ones
87 my %lost_by_text = map { ($_->{text} => $_->{translation}) } @lost;
88 $self->{texts}->{$_} = $lost_by_text{$_} for grep { !$self->{texts}{$_} } keys %alllocales;
91 my @bindir_files = find_files($bindir);
92 my @progfiles = map { m:^(.+)/([^/]+)$:; [ $2, $1 ] } grep { /\.pl$/ && !/_custom/ } @bindir_files;
93 my @customfiles = grep /_custom/, @bindir_files;
95 push @progfiles, map { m:^(.+)/([^/]+)$:; [ $2, $1 ] } grep { /\.pm$/ } map { find_files($_) } @progdirs;
97 # put customized files into @customfiles
103 tie %dir_h, 'IO::Dir', $basedir;
104 push @menufiles, map { "$basedir/$_" } grep { /.*_menu.ini$/ } keys %dir_h;
108 foreach my $sub_dir ("Pg-upgrade2", "Pg-upgrade2-auth") {
109 my $dir = "$basedir/sql/$sub_dir";
110 tie %dir_h, 'IO::Dir', $dir;
111 push @dbplfiles, map { [ $_, $dir ] } grep { /\.pl$/ } keys %dir_h;
114 # slurp the translations in
115 if (-f "$locales_dir/all") {
116 require "$locales_dir/all";
118 if (-f "$locales_dir/missing") {
119 require "$locales_dir/missing" ;
120 unlink "$locales_dir/missing";
122 if (-f "$locales_dir/lost") {
123 require "$locales_dir/lost";
124 unlink "$locales_dir/lost";
127 my %old_texts = %{ $self->{texts} || {} };
129 handle_file(@{ $_ }) for @progfiles;
130 handle_file(@{ $_ }) for @dbplfiles;
131 scanmenu($_) for @menufiles;
133 for my $file_name (grep { /\.(?:js|html)$/i } map({find_files($_)} @javascript_dirs)) {
134 scan_javascript_file($file_name);
137 # merge entries to translate with entries from files 'missing' and 'lost'
142 file => "$locales_dir/all",
143 header => $ALL_HEADER,
144 data_name => '$self->{texts}',
145 data_sub => sub { _print_line($_, $self->{texts}{$_}, @_) for sort keys %alllocales },
148 open(my $js_file, '>:encoding(utf8)', $javascript_output_dir .'/locale/'. $locale .'.js') || die;
149 print $js_file 'namespace("kivi").setupLocale({';
151 for my $key (sort(keys(%jslocale))) {
152 print $js_file ((!$first_entry ? ',' : '') ."\n". _double_quote($key) .':'. _double_quote($self->{texts}{$key}));
155 print $js_file ("\n");
156 print $js_file ('});'."\n");
159 foreach my $text (keys %$missing) {
160 if ($locale{$text} || $htmllocale{$text}) {
161 unless ($self->{texts}{$text}) {
162 $self->{texts}{$text} = $missing->{$text};
168 # calc and generate missing
169 my @new_missing = grep { !$self->{texts}{$_} } sort keys %alllocales;
173 my %existing_lc = map { (lc $_ => $_) } grep { $self->{texts}->{$_} } keys %{ $self->{texts} };
174 foreach my $entry (@new_missing) {
175 my $other = $existing_lc{lc $entry};
176 print "W: No entry for '${entry}' exists, but there is one with different case: '${other}'\n" if $other;
181 for my $string (@new_missing) {
182 print "new string '$string' in files:\n";
183 for my $file (keys %cached) {
184 print " $file", $/ if $cached{$file}{all}{$string};
190 file => "$locales_dir/missing",
191 header => $MISSING_HEADER,
192 data_name => '$missing',
193 data_sub => sub { _print_line($_, '', @_) for @new_missing },
197 # calc and generate lost
198 while (my ($text, $translation) = each %old_texts) {
199 next if ($alllocales{$text});
200 push @lost, { 'text' => $text, 'translation' => $translation };
204 splice @lost, 0, (scalar @lost - 50) if (scalar @lost > 50);
206 file => "$locales_dir/lost",
207 header => $LOST_HEADER,
209 data_name => '@lost',
211 _print_line($_->{text}, $_->{translation}, @_, template => " { 'text' => %s, 'translation' => %s },\n") for @lost;
216 my $trlanguage = slurp("$locales_dir/LANGUAGE");
219 search_unused_htmlfiles() if $opt_c;
221 my $count = scalar keys %alllocales;
222 my $notext = scalar @new_missing;
223 my $per = sprintf("%.1f", ($count - $notext) / $count * 100);
224 print "\n$trlanguage - ${per}%";
225 print " - $notext/$count missing" if $notext;
234 # These are all the texts to build the translations files.
235 # The file has the form of 'english text' => 'foreign text',
236 # you can add the translation in this file or in the 'missing' file
237 # run locales.pl from this directory to rebuild the translation files
239 $MISSING_HEADER = <<EOL;
240 # add the missing texts and run locales.pl to rebuild
242 $LOST_HEADER = <<EOL;
243 # The last 50 text strings, that have been removed.
244 # This file has been auto-generated by locales.pl. Please don't edit!
251 my ($opt_no_c, $ignore_for_compatiblity);
254 'no-custom-files' => \$opt_n,
255 'check-files' => \$ignore_for_compatiblity,
256 'no-check-files' => \$opt_no_c,
257 'verbose' => \$opt_v,
258 'filenames' => \$opt_f,
272 pod2usage(-exitstatus => 0, -verbose => 2);
277 my $arg = shift @ARGV;
279 foreach my $dir ("../locale/$arg", "locale/$arg", "../$arg", $arg) {
280 next unless -d $dir && -f "$dir/all" && -f "$dir/LANGUAGE";
289 print "The locale directory '$arg' could not be found.\n";
293 } elsif (!-f 'all' || !-f 'LANGUAGE') {
294 print "locales.pl was not called from a locale/* subdirectory,\n"
295 . "and no locale directory name was given.\n";
299 $locale ||= (grep { $_ } split m:/:, getcwd())[-1];
304 my ($file, $dir) = @_;
305 print "\n$file" if $opt_v;
309 &scanfile("$dir/$file");
311 # scan custom_{module}.pl or {login}_{module}.pl files
312 foreach my $customfile (@customfiles) {
313 if ($customfile =~ /_$file/) {
314 if (-f "$dir/$customfile") {
315 &scanfile("$dir/$customfile");
323 sub extract_text_between_parenthesis {
324 my ($fh, $line) = @_;
325 my ($inside_string, $pos, $text, $quote_next) = (undef, 0, "", 0);
328 if (length($line) <= $pos) {
330 return ($text, "") unless ($line);
334 my $cur_char = substr($line, $pos, 1);
336 if (!$inside_string) {
337 if ((length($line) >= ($pos + 3)) && (substr($line, $pos, 2)) eq "qq") {
338 $inside_string = substr($line, $pos + 2, 1);
341 } elsif ((length($line) >= ($pos + 2)) &&
342 (substr($line, $pos, 1) eq "q")) {
343 $inside_string = substr($line, $pos + 1, 1);
346 } elsif (($cur_char eq '"') || ($cur_char eq '\'')) {
347 $inside_string = $cur_char;
349 } elsif (($cur_char eq ")") || ($cur_char eq ',')) {
350 return ($text, substr($line, $pos + 1));
355 $text .= '\\' unless $cur_char eq "'";
359 } elsif ($cur_char eq '\\') {
362 } elsif ($cur_char eq $inside_string) {
363 undef($inside_string);
376 my $dont_include_subs = shift;
377 my $scanned_files = shift;
382 $scanned_files = {} unless ($scanned_files);
383 return if ($scanned_files->{$file});
384 $scanned_files->{$file} = 1;
386 if (!defined $cached{$file}) {
388 return unless (-f "$file");
390 my $fh = new FileHandle;
391 open $fh, '<:encoding(utf8)', $file or die "$! : $file";
393 my ($is_submit, $line_no, $sub_line_no) = (0, 0, 0);
396 last if /^\s*__END__/;
400 # is this another file
401 if (/require\s+\W.*\.pl/) {
403 $newfile =~ s/require\s+\W//;
404 $newfile =~ s|bin/mozilla||;
405 $cached{$file}{scan}{"$bindir/$newfile"} = 1;
406 } elsif (/use\s+SL::([\w:]*)/) {
409 $cached{$file}{scannosubs}{"../../SL/${module}.pm"} = 1;
412 # Some calls to render() are split over multiple lines. Deal
414 while (/(?:parse_html_template2?|render)\s*\( *$/) {
419 # is this a template call?
420 if (/(?:parse_html_template2?|render)\s*\(\s*[\"\']([\w\/]+)\s*[\"\']/) {
421 my $new_file_base = "$basedir/templates/webpages/$1.";
422 if (/parse_html_template2/) {
423 print "E: " . strip_base($file) . " is still using 'parse_html_template2' for " . strip_base("${new_file_base}html") . ".\n";
427 foreach my $ext (qw(html js json)) {
428 my $new_file = "${new_file_base}${ext}";
430 $cached{$file}{scanh}{$new_file} = 1;
436 if ($opt_c && !$found_one) {
437 print "W: missing HTML template: " . strip_base($new_file_base) . "{html,json,js} (referenced from " . strip_base($file) . ")\n";
446 my ($null, $country) = split(/,/);
447 $country =~ s/^ +[\"\']//;
448 $country =~ s/[\"\'].*//;
454 # is it a submit button before $locale->
455 if (/$submitsearch/) {
457 if ($` !~ /locale->text/) {
459 $sub_line_no = $line_no;
464 if (/ (?: locale->text | \b t8 ) \b .*? \(/x) {
471 ($string, $_) = extract_text_between_parenthesis($fh, $postmatch);
474 # if there is no $ in the string record it
475 unless (($string =~ /\$\D.*/) || ("" eq $string)) {
477 # this guarantees one instance of string
478 $cached{$file}{locale}{$string} = 1;
480 # this one is for all the locales
481 $cached{$file}{all}{$string} = 1;
483 # is it a submit button before $locale->
485 $cached{$file}{submit}{$string} = 1;
488 } elsif ($postmatch =~ />/) {
492 # exit loop if there are no more locales on this line
493 ($rc) = ($postmatch =~ /locale->text | \b t8/x);
495 if ( ($postmatch =~ />/)
496 || (!$found && ($sub_line_no != $line_no) && />/)) {
506 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
507 $locale{$_} = 1 for keys %{$cached{$file}{locale}};
508 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
510 scanfile($_, 0, $scanned_files) for keys %{$cached{$file}{scan}};
511 scanfile($_, 1, $scanned_files) for keys %{$cached{$file}{scannosubs}};
512 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
514 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
520 my $fh = new FileHandle;
521 open $fh, '<:encoding(utf8)', $file or die "$! : $file";
523 my @a = grep m/^\[/, <$fh>;
527 grep { s/(\[|\])//g } @a;
529 foreach my $item (@a) {
530 my @b = split /--/, $item;
531 foreach my $string (@b) {
533 $locale{$string} = 1;
534 $alllocales{$string} = 1;
540 sub unescape_template_string {
551 return if defined $cached{$file};
553 my %plugins = ( 'loaded' => { }, 'needed' => { } );
555 if (!open(IN, '<:encoding(utf8)', $file)) {
556 print "E: template file '$file' not found\n";
563 while (my $line = <IN>) {
566 while ($line =~ m/\[\%[^\w]*use[^\w]+(\w+)[^\w]*?\%\]/gi) {
567 $plugins{loaded}->{$1} = 1;
570 while ($line =~ m/\[\%[^\w]*(\w+)\.\w+\(/g) {
572 $plugins{needed}->{$plugin} = 1 if (first { $_ eq $plugin } qw(HTML LxERP JavaScript JSON L P));
575 $plugins{needed}->{T8} = 1 if $line =~ m/\[\%.*\|.*\$T8/;
577 while ($line =~ m/(?: # Start von Variante 1: LxERP.t8('...'); ohne darumliegende [% ... %]-Tags
578 (LxERP\.t8)\( # LxERP.t8( ::Parameter $1::
579 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $2::
580 (.*?) # Der zu übersetzende String ::Parameter $3::
581 (?<!\\)\2 # Ende des zu übersetzenden Strings
582 | # Start von Variante 2: [% '...' | $T8 %]
583 \[\% # Template-Start-Tag
584 [\-~#]? # Whitespace-Unterdrückung
585 \s* # Optional beliebig viele Whitespace
586 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $4::
587 (.*?) # Der zu übersetzende String ::Parameter $5::
588 (?<!\\)\4 # Ende des zu übersetzenden Strings
589 \s*\|\s* # Pipe-Zeichen mit optionalen Whitespace davor und danach
590 (\$T8) # Filteraufruf ::Parameter $6::
591 .*? # Optionale Argumente für den Filter
593 [\-~#]? # Whitespace-Unterdrückung
594 \%\] # Template-Ende-Tag
597 my $module = $1 || $6;
598 my $string = $3 || $5;
599 print "Found filter >>>$string<<<\n" if $debug;
600 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
602 $string = unescape_template_string($string);
603 $cached{$file}{all}{$string} = 1;
604 $cached{$file}{html}{$string} = 1;
605 $cached{$file}{submit}{$string} = 1 if $PREMATCH =~ /$submitsearch/;
606 $plugins{needed}->{T8} = 1 if $module eq '$T8';
607 $plugins{needed}->{LxERP} = 1 if $module eq 'LxERP.t8';
610 while ($line =~ m/\[\% # Template-Start-Tag
611 [\-~#]? # Whitespace-Unterdrückung
612 \s* # Optional beliebig viele Whitespace
613 (?: # Die erkannten Template-Direktiven
618 \s+ # Mindestens ein Whitespace
619 [\'\"]? # Anfang des Dateinamens
620 ([^\s]+) # Beliebig viele Nicht-Whitespaces -- Dateiname
621 \.(html|js) # Endung ".html" oder ".js", ansonsten kann es der Name eines Blocks sein
623 my $new_file_name = "$basedir/templates/webpages/$1.$2";
624 $cached{$file}{scanh}{$new_file_name} = 1;
625 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
631 foreach my $plugin (keys %{ $plugins{needed} }) {
632 next if ($plugins{loaded}->{$plugin});
633 print "E: " . strip_base($file) . " requires the Template plugin '$plugin', but is not loaded with '[\% USE $plugin \%]'.\n";
636 # copy back into global arrays
637 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
638 $locale{$_} = 1 for keys %{$cached{$file}{html}};
639 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
641 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
643 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
646 sub scan_javascript_file {
649 open(my $fh, '<:encoding(utf8)', $file) || die('can not open file: '. $file);
651 while( my $line = readline($fh) ) {
662 my $text = unescape_template_string($2);
664 $jslocale{$text} = 1;
665 $alllocales{$text} = 1;
671 sub search_unused_htmlfiles {
672 my @unscanned_dirs = ('../../templates/webpages');
674 while (scalar @unscanned_dirs) {
675 my $dir = shift @unscanned_dirs;
677 foreach my $entry (<$dir/*>) {
679 push @unscanned_dirs, $entry;
681 } elsif (!$ignore_unused_templates{strip_base($entry)} && -f $entry && !$referenced_html_files{$entry}) {
682 print "W: unused HTML template: " . strip_base($entry) . "\n";
690 my $s = "$_[0]"; # Create a copy of the string.
693 $s =~ s|templates/webpages/||;
700 $val =~ s/(\'|\\$)/\\$1/g;
701 return "'" . $val . "'";
706 $val =~ s/(\"|\\$)/\\$1/g;
707 return '"'. $val .'"';
711 my $key = _single_quote(shift);
712 my $text = _single_quote(shift);
714 my $template = $params{template} || qq| %-29s => %s,\n|;
715 my $fh = $params{fh} || croak 'need filehandle in _print_line';
717 print $fh sprintf $template, $key, $text;
723 my $file = $params{file} || croak 'need filename in generate_file';
724 my $header = $params{header};
725 my $lines = $params{data_sub};
726 my $data_name = $params{data_name};
727 my @delim = split //, ($params{delim} || '{}');
729 open my $fh, '>:encoding(utf8)', $file or die "$! : $file";
731 print $fh "#!/usr/bin/perl\n# -*- coding: utf-8; -*-\n# vim: fenc=utf-8\n\nuse utf8;\n\n";
732 print $fh $header, "\n" if $header;
733 print $fh "$data_name = $delim[0]\n" if $data_name;
737 print $fh qq|$delim[1];\n\n1;\n|;
745 locales.pl - Collect strings for translation in kivitendo
749 locales.pl [options] lang_code
752 -n, --no-custom-files Do not process files whose name contains "_"
753 -c, --check-files Run extended checks on HTML files
754 -f, --filenames Show the filenames where new strings where found
755 -v, --verbose Be more verbose
756 -h, --help Show this help
762 =item B<-n>, B<--no-custom-files>
764 Do not process files whose name contains "_", e.g. "custom_io.pl".
766 =item B<-c>, B<--check-files>
768 Run extended checks on the usage of templates. This can be used to
769 discover HTML templates that are never used as well as the usage of
770 non-existing HTML templates.
772 =item B<-v>, B<--verbose>
780 This script collects strings from Perl files, the menu.ini file and
781 HTML templates and puts them into the file "all" for translation.