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;
38 my $basedir = "../..";
39 my $locales_dir = ".";
40 my $bindir = "$basedir/bin/mozilla";
41 my @progdirs = ( "$basedir/SL" );
42 my @menufiles = <${basedir}/menus/*.ini>;
43 my @javascript_dirs = ($basedir .'/js', $basedir .'/templates/webpages');
44 my $javascript_output_dir = $basedir .'/js';
45 my $submitsearch = qr/type\s*=\s*[\"\']?submit/i;
50 my %ignore_unused_templates = (
51 map { $_ => 1 } qw(ct/testpage.html generic/autocomplete.html oe/periodic_invoices_email.txt part/testpage.html t/render.html t/render.js)
54 my (%referenced_html_files, %locale, %htmllocale, %alllocales, %cached, %submit, %jslocale);
55 my ($ALL_HEADER, $MISSING_HEADER, $LOST_HEADER);
60 my ($top_dir_name) = @_;
67 tie my %dir_h, 'IO::Dir', $dir_name;
69 push @files, grep { -f } map { "${dir_name}/${_}" } keys %dir_h;
70 my @sub_dirs = grep { -d } map { "${dir_name}/${_}" } grep { ! m/^\.\.?$/ } keys %dir_h;
72 $finder->($_) for @sub_dirs;
75 $finder->($top_dir_name);
81 # overwrite existing entries with the ones from 'missing'
82 $self->{texts}->{$_} = $missing->{$_} for grep { $missing->{$_} } keys %alllocales;
84 # try to set missing entries from lost ones
85 my %lost_by_text = map { ($_->{text} => $_->{translation}) } @lost;
86 $self->{texts}->{$_} = $lost_by_text{$_} for grep { !$self->{texts}{$_} } keys %alllocales;
89 my @bindir_files = find_files($bindir);
90 my @progfiles = map { m:^(.+)/([^/]+)$:; [ $2, $1 ] } grep { /\.pl$/ && !/_custom/ } @bindir_files;
91 my @customfiles = grep /_custom/, @bindir_files;
93 push @progfiles, map { m:^(.+)/([^/]+)$:; [ $2, $1 ] } grep { /\.pm$/ } map { find_files($_) } @progdirs;
95 # put customized files into @customfiles
101 tie %dir_h, 'IO::Dir', $basedir;
102 push @menufiles, map { "$basedir/$_" } grep { /.*_menu.ini$/ } keys %dir_h;
106 foreach my $sub_dir ("Pg-upgrade2", "Pg-upgrade2-auth") {
107 my $dir = "$basedir/sql/$sub_dir";
108 tie %dir_h, 'IO::Dir', $dir;
109 push @dbplfiles, map { [ $_, $dir ] } grep { /\.pl$/ } keys %dir_h;
112 # slurp the translations in
113 if (-f "$locales_dir/all") {
114 require "$locales_dir/all";
116 if (-f "$locales_dir/missing") {
117 require "$locales_dir/missing" ;
118 unlink "$locales_dir/missing";
120 if (-f "$locales_dir/lost") {
121 require "$locales_dir/lost";
122 unlink "$locales_dir/lost";
125 my %old_texts = %{ $self->{texts} || {} };
127 handle_file(@{ $_ }) for @progfiles;
128 handle_file(@{ $_ }) for @dbplfiles;
129 scanmenu($_) for @menufiles;
131 for my $file_name (map({find_files($_)} @javascript_dirs)) {
132 scan_javascript_file($file_name);
135 # merge entries to translate with entries from files 'missing' and 'lost'
140 file => "$locales_dir/all",
141 header => $ALL_HEADER,
142 data_name => '$self->{texts}',
143 data_sub => sub { _print_line($_, $self->{texts}{$_}, @_) for sort keys %alllocales },
146 open(my $js_file, '>:encoding(utf8)', $javascript_output_dir .'/locale/'. $locale .'.js') || die;
147 print $js_file 'namespace("kivi").setupLocale({';
149 for my $key (sort(keys(%jslocale))) {
150 print $js_file ((!$first_entry ? ',' : '') ."\n". _double_quote($key) .':'. _double_quote($self->{texts}{$key}));
153 print $js_file ("\n");
154 print $js_file ('});'."\n");
157 foreach my $text (keys %$missing) {
158 if ($locale{$text} || $htmllocale{$text}) {
159 unless ($self->{texts}{$text}) {
160 $self->{texts}{$text} = $missing->{$text};
166 # calc and generate missing
167 my @new_missing = grep { !$self->{texts}{$_} } sort keys %alllocales;
171 my %existing_lc = map { (lc $_ => $_) } grep { $self->{texts}->{$_} } keys %{ $self->{texts} };
172 foreach my $entry (@new_missing) {
173 my $other = $existing_lc{lc $entry};
174 print "W: No entry for '${entry}' exists, but there is one with different case: '${other}'\n" if $other;
179 file => "$locales_dir/missing",
180 header => $MISSING_HEADER,
181 data_name => '$missing',
182 data_sub => sub { _print_line($_, '', @_) for @new_missing },
186 # calc and generate lost
187 while (my ($text, $translation) = each %old_texts) {
188 next if ($alllocales{$text});
189 push @lost, { 'text' => $text, 'translation' => $translation };
193 splice @lost, 0, (scalar @lost - 50) if (scalar @lost > 50);
195 file => "$locales_dir/lost",
196 header => $LOST_HEADER,
198 data_name => '@lost',
200 _print_line($_->{text}, $_->{translation}, @_, template => " { 'text' => %s, 'translation' => %s },\n") for @lost;
205 my $trlanguage = slurp("$locales_dir/LANGUAGE");
208 search_unused_htmlfiles() if $opt_c;
210 my $count = scalar keys %alllocales;
211 my $notext = scalar @new_missing;
212 my $per = sprintf("%.1f", ($count - $notext) / $count * 100);
213 print "\n$trlanguage - ${per}%";
214 print " - $notext/$count missing" if $notext;
223 # These are all the texts to build the translations files.
224 # The file has the form of 'english text' => 'foreign text',
225 # you can add the translation in this file or in the 'missing' file
226 # run locales.pl from this directory to rebuild the translation files
228 $MISSING_HEADER = <<EOL;
229 # add the missing texts and run locales.pl to rebuild
231 $LOST_HEADER = <<EOL;
232 # The last 50 text strings, that have been removed.
233 # This file has been auto-generated by locales.pl. Please don't edit!
240 my ($opt_no_c, $ignore_for_compatiblity);
243 'no-custom-files' => \$opt_n,
244 'check-files' => \$ignore_for_compatiblity,
245 'no-check-files' => \$opt_no_c,
246 'verbose' => \$opt_v,
260 pod2usage(-exitstatus => 0, -verbose => 2);
265 my $arg = shift @ARGV;
267 foreach my $dir ("../locale/$arg", "locale/$arg", "../$arg", $arg) {
268 next unless -d $dir && -f "$dir/all" && -f "$dir/LANGUAGE";
277 print "The locale directory '$arg' could not be found.\n";
281 } elsif (!-f 'all' || !-f 'LANGUAGE') {
282 print "locales.pl was not called from a locale/* subdirectory,\n"
283 . "and no locale directory name was given.\n";
287 $locale ||= (grep { $_ } split m:/:, getcwd())[-1];
292 my ($file, $dir) = @_;
293 print "\n$file" if $opt_v;
297 &scanfile("$dir/$file");
299 # scan custom_{module}.pl or {login}_{module}.pl files
300 foreach my $customfile (@customfiles) {
301 if ($customfile =~ /_$file/) {
302 if (-f "$dir/$customfile") {
303 &scanfile("$dir/$customfile");
311 sub extract_text_between_parenthesis {
312 my ($fh, $line) = @_;
313 my ($inside_string, $pos, $text, $quote_next) = (undef, 0, "", 0);
316 if (length($line) <= $pos) {
318 return ($text, "") unless ($line);
322 my $cur_char = substr($line, $pos, 1);
324 if (!$inside_string) {
325 if ((length($line) >= ($pos + 3)) && (substr($line, $pos, 2)) eq "qq") {
326 $inside_string = substr($line, $pos + 2, 1);
329 } elsif ((length($line) >= ($pos + 2)) &&
330 (substr($line, $pos, 1) eq "q")) {
331 $inside_string = substr($line, $pos + 1, 1);
334 } elsif (($cur_char eq '"') || ($cur_char eq '\'')) {
335 $inside_string = $cur_char;
337 } elsif (($cur_char eq ")") || ($cur_char eq ',')) {
338 return ($text, substr($line, $pos + 1));
343 $text .= '\\' unless $cur_char eq "'";
347 } elsif ($cur_char eq '\\') {
350 } elsif ($cur_char eq $inside_string) {
351 undef($inside_string);
364 my $dont_include_subs = shift;
365 my $scanned_files = shift;
370 $scanned_files = {} unless ($scanned_files);
371 return if ($scanned_files->{$file});
372 $scanned_files->{$file} = 1;
374 if (!defined $cached{$file}) {
376 return unless (-f "$file");
378 my $fh = new FileHandle;
379 open $fh, "$file" or die "$! : $file";
381 my ($is_submit, $line_no, $sub_line_no) = (0, 0, 0);
384 last if /^\s*__END__/;
388 # is this another file
389 if (/require\s+\W.*\.pl/) {
391 $newfile =~ s/require\s+\W//;
392 $newfile =~ s|bin/mozilla||;
393 $cached{$file}{scan}{"$bindir/$newfile"} = 1;
394 } elsif (/use\s+SL::([\w:]*)/) {
397 $cached{$file}{scannosubs}{"../../SL/${module}.pm"} = 1;
400 # Some calls to render() are split over multiple lines. Deal
402 while (/(?:parse_html_template2?|render)\s*\( *$/) {
407 # is this a template call?
408 if (/(?:parse_html_template2?|render)\s*\(\s*[\"\']([\w\/]+)\s*[\"\']/) {
409 my $new_file_base = "$basedir/templates/webpages/$1.";
410 if (/parse_html_template2/) {
411 print "E: " . strip_base($file) . " is still using 'parse_html_template2' for " . strip_base("${new_file_base}html") . ".\n";
415 foreach my $ext (qw(html js json)) {
416 my $new_file = "${new_file_base}${ext}";
418 $cached{$file}{scanh}{$new_file} = 1;
424 if ($opt_c && !$found_one) {
425 print "W: missing HTML template: " . strip_base($new_file_base) . "{html,json,js} (referenced from " . strip_base($file) . ")\n";
434 my ($null, $country) = split(/,/);
435 $country =~ s/^ +[\"\']//;
436 $country =~ s/[\"\'].*//;
442 # is it a submit button before $locale->
443 if (/$submitsearch/) {
445 if ($` !~ /locale->text/) {
447 $sub_line_no = $line_no;
452 if (/ (?: locale->text | \b t8 ) \b .*? \(/x) {
459 ($string, $_) = extract_text_between_parenthesis($fh, $postmatch);
462 # if there is no $ in the string record it
463 unless (($string =~ /\$\D.*/) || ("" eq $string)) {
465 # this guarantees one instance of string
466 $cached{$file}{locale}{$string} = 1;
468 # this one is for all the locales
469 $cached{$file}{all}{$string} = 1;
471 # is it a submit button before $locale->
473 $cached{$file}{submit}{$string} = 1;
476 } elsif ($postmatch =~ />/) {
480 # exit loop if there are no more locales on this line
481 ($rc) = ($postmatch =~ /locale->text | \b t8/x);
483 if ( ($postmatch =~ />/)
484 || (!$found && ($sub_line_no != $line_no) && />/)) {
494 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
495 $locale{$_} = 1 for keys %{$cached{$file}{locale}};
496 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
498 scanfile($_, 0, $scanned_files) for keys %{$cached{$file}{scan}};
499 scanfile($_, 1, $scanned_files) for keys %{$cached{$file}{scannosubs}};
500 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
502 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
508 my $fh = new FileHandle;
509 open $fh, "$file" or die "$! : $file";
511 my @a = grep m/^\[/, <$fh>;
515 grep { s/(\[|\])//g } @a;
517 foreach my $item (@a) {
518 my @b = split /--/, $item;
519 foreach my $string (@b) {
521 $locale{$string} = 1;
522 $alllocales{$string} = 1;
528 sub unescape_template_string {
539 return if defined $cached{$file};
541 my %plugins = ( 'loaded' => { }, 'needed' => { } );
543 if (!open(IN, $file)) {
544 print "E: template file '$file' not found\n";
551 while (my $line = <IN>) {
554 while ($line =~ m/\[\%[^\w]*use[^\w]+(\w+)[^\w]*?\%\]/gi) {
555 $plugins{loaded}->{$1} = 1;
558 while ($line =~ m/\[\%[^\w]*(\w+)\.\w+\(/g) {
560 $plugins{needed}->{$plugin} = 1 if (first { $_ eq $plugin } qw(HTML LxERP JavaScript JSON L P));
563 $plugins{needed}->{T8} = 1 if $line =~ m/\[\%.*\|.*\$T8/;
565 while ($line =~ m/(?: # Start von Variante 1: LxERP.t8('...'); ohne darumliegende [% ... %]-Tags
566 (LxERP\.t8)\( # LxERP.t8( ::Parameter $1::
567 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $2::
568 (.*?) # Der zu übersetzende String ::Parameter $3::
569 (?<!\\)\2 # Ende des zu übersetzenden Strings
570 | # Start von Variante 2: [% '...' | $T8 %]
571 \[\% # Template-Start-Tag
572 [\-~#]? # Whitespace-Unterdrückung
573 \s* # Optional beliebig viele Whitespace
574 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $4::
575 (.*?) # Der zu übersetzende String ::Parameter $5::
576 (?<!\\)\4 # Ende des zu übersetzenden Strings
577 \s*\|\s* # Pipe-Zeichen mit optionalen Whitespace davor und danach
578 (\$T8) # Filteraufruf ::Parameter $6::
579 .*? # Optionale Argumente für den Filter
581 [\-~#]? # Whitespace-Unterdrückung
582 \%\] # Template-Ende-Tag
585 my $module = $1 || $6;
586 my $string = $3 || $5;
587 print "Found filter >>>$string<<<\n" if $debug;
588 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
590 $string = unescape_template_string($string);
591 $cached{$file}{all}{$string} = 1;
592 $cached{$file}{html}{$string} = 1;
593 $cached{$file}{submit}{$string} = 1 if $PREMATCH =~ /$submitsearch/;
594 $plugins{needed}->{T8} = 1 if $module eq '$T8';
595 $plugins{needed}->{LxERP} = 1 if $module eq 'LxERP.t8';
598 while ($line =~ m/\[\% # Template-Start-Tag
599 [\-~#]? # Whitespace-Unterdrückung
600 \s* # Optional beliebig viele Whitespace
601 (?: # Die erkannten Template-Direktiven
606 \s+ # Mindestens ein Whitespace
607 [\'\"]? # Anfang des Dateinamens
608 ([^\s]+) # Beliebig viele Nicht-Whitespaces -- Dateiname
609 \.html # Endung ".html", ansonsten kann es der Name eines Blocks sein
611 my $new_file_name = "$basedir/templates/webpages/$1.html";
612 $cached{$file}{scanh}{$new_file_name} = 1;
613 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
619 foreach my $plugin (keys %{ $plugins{needed} }) {
620 next if ($plugins{loaded}->{$plugin});
621 print "E: " . strip_base($file) . " requires the Template plugin '$plugin', but is not loaded with '[\% USE $plugin \%]'.\n";
624 # copy back into global arrays
625 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
626 $locale{$_} = 1 for keys %{$cached{$file}{html}};
627 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
629 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
631 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
634 sub scan_javascript_file {
637 open(my $fh, $file) || die('can not open file: '. $file);
639 while( my $line = readline($fh) ) {
650 my $text = unescape_template_string($2);
652 $jslocale{$text} = 1;
653 $alllocales{$text} = 1;
659 sub search_unused_htmlfiles {
660 my @unscanned_dirs = ('../../templates/webpages');
662 while (scalar @unscanned_dirs) {
663 my $dir = shift @unscanned_dirs;
665 foreach my $entry (<$dir/*>) {
667 push @unscanned_dirs, $entry;
669 } elsif (!$ignore_unused_templates{strip_base($entry)} && -f $entry && !$referenced_html_files{$entry}) {
670 print "W: unused HTML template: " . strip_base($entry) . "\n";
678 my $s = "$_[0]"; # Create a copy of the string.
681 $s =~ s|templates/webpages/||;
688 $val =~ s/(\'|\\$)/\\$1/g;
689 return "'" . $val . "'";
694 $val =~ s/(\"|\\$)/\\$1/g;
695 return '"'. $val .'"';
699 my $key = _single_quote(shift);
700 my $text = _single_quote(shift);
702 my $template = $params{template} || qq| %-29s => %s,\n|;
703 my $fh = $params{fh} || croak 'need filehandle in _print_line';
705 print $fh sprintf $template, $key, $text;
711 my $file = $params{file} || croak 'need filename in generate_file';
712 my $header = $params{header};
713 my $lines = $params{data_sub};
714 my $data_name = $params{data_name};
715 my @delim = split //, ($params{delim} || '{}');
717 open my $fh, '>:encoding(utf8)', $file or die "$! : $file";
719 print $fh "#!/usr/bin/perl\n# -*- coding: utf-8; -*-\n# vim: fenc=utf-8\n\nuse utf8;\n\n";
720 print $fh $header, "\n" if $header;
721 print $fh "$data_name = $delim[0]\n" if $data_name;
725 print $fh qq|$delim[1];\n\n1;\n|;
733 locales.pl - Collect strings for translation in kivitendo
737 locales.pl [options] lang_code
740 -n, --no-custom-files Do not process files whose name contains "_"
741 -c, --check-files Run extended checks on HTML files
742 -v, --verbose Be more verbose
743 -h, --help Show this help
749 =item B<-n>, B<--no-custom-files>
751 Do not process files whose name contains "_", e.g. "custom_io.pl".
753 =item B<-c>, B<--check-files>
755 Run extended checks on the usage of templates. This can be used to
756 discover HTML templates that are never used as well as the usage of
757 non-existing HTML templates.
759 =item B<-v>, B<--verbose>
767 This script collects strings from Perl files, the menu.ini file and
768 HTML templates and puts them into the file "all" for translation.