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.
15 unshift(@INC, $FindBin::Bin . '/../modules/override'); # Use our own versions of various modules (e.g. YAML).
16 push (@INC, $FindBin::Bin . '/..');
17 push (@INC, $FindBin::Bin . '/../modules/fallback'); # Only use our own versions of modules if there's no system version.
24 use File::Slurp qw(slurp);
28 use List::MoreUtils qw(apply);
29 use List::Util qw(first);
32 use YAML::Loader (); # YAML tries to load Y:L at runtime, but can't find it after we chdir'ed
34 use SL::System::Process;
36 $OUTPUT_AUTOFLUSH = 1;
47 my $basedir = "../..";
48 my $locales_dir = ".";
49 my $bindir = "$basedir/bin/mozilla";
50 my @progdirs = ( "$basedir/SL" );
51 my @menufiles = glob("${basedir}/menus/*/*");
52 my @javascript_dirs = ($basedir .'/js', $basedir .'/templates/webpages');
53 my $javascript_output_dir = $basedir .'/js';
54 my $submitsearch = qr/type\s*=\s*[\"\']?submit/i;
59 my %ignore_unused_templates = (
60 map { $_ => 1 } qw(ct/testpage.html oe/periodic_invoices_email.txt part/testpage.html t/render.html t/render.js task_server/failure_notification_email.txt
61 failed_background_jobs_report/email.txt)
64 my (%referenced_html_files, %locale, %htmllocale, %alllocales, %cached, %submit, %jslocale);
65 my ($ALL_HEADER, $MISSING_HEADER, $LOST_HEADER);
70 my ($top_dir_name) = @_;
77 tie my %dir_h, 'IO::Dir', $dir_name;
79 push @files, grep { -f } map { "${dir_name}/${_}" } keys %dir_h;
80 my @sub_dirs = grep { -d } map { "${dir_name}/${_}" } grep { ! m/^\.\.?$/ } keys %dir_h;
82 $finder->($_) for @sub_dirs;
85 $finder->($top_dir_name);
91 # overwrite existing entries with the ones from 'missing'
92 $self->{texts}->{$_} = $missing->{$_} for grep { $missing->{$_} } keys %alllocales;
94 # try to set missing entries from lost ones
95 my %lost_by_text = map { ($_->{text} => $_->{translation}) } @lost;
96 $self->{texts}->{$_} = $lost_by_text{$_} for grep { !$self->{texts}{$_} } keys %alllocales;
99 my @bindir_files = find_files($bindir);
100 my @progfiles = map { m:^(.+)/([^/]+)$:; [ $2, $1 ] } grep { /\.pl$/ && !/_custom/ } @bindir_files;
101 my @customfiles = grep /_custom/, @bindir_files;
103 push @progfiles, map { m:^(.+)/([^/]+)$:; [ $2, $1 ] } grep { /\.pm$/ } map { find_files($_) } @progdirs;
105 # put customized files into @customfiles
109 foreach my $sub_dir ("Pg-upgrade2", "Pg-upgrade2-auth") {
110 my $dir = "$basedir/sql/$sub_dir";
111 tie %dir_h, 'IO::Dir', $dir;
112 push @dbplfiles, map { [ $_, $dir ] } grep { /\.pl$/ } keys %dir_h;
115 # slurp the translations in
116 if (-f "$locales_dir/all") {
117 require "$locales_dir/all";
119 # load custom translation (more_texts)
120 for my $file (glob("${locales_dir}/more/*")) {
121 if (open my $in, "<", "$file") {
126 $self->{more_texts_temp}{$_} = $self->{more_texts}{$_} for keys %{ $self->{more_texts} };
129 $self->{more_texts} = delete $self->{more_texts_temp};
131 if (-f "$locales_dir/missing") {
132 require "$locales_dir/missing" ;
133 unlink "$locales_dir/missing";
135 if (-f "$locales_dir/lost") {
136 require "$locales_dir/lost";
137 unlink "$locales_dir/lost";
140 my %old_texts = %{ $self->{texts} || {} };
142 handle_file(@{ $_ }) for @progfiles;
143 handle_file(@{ $_ }) for @dbplfiles;
144 scanmenu($_) for @menufiles;
147 for my $file_name (grep { /\.(?:js|html)$/i } map({find_files($_)} @javascript_dirs)) {
148 scan_javascript_file($file_name);
151 # merge entries to translate with entries from files 'missing' and 'lost'
156 file => "$locales_dir/all",
157 header => $ALL_HEADER,
158 data_name => '$self->{texts}',
159 data_sub => sub { _print_line($_, $self->{texts}{$_}, @_) for sort keys %alllocales },
162 open(my $js_file, '>:encoding(utf8)', $javascript_output_dir .'/locale/'. $locale .'.js') || die;
163 print $js_file 'namespace("kivi").setupLocale({';
165 for my $key (sort(keys(%jslocale))) {
166 print $js_file ((!$first_entry ? ',' : '') ."\n". _double_quote($key) .':'. _double_quote($self->{texts}{$key}));
169 print $js_file ("\n");
170 print $js_file ('});'."\n");
173 foreach my $text (keys %$missing) {
174 if ($locale{$text} || $htmllocale{$text}) {
175 unless ($self->{texts}{$text}) {
176 $self->{texts}{$text} = $missing->{$text};
182 # calc and generate missing
183 # don't add missing ones if we have a translation in more_texts
184 my @new_missing = grep { !$self->{more_texts}{$_} && !$self->{texts}{$_} } sort keys %alllocales;
188 my %existing_lc = map { (lc $_ => $_) } grep { $self->{texts}->{$_} } keys %{ $self->{texts} };
189 foreach my $entry (@new_missing) {
190 my $other = $existing_lc{lc $entry};
191 print "W: No entry for '${entry}' exists, but there is one with different case: '${other}'\n" if $other;
196 for my $string (@new_missing) {
197 print "new string '$string' in files:\n";
200 apply { s{^(?:\.\./)+}{} }
201 grep { $cached{$_}{all}{$string} }
207 file => "$locales_dir/missing",
208 header => $MISSING_HEADER,
209 data_name => '$missing',
210 data_sub => sub { _print_line($_, '', @_) for @new_missing },
214 # calc and generate lost
215 while (my ($text, $translation) = each %old_texts) {
216 next if ($alllocales{$text});
217 push @lost, { 'text' => $text, 'translation' => $translation };
221 splice @lost, 0, (scalar @lost - 50) if (scalar @lost > 50);
223 file => "$locales_dir/lost",
224 header => $LOST_HEADER,
226 data_name => '@lost',
228 _print_line($_->{text}, $_->{translation}, @_, template => " { 'text' => %s, 'translation' => %s },\n") for @lost;
233 my $trlanguage = slurp("$locales_dir/LANGUAGE");
236 search_unused_htmlfiles() if $opt_c;
238 my $count = scalar keys %alllocales;
239 my $notext = scalar @new_missing;
240 my $per = sprintf("%.1f", ($count - $notext) / $count * 100);
241 print "\n$trlanguage - ${per}%";
242 print " - $notext/$count missing" if $notext;
251 # These are all the texts to build the translations files.
252 # The file has the form of 'english text' => 'foreign text',
253 # you can add the translation in this file or in the 'missing' file
254 # run locales.pl from this directory to rebuild the translation files
256 $MISSING_HEADER = <<EOL;
257 # add the missing texts and run locales.pl to rebuild
259 $LOST_HEADER = <<EOL;
260 # The last 50 text strings, that have been removed.
261 # This file has been auto-generated by locales.pl. Please don't edit!
268 my ($opt_no_c, $ignore_for_compatiblity);
271 'no-custom-files' => \$opt_n,
272 'check-files' => \$ignore_for_compatiblity,
273 'no-check-files' => \$opt_no_c,
274 'verbose' => \$opt_v,
275 'filenames' => \$opt_f,
289 pod2usage(-exitstatus => 0, -verbose => 2);
294 my $arg = shift @ARGV;
296 foreach my $dir ("../locale/$arg", "locale/$arg", "../$arg", $arg) {
297 next unless -d $dir && -f "$dir/all" && -f "$dir/LANGUAGE";
306 print "The locale directory '$arg' could not be found.\n";
310 } elsif (!-f 'all' || !-f 'LANGUAGE') {
311 print "locales.pl was not called from a locale/* subdirectory,\n"
312 . "and no locale directory name was given.\n";
316 $locale ||= (grep { $_ } split m:/:, getcwd())[-1];
321 my ($file, $dir) = @_;
322 print "\n$file" if $opt_v;
326 &scanfile("$dir/$file");
328 # scan custom_{module}.pl or {login}_{module}.pl files
329 foreach my $customfile (@customfiles) {
330 if ($customfile =~ /_$file/) {
331 if (-f "$dir/$customfile") {
332 &scanfile("$dir/$customfile");
340 sub extract_text_between_parenthesis {
341 my ($fh, $line) = @_;
342 my ($inside_string, $pos, $text, $quote_next) = (undef, 0, "", 0);
345 if (length($line) <= $pos) {
347 return ($text, "") unless ($line);
351 my $cur_char = substr($line, $pos, 1);
353 if (!$inside_string) {
354 if ((length($line) >= ($pos + 3)) && (substr($line, $pos, 2)) eq "qq") {
355 $inside_string = substr($line, $pos + 2, 1);
358 } elsif ((length($line) >= ($pos + 2)) &&
359 (substr($line, $pos, 1) eq "q")) {
360 $inside_string = substr($line, $pos + 1, 1);
363 } elsif (($cur_char eq '"') || ($cur_char eq '\'')) {
364 $inside_string = $cur_char;
366 } elsif (($cur_char eq ")") || ($cur_char eq ',')) {
367 return ($text, substr($line, $pos + 1));
372 $text .= '\\' unless $cur_char eq "'";
376 } elsif ($cur_char eq '\\') {
379 } elsif ($cur_char eq $inside_string) {
380 undef($inside_string);
393 my $dont_include_subs = shift;
394 my $scanned_files = shift;
399 $scanned_files = {} unless ($scanned_files);
400 return if ($scanned_files->{$file});
401 $scanned_files->{$file} = 1;
403 if (!defined $cached{$file}) {
405 return unless (-f "$file");
407 my $fh = new FileHandle;
408 open $fh, '<:encoding(utf8)', $file or die "$! : $file";
410 my ($is_submit, $line_no, $sub_line_no) = (0, 0, 0);
413 last if /^\s*__END__/;
417 # is this another file
418 if (/require\s+\W.*\.pl/) {
420 $newfile =~ s/require\s+\W//;
421 $newfile =~ s|bin/mozilla||;
422 $cached{$file}{scan}{"$bindir/$newfile"} = 1;
423 } elsif (/use\s+SL::([\w:]*)/) {
426 $cached{$file}{scannosubs}{"../../SL/${module}.pm"} = 1;
429 # Some calls to render() are split over multiple lines. Deal
431 while (/(?:parse_html_template2?|render)\s*\( *$/) {
436 # is this a template call?
437 if (/(?:parse_html_template2?|render)\s*\(\s*[\"\']([\w\/]+)\s*[\"\']/) {
438 my $new_file_base = "$basedir/templates/webpages/$1.";
439 if (/parse_html_template2/) {
440 print "E: " . strip_base($file) . " is still using 'parse_html_template2' for " . strip_base("${new_file_base}html") . ".\n";
444 foreach my $ext (qw(html js json)) {
445 my $new_file = "${new_file_base}${ext}";
447 $cached{$file}{scanh}{$new_file} = 1;
453 if ($opt_c && !$found_one) {
454 print "W: missing HTML template: " . strip_base($new_file_base) . "{html,json,js} (referenced from " . strip_base($file) . ")\n";
463 my ($null, $country) = split(/,/);
464 $country =~ s/^ +[\"\']//;
465 $country =~ s/[\"\'].*//;
471 # is it a submit button before $locale->
472 if (/$submitsearch/) {
474 if ($` !~ /locale->text/) {
476 $sub_line_no = $line_no;
481 if (/ (?: locale->text | \b t8 ) \b .*? \(/x) {
488 ($string, $_) = extract_text_between_parenthesis($fh, $postmatch);
491 # if there is no $ in the string record it
492 unless (($string =~ /\$\D.*/) || ("" eq $string)) {
494 # this guarantees one instance of string
495 $cached{$file}{locale}{$string} = 1;
497 # this one is for all the locales
498 $cached{$file}{all}{$string} = 1;
500 # is it a submit button before $locale->
502 $cached{$file}{submit}{$string} = 1;
505 } elsif ($postmatch =~ />/) {
509 # exit loop if there are no more locales on this line
510 ($rc) = ($postmatch =~ /locale->text | \b t8/x);
512 if ( ($postmatch =~ />/)
513 || (!$found && ($sub_line_no != $line_no) && />/)) {
523 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
524 $locale{$_} = 1 for keys %{$cached{$file}{locale}};
525 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
527 scanfile($_, 0, $scanned_files) for keys %{$cached{$file}{scan}};
528 scanfile($_, 1, $scanned_files) for keys %{$cached{$file}{scannosubs}};
529 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
531 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
537 my $menu = YAML::LoadFile($file);
539 for my $node (@$menu) {
540 # possible for override files
541 next unless exists $node->{name};
543 $locale{$node->{name}} = 1;
544 $alllocales{$node->{name}} = 1;
545 $cached{$file}{all}{$node->{name}} = 1;
550 # we only need to do this for auth atm, because only auth scripts can include new rights, which are translateable
553 my $dbu = SL::DBUpgrade2->new(auth => $auth, path => SL::System::Process->exe_dir . '/sql/Pg-upgrade2-auth');
555 for my $upgrade ($dbu->sort_dbupdate_controls) {
556 for my $string (@{ $upgrade->{locales} || [] }) {
557 $locale{$string} = 1;
558 $alllocales{$string} = 1;
559 $cached{$upgrade->{tag}}{all}{$string} = 1;
564 sub unescape_template_string {
575 return if defined $cached{$file};
577 my %plugins = ( 'loaded' => { }, 'needed' => { } );
579 if (!open(IN, '<:encoding(utf8)', $file)) {
580 print "E: template file '$file' not found\n";
587 while (my $line = <IN>) {
590 while ($line =~ m/\[\%[^\w]*use[^\w]+(\w+)[^\w]*?\%\]/gi) {
591 $plugins{loaded}->{$1} = 1;
594 while ($line =~ m/\[\%[^\w]*(\w+)\.\w+\(/g) {
596 $plugins{needed}->{$plugin} = 1 if (first { $_ eq $plugin } qw(HTML LxERP JavaScript JSON L P));
599 $plugins{needed}->{T8} = 1 if $line =~ m/\[\%.*\|.*\$T8/;
601 while ($line =~ m/(?: # Start von Variante 1: LxERP.t8('...'); ohne darumliegende [% ... %]-Tags
602 (LxERP\.t8)\( # LxERP.t8( ::Parameter $1::
603 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $2::
604 (.*?) # Der zu übersetzende String ::Parameter $3::
605 (?<!\\)\2 # Ende des zu übersetzenden Strings
606 | # Start von Variante 2: [% '...' | $T8 %]
607 \[\% # Template-Start-Tag
608 [\-~#]? # Whitespace-Unterdrückung
609 \s* # Optional beliebig viele Whitespace
610 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $4::
611 (.*?) # Der zu übersetzende String ::Parameter $5::
612 (?<!\\)\4 # Ende des zu übersetzenden Strings
613 \s*\|\s* # Pipe-Zeichen mit optionalen Whitespace davor und danach
614 (\$T8) # Filteraufruf ::Parameter $6::
615 .*? # Optionale Argumente für den Filter
617 [\-~#]? # Whitespace-Unterdrückung
618 \%\] # Template-Ende-Tag
621 my $module = $1 || $6;
622 my $string = $3 || $5;
623 print "Found filter >>>$string<<<\n" if $debug;
624 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
626 $string = unescape_template_string($string);
627 $cached{$file}{all}{$string} = 1;
628 $cached{$file}{html}{$string} = 1;
629 $cached{$file}{submit}{$string} = 1 if $PREMATCH =~ /$submitsearch/;
630 $plugins{needed}->{T8} = 1 if $module eq '$T8';
631 $plugins{needed}->{LxERP} = 1 if $module eq 'LxERP.t8';
634 while ($line =~ m/\[\% # Template-Start-Tag
635 [\-~#]* # Whitespace-Unterdrückung
636 \s* # Optional beliebig viele Whitespace
637 (?: # Die erkannten Template-Direktiven
642 \s+ # Mindestens ein Whitespace
643 [\'\"]? # Anfang des Dateinamens
644 ([^\s]+) # Beliebig viele Nicht-Whitespaces -- Dateiname
645 \.(html|js) # Endung ".html" oder ".js", ansonsten kann es der Name eines Blocks sein
647 my $new_file_name = "$basedir/templates/webpages/$1.$2";
648 $cached{$file}{scanh}{$new_file_name} = 1;
649 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
655 foreach my $plugin (keys %{ $plugins{needed} }) {
656 next if ($plugins{loaded}->{$plugin});
657 print "E: " . strip_base($file) . " requires the Template plugin '$plugin', but is not loaded with '[\% USE $plugin \%]'.\n";
660 # copy back into global arrays
661 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
662 $locale{$_} = 1 for keys %{$cached{$file}{html}};
663 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
665 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
667 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
670 sub scan_javascript_file {
673 open(my $fh, '<:encoding(utf8)', $file) || die('can not open file: '. $file);
675 while( my $line = readline($fh) ) {
686 my $text = unescape_template_string($2);
688 $jslocale{$text} = 1;
689 $alllocales{$text} = 1;
695 sub search_unused_htmlfiles {
696 my @unscanned_dirs = ('../../templates/webpages');
698 while (scalar @unscanned_dirs) {
699 my $dir = shift @unscanned_dirs;
701 foreach my $entry (<$dir/*>) {
703 push @unscanned_dirs, $entry;
705 } elsif (!$ignore_unused_templates{strip_base($entry)} && -f $entry && !$referenced_html_files{$entry}) {
706 print "W: unused HTML template: " . strip_base($entry) . "\n";
714 my $s = "$_[0]"; # Create a copy of the string.
717 $s =~ s|templates/webpages/||;
724 $val =~ s/(\'|\\$)/\\$1/g;
725 return "'" . $val . "'";
730 $val =~ s/(\"|\\$)/\\$1/g;
731 return '"'. $val .'"';
735 my $key = _single_quote(shift);
736 my $text = _single_quote(shift);
738 my $template = $params{template} || qq| %-29s => %s,\n|;
739 my $fh = $params{fh} || croak 'need filehandle in _print_line';
741 print $fh sprintf $template, $key, $text;
747 my $file = $params{file} || croak 'need filename in generate_file';
748 my $header = $params{header};
749 my $lines = $params{data_sub};
750 my $data_name = $params{data_name};
751 my @delim = split //, ($params{delim} || '{}');
753 open my $fh, '>:encoding(utf8)', $file or die "$! : $file";
755 print $fh "#!/usr/bin/perl\n# -*- coding: utf-8; -*-\n# vim: fenc=utf-8\n\nuse utf8;\n\n";
756 print $fh $header, "\n" if $header;
757 print $fh "$data_name = $delim[0]\n" if $data_name;
761 print $fh qq|$delim[1];\n\n1;\n|;
769 locales.pl - Collect strings for translation in kivitendo
773 locales.pl [options] lang_code
776 -n, --no-custom-files Do not process files whose name contains "_"
777 -c, --check-files Run extended checks on HTML files
778 -f, --filenames Show the filenames where new strings where found
779 -v, --verbose Be more verbose
780 -h, --help Show this help
786 =item B<-n>, B<--no-custom-files>
788 Do not process files whose name contains "_", e.g. "custom_io.pl".
790 =item B<-c>, B<--check-files>
792 Run extended checks on the usage of templates. This can be used to
793 discover HTML templates that are never used as well as the usage of
794 non-existing HTML templates.
796 =item B<-v>, B<--verbose>
804 This script collects strings from Perl files, the menu files and
805 HTML templates and puts them into the file "all" for translation.