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 if (-f "$locales_dir/missing") {
116 require "$locales_dir/missing" ;
117 unlink "$locales_dir/missing";
119 if (-f "$locales_dir/lost") {
120 require "$locales_dir/lost";
121 unlink "$locales_dir/lost";
124 my %old_texts = %{ $self->{texts} || {} };
126 handle_file(@{ $_ }) for @progfiles;
127 handle_file(@{ $_ }) for @dbplfiles;
128 scanmenu($_) for @menufiles;
131 for my $file_name (grep { /\.(?:js|html)$/i } 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 for my $string (@new_missing) {
180 print "new string '$string' in files:\n";
183 apply { s{^(?:\.\./)+}{} }
184 grep { $cached{$_}{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 $menu = YAML::LoadFile($file);
522 for my $node (@$menu) {
523 # possible for override files
524 next unless exists $node->{name};
526 $locale{$node->{name}} = 1;
527 $alllocales{$node->{name}} = 1;
528 $cached{$file}{all}{$node->{name}} = 1;
533 # we only need to do this for auth atm, because only auth scripts can include new rights, which are translateable
536 my $dbu = SL::DBUpgrade2->new(auth => $auth, path => '../../sql/Pg-upgrade2-auth');
538 for my $upgrade ($dbu->sort_dbupdate_controls) {
539 for my $string (@{ $upgrade->{locales} || [] }) {
540 $locale{$string} = 1;
541 $alllocales{$string} = 1;
542 $cached{$upgrade->{tag}}{all}{$string} = 1;
547 sub unescape_template_string {
558 return if defined $cached{$file};
560 my %plugins = ( 'loaded' => { }, 'needed' => { } );
562 if (!open(IN, '<:encoding(utf8)', $file)) {
563 print "E: template file '$file' not found\n";
570 while (my $line = <IN>) {
573 while ($line =~ m/\[\%[^\w]*use[^\w]+(\w+)[^\w]*?\%\]/gi) {
574 $plugins{loaded}->{$1} = 1;
577 while ($line =~ m/\[\%[^\w]*(\w+)\.\w+\(/g) {
579 $plugins{needed}->{$plugin} = 1 if (first { $_ eq $plugin } qw(HTML LxERP JavaScript JSON L P));
582 $plugins{needed}->{T8} = 1 if $line =~ m/\[\%.*\|.*\$T8/;
584 while ($line =~ m/(?: # Start von Variante 1: LxERP.t8('...'); ohne darumliegende [% ... %]-Tags
585 (LxERP\.t8)\( # LxERP.t8( ::Parameter $1::
586 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $2::
587 (.*?) # Der zu übersetzende String ::Parameter $3::
588 (?<!\\)\2 # Ende des zu übersetzenden Strings
589 | # Start von Variante 2: [% '...' | $T8 %]
590 \[\% # Template-Start-Tag
591 [\-~#]? # Whitespace-Unterdrückung
592 \s* # Optional beliebig viele Whitespace
593 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $4::
594 (.*?) # Der zu übersetzende String ::Parameter $5::
595 (?<!\\)\4 # Ende des zu übersetzenden Strings
596 \s*\|\s* # Pipe-Zeichen mit optionalen Whitespace davor und danach
597 (\$T8) # Filteraufruf ::Parameter $6::
598 .*? # Optionale Argumente für den Filter
600 [\-~#]? # Whitespace-Unterdrückung
601 \%\] # Template-Ende-Tag
604 my $module = $1 || $6;
605 my $string = $3 || $5;
606 print "Found filter >>>$string<<<\n" if $debug;
607 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
609 $string = unescape_template_string($string);
610 $cached{$file}{all}{$string} = 1;
611 $cached{$file}{html}{$string} = 1;
612 $cached{$file}{submit}{$string} = 1 if $PREMATCH =~ /$submitsearch/;
613 $plugins{needed}->{T8} = 1 if $module eq '$T8';
614 $plugins{needed}->{LxERP} = 1 if $module eq 'LxERP.t8';
617 while ($line =~ m/\[\% # Template-Start-Tag
618 [\-~#]* # Whitespace-Unterdrückung
619 \s* # Optional beliebig viele Whitespace
620 (?: # Die erkannten Template-Direktiven
625 \s+ # Mindestens ein Whitespace
626 [\'\"]? # Anfang des Dateinamens
627 ([^\s]+) # Beliebig viele Nicht-Whitespaces -- Dateiname
628 \.(html|js) # Endung ".html" oder ".js", ansonsten kann es der Name eines Blocks sein
630 my $new_file_name = "$basedir/templates/webpages/$1.$2";
631 $cached{$file}{scanh}{$new_file_name} = 1;
632 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
638 foreach my $plugin (keys %{ $plugins{needed} }) {
639 next if ($plugins{loaded}->{$plugin});
640 print "E: " . strip_base($file) . " requires the Template plugin '$plugin', but is not loaded with '[\% USE $plugin \%]'.\n";
643 # copy back into global arrays
644 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
645 $locale{$_} = 1 for keys %{$cached{$file}{html}};
646 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
648 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
650 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
653 sub scan_javascript_file {
656 open(my $fh, '<:encoding(utf8)', $file) || die('can not open file: '. $file);
658 while( my $line = readline($fh) ) {
669 my $text = unescape_template_string($2);
671 $jslocale{$text} = 1;
672 $alllocales{$text} = 1;
678 sub search_unused_htmlfiles {
679 my @unscanned_dirs = ('../../templates/webpages');
681 while (scalar @unscanned_dirs) {
682 my $dir = shift @unscanned_dirs;
684 foreach my $entry (<$dir/*>) {
686 push @unscanned_dirs, $entry;
688 } elsif (!$ignore_unused_templates{strip_base($entry)} && -f $entry && !$referenced_html_files{$entry}) {
689 print "W: unused HTML template: " . strip_base($entry) . "\n";
697 my $s = "$_[0]"; # Create a copy of the string.
700 $s =~ s|templates/webpages/||;
707 $val =~ s/(\'|\\$)/\\$1/g;
708 return "'" . $val . "'";
713 $val =~ s/(\"|\\$)/\\$1/g;
714 return '"'. $val .'"';
718 my $key = _single_quote(shift);
719 my $text = _single_quote(shift);
721 my $template = $params{template} || qq| %-29s => %s,\n|;
722 my $fh = $params{fh} || croak 'need filehandle in _print_line';
724 print $fh sprintf $template, $key, $text;
730 my $file = $params{file} || croak 'need filename in generate_file';
731 my $header = $params{header};
732 my $lines = $params{data_sub};
733 my $data_name = $params{data_name};
734 my @delim = split //, ($params{delim} || '{}');
736 open my $fh, '>:encoding(utf8)', $file or die "$! : $file";
738 print $fh "#!/usr/bin/perl\n# -*- coding: utf-8; -*-\n# vim: fenc=utf-8\n\nuse utf8;\n\n";
739 print $fh $header, "\n" if $header;
740 print $fh "$data_name = $delim[0]\n" if $data_name;
744 print $fh qq|$delim[1];\n\n1;\n|;
752 locales.pl - Collect strings for translation in kivitendo
756 locales.pl [options] lang_code
759 -n, --no-custom-files Do not process files whose name contains "_"
760 -c, --check-files Run extended checks on HTML files
761 -f, --filenames Show the filenames where new strings where found
762 -v, --verbose Be more verbose
763 -h, --help Show this help
769 =item B<-n>, B<--no-custom-files>
771 Do not process files whose name contains "_", e.g. "custom_io.pl".
773 =item B<-c>, B<--check-files>
775 Run extended checks on the usage of templates. This can be used to
776 discover HTML templates that are never used as well as the usage of
777 non-existing HTML templates.
779 =item B<-v>, B<--verbose>
787 This script collects strings from Perl files, the menu files and
788 HTML templates and puts them into the file "all" for translation.